CEamonn
CEamonn

Reputation: 925

Ansible Template with Jinja formatting

I have a playbook that runs a few commands on network devices and pulls the results into separate lists, and then using Template + a .j2 file outputs it all into a seperate file. The template looks like:

{% for i in ips %}
IP: {{ i }}
{% endfor %}

{% for j in intf %}
Intf: {{ j }}

{% for k in br_list %}
BR: {{ k }}
{% endfor %}

My output looks like this:

IP: 127.0.0.1
IP: 127.0.0.2
IP: 127.0.0.3
IP: 127.0.0.4

Intf: Vlan1
Intf: Vlan2
Intf: Vlan3
Intf: Vlan4

BR: False
BR: False
BR: False
BR: False

What I want is for the output to be tabulated like this:

IP            Intf            BR
127.0.0.1     Vlan1           False
127.0.0.2     Vlan2           False
127.0.0.3     Vlan3           False
127.0.0.4     Vlan4           False

Any nested loops I tried returns duplicates of each list. Is this possible with Ansible/Jinja?

Upvotes: 1

Views: 1867

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68229

Use zip filter:

{% for i in ips | zip(intf, br_list) %}
{{ "%-10s" | format(i[0]) }}{{ "%-10s" | format(i[1]) }}{{ "%-10s" | format(i[2]) }}
{% endfor %}

"%-10s" | format(i[0]) is to get 10 spaces padding on the right side.

You can even use nested loop:

{% for i in l1 | zip(l2,l3) %}
{% for j in i %}
{{ "%-10s" | format(j) }}
{%- endfor %}

{% endfor %}

Upvotes: 4

Related Questions