Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading