Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible: sort of list comprehension?

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']" 
like image 742
Michael Avatar asked Oct 21 '14 16:10

Michael


1 Answers

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).

like image 191
Thomas Quinot Avatar answered Sep 28 '22 03:09

Thomas Quinot