The variables in ansible playbook doesn't persist between iterations in Jinja for loop

35 Views Asked by At

I can't understand why the list of list elements doesn't change between the iterations of a for loop inside the Jinja template.

For example, playbook:

- name: Create Config Files
  hosts: localhost
  gather_facts: false
  vars:
    conf_elements: 
#          Hostname|Octet|Mgmt|Location
      - ["host-s01","100","10","999"]
      - ["host-s02","100","20","999"]
      - ["host-s03","100","30","999"]
      - ["host-s04","100","40","999"]
  tasks:
    - name: Creata a New config file
      ansible.builtin.template:
        src: config-template_v0.1.j2
        dest: "./CNFG/{{item.0}}.txt"
      loop: "{{ conf_elements }}"

and the template (redacted):

{% for hostname, octet, mgmtip, id in conf_elements %}
!
conf t
hostname {{ hostname }}
mgmt 10.{{ octet }}.10.10
ip address 10.{{ octet }}.10.{{ mgmtip }}
descr location {{ id }}
!
{% endfor %}

What I'm expecting here in CNFG directory 4 files named respectively same as the hostnames (first list element in each list). Which actually works, but all 4 files are populated with the variables from the first list element basically all 4 files are the same and I can't understand why the past list variables are not used in Jinja.

Thanks for reading!

1

There are 1 best solutions below

1
jason s On

Not sure if you figured it out yet, but you're looping the conf_elements variable twice.

Once with the task (loop: "{{ conf_elements }}") And once with the template (which would print all 4 lines in the file).

So the solution is to use the same dot-notation you have when naming the file dest: "./CNFG/{{item.0}}.txt" within the template file.

So the template file should look like this:

!
conf t
hostname {{ item.0 }}
mgmt 10.{{ item.1 }}.10.10
ip address 10.{{ item.1 }}.10.{{ item.2 }}
descr location {{ item.3 }}
!