2017-02-09 231 views
1

这里是YAML模板:Jinja2的for循环和复杂条件

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条件?

回答

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 
+0

真棒方式简单。再次感谢你的帮助! – netauto