Repeated lines from Jinja For Loop

Viewed 19

I am new to coding and learning for Infrastructure as Code.
Trying to pull info from a variable YAML file within a Jinja file using a for loop. It is working but it is displaying the code two additional times and I am not sure why.

{% for item in underlay[inventory_hostname]['MLAG'] -%}
{% if item == 'Odd' -%}   
   neighbor 192.168.255.1 peer group LEAF_Peer
{%- else %}
   neighbor 192.168.255.2 peer group LEAF_Peer
{% endif %}
{%- endfor %}

Sample of entry in Underlay.yml

leaf1-DC2:
  interfaces:
    loopback0: 
      ipv4: 10.2.0.11
      mask: 32
    loopback1: 
      ipv4: 10.2.1.11
      mask: 32
    Ethernet3:
      ipv4: 10.2.2.0
      mask: 31
    Ethernet4: 
      ipv4: 10.2.2.2
      mask: 31
    Ethernet5: 
      ipv4: 10.2.2.4
      mask: 31
  BGP: 
    ASN: 65201
    spine-peers:
      - 10.2.2.1
      - 10.2.2.3
      - 10.2.2.5
    spine-ASN: 65200
  MLAG: Odd

The results are:

neighbor 192.168.255.2 peer group LEAF_Peer
neighbor 192.168.255.2 peer group LEAF_Peer
neighbor 192.168.255.2 peer group LEAF_Peer

But should be:

neighbor 192.168.255.2 peer group LEAF_Peer

I took the variable file down to a single device that only has the entry for MLAG once but that still produces two additional lines and do not understand why.

The goal is to create a for loop that looks at MLAG and if it is Odd then produce the one statement or Even produce the other.

1 Answers

This happens because a string is an iterable object in both Jinja and Python.

You can test this doing:

{% for item in 'Odd' %}
Displaying one line (because of `{{ item }}`)
{% endfor %}

That would give you

Displaying one line (because of `O`)
Displaying one line (because of `d`)
Displaying one line (because of `d`)

Your fix is as simple as dropping the for loop, totally:

{% if underlay[inventory_hostname].MLAG == 'Odd' -%}   
   neighbor 192.168.255.1 peer group LEAF_Peer
{% else -%}
   neighbor 192.168.255.2 peer group LEAF_Peer
{% endif %}
Related