Ansible template module not parsing with_items variable

felichas picture felichas · Mar 29, 2017 · Viewed 8.3k times · Source

I am using a simple template with only variables in it. This is how my task looks like in my playbook (actually a role being used from my playbook):

- name: Ensure the conf file exists
  template:
    src: file.conf.j2
    dest: '/opt/file.conf'
  with_items: '{{ myrole }}'

I keep variables in group_vars. Any variable in file.conf.j2 will be expanded correctly, like {{ myrole_user }} but fails when expanding one of with_items variables, like {{ myrole.applicationName }}.

My group_vars looks like this:

myrole_user: regularuser
myrole:
  -  { applicationName: foo, othervar: bar }

And this is the Ansible error:

"msg": "AnsibleUndefinedVariable: 'list object' has no attribute 'applicationName'"

Answer

techraf picture techraf · Mar 29, 2017

You defined a list called myrole and then try to access a value of the key myrole.applicationName, so you get an error message that the list does not contain the key/attribute (which is true -- a list contains only an ordered set of elements).

Ansible with_ loops by default* set a variable named item containing the value of the element in the current iteration, so in the template you should refer to the item (not to the myrole variable which remains intact):

{{ item.applicationName }}

* you can change this with loop_var setting in the loop control section.