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:

/etc/hosts

We want to generate the following snip of code inside /etc/hosts:

192.168.1.2 web01 BB-WS1
192.168.1.3 web02 BB-WS2
192.168.1.4 web03 BB-WS3
192.168.1.5 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 %}

workers.properties

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

worker.loadbalancer.balance_workers=bb-ws1_gf,bb-ws2_gf,bb-ws3_gf,bb-ws4_gf

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:

worker.loadbalancer.balance_workers=
{% 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.

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s