'Trouble passing Ansible dictionary to template

Wonder if anyone could help me here please.

I have an array in host_vars structured as so that I want to pass this into my template.

network:
  igb0:
      - address: x.x.x.x
        netmask: 255.255.255.0
      - address: x.x.x.x
        netmask: 255.255.255.0
      - address: x.x.x.x
        netmask: 255.255.255.0

I'm trying to put it in the vars section but I can't work out what format it needs to be in the vars section of the task.

vars:
    network: "{{ network }}"

Adding the following in the template:

{% for net in network %}
{% endfor %}

Results in an error:

FAILED! => {"changed": false, "msg": "AnsibleError: An unhandled exception occurred while templating '{{ network }}'. Error was a , original message: ...

Thanks in advance for any help.



Solution 1:[1]

For example, the playbook below

- hosts: localhost
  vars:
    network:
      igb0:
        - address: x.x.x.x
          netmask: 255.255.255.0
        - address: y.y.y.y
          netmask: 255.255.255.0
        - address: z.z.z.z
          netmask: 255.255.255.0
  tasks:
    - template:
        src: test.txt.j2
        dest: test.txt

and the template

shell> cat test.txt.j2
{% for k,v in network.items() %}
{{ k }}
{% for ip in v %}
{{ ip.address }} {{ ip.netmask }}
{% endfor %}
{% endfor %}

work as expected and create the file

shell> cat test.txt 
igb0
x.x.x.x 255.255.255.0
y.y.y.y 255.255.255.0
z.z.z.z 255.255.255.0

Optionally, the template below

shell> cat test.yaml.j2
---
network:
  {{ network|to_yaml|indent(2) }}

will create valid YAML

shell> cat test.yaml
---
network:
  igb0:
  - {address: x.x.x.x, netmask: 255.255.255.0}
  - {address: y.y.y.y, netmask: 255.255.255.0}
  - {address: z.z.z.z, netmask: 255.255.255.0}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1