Jinja2: Using loop.index and loop.length. Examples: /etc/hosts and workers.properties

It’s really important to know how Jinja2 works if you want to create powerful templates for your playbooks. Today we’re gonna work with:

  • loop.index: The current iteration of the loop. (1 indexed)
  • loop.length:  The number of items in the sequence

Two different examples for different files: /etc/hosts and workers.properties:


We want to generate the following snip of code inside /etc/hosts: web01 BB-WS1 web02 BB-WS2 web03 BB-WS3 web04 BB-WS4

web01, web02, web03 and web04 are hostnames, but how can we generate the second field?

Let’s say we have a group called ‘webservers’ in our inventory file. We can use loop.index if we want to create the code above:

{% for host in groups['webservers'] %}
{{ hostvars[host]['ansible_default_ipv4']['address'] }} {{ hostvars[host]['ansible_fqdn'] }} BB-WS{{ loop.index }}
{% endfor %}


We want to generate the following snip of code for Apache workers properties:


In that case, not only it’s important to know the loop.index value. Also we want to know if we’re in the latest item. Because the latest item it’s without comma. To do that we will use loop.index combined with loop.length:

{% for host in groups['webservers'] %}
{% if loop.index == loop.length %}
bb-ws{{ loop.index }}_gf
{% else %}
bb-ws{{ loop.index }}_gf,
{% endif %}
{% endfor %}

As you can see if we’re in the latest item ( loop.index == loop.length ) we should write the code without comma.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s