Given this inventory:
[webservers]
10.0.0.51 private_ip='X.X.X.X'
10.0.0.52 private_ip='Y.Y.Y.Y'
10.0.0.53 private_ip='Z.Z.Z.Z'
How can I get a list of the private ips of the webservers?
webservers_private_ips: "{{ }}" # ['X.X.X.X', 'Y.Y.Y.Y', 'Z.Z.Z.Z']
I know groups['webservers']
will give me this list ['10.0.0.51', '10.0.0.52', '10.0.0.53']
and I can get the private_ip of one with:
{{ hostvars[item]['private_ip'] }}
with_items: groups['webservers']
But I would like to declare a variable in my var file directly and not have a task to register it. It would be nice if something like the following could be done:
webservers_private_ips: "{{ hostvars[item]['private_ip'] }} for item in groups['webservers']"
You can take advantage of the extract filter to get components of a composite data object:
webservers_private_ips: "{{ groups['webservers']|map('extract', hostvars, 'private_ip')|list }}"
The extract filter is used to map from a list of indices to a list of values from a container (hash or array).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With