Jinja2用于循环和复杂条件

时间:2017-02-09 15:28:52

标签: ansible yaml jinja2

这是yaml模板:

 static_routes:
    - network: 1.1.1.0
      mask: 255.255.255.0
      next_hop: 19.19.3.10
    - network: 7.7.32.0
      mask: 255.255.255.0
      next_hop: 7.7.2.1
    - network: 172.16.110.0
      mask: 255.255.255.248
      intf: FastEthernet0/1.1
      next_hop: 172.16.110.3
    - network: 172.16.120.0
      mask: 255.255.255.248
      intf: FastEthernet0/1.2
      next_hop: 172.16.120.3
    - network: 150.1.7.4
      mask: 255.255.255.255
      intf: FastEthernet0/0.1
      next_hop: 19.19.3.10
      vrf: Site-1
      glob: global
    - network: 150.1.7.4
      mask: 255.255.255.255
      next_hop: 19.19.3.10
      vrf: Site-1
    - network: 150.1.7.4
      mask: 255.255.255.255
      next_hop: 19.19.3.10
      intf: FastEthernet0/0.1
      glob: global
      vrf: Site-2
    - network: 150.1.7.4
      mask: 255.255.255.255
      next_hop: 19.19.3.10
      vrf: Site-2

Jinja2模板(注意重复if语句并想知道是否有办法将其组合在一起以获得下面所需的输出)

{% for r in item.static_routes %}
{% if r.intf is undefined and r.vrf is undefined and r.glob is undefined %}
ip route {{ r.network }} {{ r.mask }} {{ r.next_hop }}
{% endif %}
{% if r.intf is defined and r.glob is undefined %}
ip route {{ r.network }} {{ r.mask }} {{ r.intf }} {{ r.next_hop }}
{% endif %}
{% if r.intf is defined and r.glob is defined and r.vrf is defined and r.glob is defined %}
ip route {{ r.vrf }} {{ r.network }} {{ r.mask }} {{ r.intf }} {{ r.next_hop }} {{ r.glob }}
{% endif %}
{% if r.vrf is defined and r.intf is undefined and r.glob is undefined  %}
ip route {{ r.vrf }} {{ r.network }} {{ r.mask }} {{ r.next_hop }}
{% endif %}
{% endfor %}

最终输出将如下所示:

ip route 1.1.1.0 255.255.255.0 19.19.3.10
ip route 7.7.32.0 255.255.255.0 7.7.2.1
ip route 172.16.110.0 255.255.255.248 FastEthernet0/1.1 172.16.110.3
ip route 172.16.120.0 255.255.255.248 FastEthernet0/1.2 172.16.120.3
ip route vrf Site-1 150.1.7.4 255.255.255.255 FastEthernet0/0.1 19.19.3.10 global
ip route vrf Site-1 150.1.7.4 255.255.255.255 19.19.3.10
ip route vrf Site-2 150.1.7.4 255.255.255.255 FastEthernet0/0.1 19.19.3.10 global
ip route vrf Site-2 150.1.7.4 255.255.255.255 19.19.3.10

这段代码有效,但想知道是否有办法简化此类场景的Jinja2条件?

1 个答案:

答案 0 :(得分:2)

如果你不介意额外的空格:

{% for r in static_routes %}
ip route {{ r.vrf | default('') }} {{ r.network }} {{ r.mask }} {{ r.intf | default('') }} {{ r.next_hop }} {{ r.glob | default('') }}
{% endfor %}

有:

ip route  1.1.1.0 255.255.255.0  19.19.3.10
ip route  7.7.32.0 255.255.255.0  7.7.2.1
ip route  172.16.110.0 255.255.255.248 FastEthernet0/1.1 172.16.110.3
ip route  172.16.120.0 255.255.255.248 FastEthernet0/1.2 172.16.120.3
ip route Site-1 150.1.7.4 255.255.255.255 FastEthernet0/0.1 19.19.3.10 global
ip route Site-1 150.1.7.4 255.255.255.255  19.19.3.10
ip route Site-2 150.1.7.4 255.255.255.255 FastEthernet0/0.1 19.19.3.10 global
ip route Site-2 150.1.7.4 255.255.255.255  19.19.3.10