My inventory contains two groups: worker and main. Worker contains 5 nodes and main contains 1 node.
Every node has a host_vars
file containing name
and description
.
A Jinja template that loops over the host_vars
of all nodes in a group.
I would like to loop over the host_vars like this:
{% for node in groups["nodes"] %}
Name: {{ node.name }}
Description: {{ node.description }}
{% endfor %}
Name: Nam1
Description: Des1
Name: Nam2
Description: Des2
...
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.
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:
inventory_hostname
will contain the full nameinventory_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 %}