User a loop var from a state file in the Jinja template

33 views
Skip to first unread message

UPPERCASE

unread,
Oct 18, 2022, 10:51:46 AM10/18/22
to Salt-users
Can I use a var loop in a state file also in a template? As in I loop in the state file through vars and then use them directly in the template, not doing another loop.

Because I'm trying the following, which would work in Ansible, just making sure it does not work in Salt.

My Pillar vars

```
routes:
  ens4f0np0:
    - address: 192.168.1.0
      netmask: 255.255.255.192
      gateway: 172.18.12.1
    - address: 192.168.2.1
      netmask: 255.255.255.224
      gateway: 172.18.48.1
```

The state file loop

```
{% for interface in salt['pillar.get']('routes') %}
  file.managed:
    - name: /etc/sysconfig/network-scripts/route-{{ interface }}
    - user: root
    - group: root
    - mode: '0644'
    - source: salt://linux/network/files/routes.jinja
    - template: jinja
{% endfor %}
```

The template

```
# {{ interface }}
{% for route in salt['pillar.get']('routes:interface') %}
ADDRESS{{ loop.index }}={{ route.address }}
NETMASK{{ loop.index }}={{ route.netmask }}
GATEWAY{{ loop.index }}={{ route.gateway }}
{% endfor %}
```

But this results in an error because the var interface does not exist. Removing the first line will create an empty file without errors. Replacing the interface var of the second line with the interface name works. Is there a way to make the key in the state loop also available in the template and use it in the loop in there?

UPPERCASE

unread,
Oct 18, 2022, 11:07:24 AM10/18/22
to Salt-users
Already solved.


```
{% for interface, routes in pillar["routes"].items() %}
network_route-{{ interface }}:

  file.managed:
    - name: /etc/sysconfig/network-scripts/route-{{ interface }}
    - user: root
    - group: root
    - mode: '0644'
    - source: salt://linux/network/files/routes.jinja
    - template: jinja
    - context:
        interface: {{ interface }}
        routes: {{ routes | tojson }}
{% endfor %}
```

```
{%- for route in routes -%}
ADDRESS{{ loop.index0 }}={{ route.address }}
NETMASK{{ loop.index0 }}={{ route.netmask }}
GATEWAY{{ loop.index0 }}={{ route.gateway }}
{% endfor %}
```
Reply all
Reply to author
Forward
0 new messages