3

I have the following task (and a debug task):

- name: get list of error logs
  set_fact:
    centralised_logs: "{{ centralised_logs | default([]) | union([{'name': '{{ item }} error log'}])}}"
  with_items:
    - "one"
    - "two"
    - "three"

- debug: msg="{{ centralised_logs }}"

I'd expect the centralised_logs fact to accumulate an array of dictionaries that contain the interpolated strings in the union statement, but instead, I get the following (note that it works for the second and third items, but not the first):

TASK [nginx : get list of error logs] ******************************************
ok: [127.0.0.1] => (item=one)
ok: [127.0.0.1] => (item=two)
ok: [127.0.0.1] => (item=three)

TASK [nginx : debug] ***********************************************************
fatal: [127.0.0.1]: FAILED! => {"failed": true, "msg": "[{'name': u'two error log'}, {'name': u'three error log'}, {'name': u'{{ item }} error log'}]: 'item' is undefined"}

Why is the first value failing to be interpolated correctly?

Ansible version 2.1.0.0.

  • The square brackets [] mark the expression [{'name': '{{ item }} error log'}] as a list member, but the union filter operates on lists. So my guess would be that Ansible does not recoginse the expression as a list. I also don't understand why it works at all. – Henrik Pingel Sep 28 '16 at 18:37
4
+100

The problem is, that you try to use a the {{ variable }}-notation inside of another one.

A correct example would be

- name: get list of error logs
  set_fact:
    centralised_logs: "{{ centralised_logs | default([]) | union([{'name': item + ' error log'}])}}"
  with_items:
    - "one"
    - "two"
    - "three"

- debug: msg="{{ centralised_logs }}"

This produces the following output:

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        {
            "name": "one error log"
        }, 
        {
            "name": "two error log"
        }, 
        {
            "name": "three error log"
        }
    ]
}
  • Thanks for the solution, but why is my example working for the second and third items, and not the first? – Codebeef Sep 27 '16 at 8:36
  • I honestly don't know why it works at all – Christopher Perrin Sep 27 '16 at 9:53
  • Oh my gosh, just spent an hour trying 100 different concatenation techniques to append a dict to a list using set_fact and with_items... Using union() was the key, thanks for posting this answer! – geerlingguy Apr 27 '18 at 13:55
  • @geerlingguy glad I could help you – Christopher Perrin Apr 28 '18 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.