router_ninja
router_ninja

Reputation: 23

Jinja2 For Loop over a YAML List of Dictionaries

I am fairly new to Jinja2 and I have an issue I can't seem to resolve no matter what I try. I am trying to create a config file for a device using a Jinja2 template and some variable files I have created. I cannot seem to get it working at all when I am specifying a list of dictionaries for my YAML variable file.

template:

{% for id in VLANS %}
vlan {{ id.id }}
  name {{ id.name }}
  vn-segment {{ id.vni }}
{% endfor %}

variable file:

VLANS:
  - id: 9
    name: "VLAN9"
    vni: 109
  - id: 10
    name: "VLAN10"
    vni: 110
  - id: 11
    name: "VLAN11"
    vni: 111
  - id: 12
    name: "VLAN12"
    vni: 112

Upvotes: 2

Views: 9652

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68024

Looks fine. The play below

    - name: Template
      template:
        src: template.j2
        dest: test.txt

gives

    shell> cat test.txt 
    vlan 9
      name VLAN9
      vn-segment 109
    vlan 10
      name VLAN10
      vn-segment 110
    vlan 11
      name VLAN11
      vn-segment 111
    vlan 12
      name VLAN12
      vn-segment 112 

with template

    shell> cat template.j2
    {% for item in VLANS %}
    vlan {{ item.id }}
      name {{ item.name }}
      vn-segment {{ item.vni }}
    {% endfor %}

Upvotes: 2

Related Questions