Reputation: 13
I am struggling to understand how to use nested variables in Jinja2/Ansible
I have the following Variables in a yaml file
dual_homed_workloads:
switch1:
- tag: 200
description: DB-Servers
ports:
lags: [1,2,4]
- tag: 201
description: Storage
ports:
lags: [1,2,4]
- tag: 202
description: iLo
ports:
lags: [1,3,4]
switch2:
- tag: 200
description: DB-Servers
ports:
lags: [3,4]
- tag: 211
description: voice
ports:
lags: [1,]
- tag: 2000
description: egree
ports:
lags: [2,3]
and I want to search for the switch name matching the inventory_hostname
, then get the tag of the VLAN
{% for vlan, switch in dual_homed_workloads %}
{% if switch == inventory_hostname %}
VLAN {{ vlan.tag }}
name {{ vlan.descrption }}
{% endif %}
{% endfor %}
If I was to run this for switch 1 I'd want an output as follows
vlan 200
name DB-Servers
vlan 201
name Storage
vlan 202
name iLo
Also the LAGs is a list, is there a way of searching that list for a value e.g. "1"
Thanks
Upvotes: 0
Views: 647
Reputation: 44615
The following will loop other all vlans for the switch key equal to current inventory_hostname
filtering out all vlans which do no contain 1
in the lags
list:
{% for vlan in dual_homed_workloads[inventory_hostname] if 1 in vlan.lags %}
VLAN {{ vlan.tag }}
name {{ vlan.description }}
{% endfor %}
Here are 2 variations since I don't know exactly what you intend to look for inside the lags
key.
Keep vlans which are in either lags
1 or 2:
{% for vlan in dual_homed_workloads[inventory_hostname] if vlan.lags | intersect([1,2]) | length > 0 %}
VLAN {{ vlan.tag }}
name {{ vlan.description }}
{% endfor %}
Only keep vlans which are lags 1 and 2:
{% set keep_lags = [1,2] %}
{% for vlan in dual_homed_workloads[inventory_hostname] if vlan.lags | intersect(keep_lags) | length == keep_lags | length %}
VLAN {{ vlan.tag }}
name {{ vlan.description }}
{% endfor %}
Upvotes: 1