(Ansible) How to get all inventory variables for a group of hosts as a list in template/Jinja2?
Asked Answered
C

1

5

I am writing automation with this type of Ansible inventory:

[nodes]
<publicIp1>  privateIp=<privateIp1>
<publicIp2>  privateIp=<privateIp2>

I do this because sometimes hosts have a different public IP vs. private IP (e.g., AWS).

Now while configuring any host, I need get a csv like "privateIp1,privateIp2" inside template module's jinja2 file.

Preferrably, I do not even want to refer to the group name "node", but rather just ask for "give me list of all 'privateIp' inventory variables for all members of group of current host." << Assuming my host was a member of just one group.

If not possible, is there a way to refer to the group name and do this?

Croom answered 10/7, 2017 at 1:23 Comment(0)
S
6

Use group magic variable. There is an exact example for your use case in the documentation, just replace the variable name:

groups is a list of all the groups (and hosts) in the inventory. This can be used to enumerate all hosts within a group. [ ]

A frequently used idiom is walking a group to find all IP addresses in that group

{% for host in groups['app_servers'] %}
  {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}

You can combine the template with another magic variable group_names to get a list of groups for the current host and use it as an outer loop.

Shortterm answered 10/7, 2017 at 1:30 Comment(2)
But how do I get a csv list of the inventory variables of the hosts? I think above will print each item on a line.Croom
You need to write a proper template. When you do and encounter a specific problem, you can ask on StackOverflow. I will not write the code for you, sorry.Shortterm

© 2022 - 2024 — McMap. All rights reserved.