简体   繁体   中英

How to use nested variables in jinja2 templates

How do I use nested variables of an item within the jinja templates? I am running ansible to produce configs for network switches.

Trying to get the if statement to be based on the bgp_peer_version,

I have the following variable files

 ---
 switches:
   - ansible_hostname: Core1
     bgp_neighbors:
       - bgp_peer_version: both
         bgp_peer_ipv4: 10.1.1.1
         bgp_peer_ipv6: 2001::1
         bgp_vrf:
       - bgp_peer_version: v4
         bgp_peer_ipv4: 10.1.1.2
         bgp_peer_ipv6: 
         bgp_vrf:

   - ansible_hostname: Core2
     bgp_neighbors:
       - bgp_peer_version: 'both'
         bgp_peer_ipv4: 10.1.1.2
         bgp_peer_ipv6: 2001::1
         bgp_vrf:
       - bgp_peer_version: 'v4'
         bgp_peer_ipv4: 10.1.1.2
         bgp_peer_ipv6:
         bgp_vrf: 

and have the following code so far

{% if item[bgp_peer_version] == "v4" %}
BGP Peer
IPv4 address {{ bgp_peer_ipv4 }}
{% else %}
BGP Peer
IPv4 address {{ bgp_peer_ipv64 }}
IPv6 address {{ bgp_peer_ipv6 }}
{% endif %}

I am trying to build a template which uses the variables within the bgp neighbours for each of the switches. I am looking for an output with the first template. Template 1 output

BGP Peer IPv4 address 10.1.1.1 IPv6 address 2001::1 BGP Peer IPv4 address 10.1.1.1

Template 2 output

BGP Peer IPv4 address 10.1.1.2 IPv6 address 2001::2 BGP Peer IPv4 address 10.1.1.1

Q: "How do I use nested variables (of an item) within the jinja templates?"

A: Is this probably what you're looking for?

{% for item1 in switches %}
{% for item in item1 %}
{% if item[bgp_peer_version] == "v4" %}
result is V4
{% else %}
result if both
{% endif %}
{% endfor %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM