Index and More With Jinja For Loop

Secret Jinja tests for loop objects
August 15, 2016
ansible jinja

While working with Ansible, I often have a need to reconcile my position in a loop. Today it happened while writing out a JSON file from a list of key/value pairs. I needed a way to know if I was in the loop or at the end of it so that I could put a comma after the item (or not).

I found this, which is perfect. Because Ansible uses Jinja directly for its templates, I was able to add a condition like this:

{% if loop.last %}
    }
{% else %}
    },
{% endif %}

For those of you who like one-liners, that can be substituted with:

{{ '}' if loop.last else '},' }}

Check out the link for more tests you can run on the loop variable.