Using jinja2 how can you do loop in a loop with the second loop an incrementing count to start and stop on var values?

Viewed 36

What is the easiest way using jinja2 (being called from ansible template function) to do a loop in a loop that will start with the first switch port and loop (count) to the last switch port and then continue to the next switch and do the same iteration?

Any tips would be greating appreciated!

Sample variables:

switches:
  - name: "switch1"
    first_port: "1"
    last_port: "52"
  - name: "switch2"
    first_port: "1"
    last_port: "48"
  - name: "switch3"
    first_port: "1"
    last_port: "24"

Desired J2 template output:

switch1:
  port:1
  port:2
  ...
  port:52

switch2:
  port:1
  port:2
  ...
  port:48

switch3:
  port:1
  port:2
  ...
  port:24

1 Answers

I believe the thing you are looking for is range, but based on your provided yaml snippet, you will need to coerce those starting and ending values to int so they can be used with range:

- debug:
    msg: |
      {% for sw in switches %}
      {{ sw.name }}:
        {% for i in range(sw.first_port|int, sw.last_port|int) %}
        port:{{ i }}
        {% endfor %}
      {% endfor %}
Related