What is the best way to solve Ansible map filter error when an attribute is not defined?

Viewed 1718

I have a list of interfaces with attributes such as ip, vrf, etc. The most interesting attribute to me is vrf. I used the map attribute to filter this list and create the necessary code with the reduced unique list. What is the most elegant way to filter this list if one of the supplied interfaces does not have the vrf defined?

variables

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

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

Output When all interfaces have 'vrf' defined

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

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

Output when vrf is missing from one of the interfaces

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'"}

It is possible that the vrf attribute may not be set. How do I account for this and efficently handle this?

1 Answers
Related