繁体   English   中英

如何在 jinja2 模板中使用嵌套变量

[英]How to use nested variables in jinja2 templates

如何在 jinja 模板中使用项目的嵌套变量? 我正在运行 ansible 为网络交换机生成配置。

试图让 if 语句基于 bgp_peer_version,

我有以下变量文件

 ---
 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: 

到目前为止有以下代码

{% 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 %}

我正在尝试构建一个模板,该模板使用每个交换机的 bgp 邻居中的变量。 我正在寻找带有第一个模板的 output。 模板 1 output

BGP 对等 IPv4 地址 10.1.1.1 IPv6 地址 2001::1 BGP 对等 IPv4 地址 10.1.1.1

模板 2 output

BGP 对等 IPv4 地址 10.1.1.2 IPv6 地址 2001::2 BGP 对等 IPv4 地址 10.1.1.1

问: “我如何在 jinja 模板中使用嵌套变量(项目的)?”

A:这可能是你要找的吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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