Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible template module not parsing with_items variable

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'"

like image 371
felichas Avatar asked Mar 29 '17 04:03

felichas


1 Answers

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.

like image 50
techraf Avatar answered Oct 14 '22 17:10

techraf