在未定义属性时,解决Ansible地图过滤器错误的最佳方法是什么?

时间:2017-07-08 23:58:21

标签: ansible jinja2

我有一个带有ip,vrf等属性的接口列表。对我来说最有趣的属性是vrf。我使用map属性来过滤此列表,并使用简化的唯一列表创建必要的代码。如果其中一个提供的接口没有定义vrf,那么过滤此列表的最优雅方法是什么?

变量

base:
  HOSTNAME: MVPS001R01
  SITE_NUMBER: 20
  ROUTER_NUMBER: 1
  MGMT_IP: 100.64.1.1
  interfaces:
    - intf: LOOP0
      ip: 100.64.1.1
      vrf: MPLS1
      type: LOOP
    - intf: GI0/0/0
      vrf: global
      ip: 192.168.0.1/24
      type: eth
      peering:
    - intf: GI0/0/1
      vrf: INET1
      ip: 1.1.1.1/30
      type: eth
    - intf: GI0/1/0
      vrf: MPLS1
      ip: 172.31.0.45
      vlan: 2010
      type: eth

Jinja2代码:

{% set VRFS = base.interfaces | map(attribute='vrf') | list | unique %}

{% for transport in transports %}
{% for vrf in VRFS %}
{% if transport.name | upper == vrf | upper %}

vrf definition  {{ transport.name | upper }}
  rd 1:{{ transport.priority | int }}
  !
 address-family ipv4
 exit-address-family
 !
{% endif %}
{% endfor %}
{% endfor%}

输出当所有接口都有' vrf'定义

vrf definition  MPLS1
 rd 1:100
 !
 address-family ipv4
 exit-address-family
 !

vrf definition  INET1
 rd 1:200
!
address-family ipv4
exit-address-family

其中一个接口缺少vrf时的输出

interfaces:
- intf: LOOP0
  ip: 100.64.1.1
  vrf: MPLS1
  type: LOOP
- intf: GI0/0/0
  ip: 192.168.0.1/24
  type: eth
  peering:

TASK [deploy-smartwan : Generate Base Configuration File] *******************************************************************************************
fatal: [router1]: FAILED! => {"changed": false, "failed": true, "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'vrf'"}

可能未设置vrf属性。我如何解释这一点,并有效地处理这个问题?

1 个答案:

答案 0 :(得分:0)

通过添加selectattr过滤器,我只能从base.interfaces中选择定义了vrf属性的项目。我相信这是一种非常优雅的方法,可以将元素列表减少到生成配置所需的内容。

{% set VRFS = base.interfaces | selectattr("vrf", "defined") | map(attribute='vrf') | list | unique %}

{% for transport in transports %}
{% for vrf in VRFS %}
{% if transport.name | upper == vrf | upper %}

vrf definition  {{ transport.name | upper }}
 rd 1:{{ transport.priority | int }}
!
 address-family ipv4
 exit-address-family
!
{% endif %}
{% endfor %}   
{% endfor%}

变量

我有一个带有ip,vrf等属性的接口列表。对我来说最有趣的属性是vrf。我使用map属性来过滤此列表,并使用简化的唯一列表创建必要的代码。如果其中一个提供的接口没有定义vrf,那么过滤此列表的最优雅方法是什么?

变量

base:
  HOSTNAME: MVPS001R01
  SITE_NUMBER: 20
  ROUTER_NUMBER: 1
  MGMT_IP: 100.64.1.1
  interfaces:
    - intf: LOOP0
      ip: 100.64.1.1
      vrf: MPLS1
      type: LOOP
    - intf: GI0/0/0
      ip: 192.168.0.1/24
      type: eth
      peering:
    - intf: GI0/0/1
      vrf: INET1
      ip: 1.1.1.1/30
      type: eth
    - intf: GI0/1/0
      vrf: MPLS1
      ip: 172.31.0.45
      vlan: 2010
      type: eth

输出

vrf definition  MPLS1
 rd 1:100
 !
 address-family ipv4
 exit-address-family
 !

vrf definition  INET1
 rd 1:200
!
address-family ipv4
exit-address-family