Loop over host_vars of hosts in an ansible hosts group in jinja

Setup

Inventory

My inventory contains two groups: worker and main. Worker contains 5 nodes and main contains 1 node.

Host_Vars

Every node has a host_vars file containing name and description.

What I am looking for

Jinja

A Jinja template that loops over the host_vars of all nodes in a group.

Pseudocode

I would like to loop over the host_vars like this:

{% for node in groups["nodes"] %}
Name: {{ node.name }}
Description: {{ node.description }}
{% endfor %}

Possible Result

Name: Nam1
Description: Des1
Name: Nam2
Description: Des2
...

My "Solution"

But I fail to see how I can do this elegantly. A simple solution that I currently use is to hold a vars file containing all the host_vars information. That vars file is known by every target and by that I can access all node information from every target. However, this isn’t the best solution I guess.

>Solution :

In a nutshell:

{% for node in groups["nodes"] %}
Name: {{ hostvars[node].name }}
Description: {{ hostvars[node].description }}
{% endfor %}

For a documentation of hostvars see Ansible special variables

To go a bit further, note that if your inventory looks like:

---
nodes:
  hosts:  
    server1.mydomain.com:
    server2.mydomain.com:
  1. inventory_hostname will contain the full name
  2. inventory_hostname_short will contain the name before the first dot (i.e. server1 for the first server in that list).

You can check the above link for those special variables as well. So this could probably replace your custom name variable (saving one variables in your host specific files) and your template would then look something like:

{% for node in groups["nodes"] %}
Name: {{ hostvars[node].inventory_hostname_short }}
Description: {{ hostvars[node].description }}
{% endfor %}

Leave a Reply