Reputation: 51
I want to get an array of values of the specific variable from all hosts. For example: let's say I have host dc1.com
with variable test_var = "value1"
and host dc2.com
with variable test_var = "value2"
. I want to get an array of these values that looks like this [ "value1", "value2" ]
. Is it possible?
Upvotes: 2
Views: 2888
Reputation: 44808
You can fetch any existing var from any available host through the hostvars
dict available as a magic var
e.g.:
hostvars["dc1.com"].test_var
If you want a list of all found values, the following will go through all hosts in your inventory and extract the defined values in a list. Check the documentation on filters for more details and to arrange to your exact requirements.
- name: Show a list of all test_var values in my inventory
debug:
msg: "{{ hostvars | dict2items | selectattr('value.test_var', 'defined') | map(attribute='value.test_var') }}"
Bonus (once more study the documentation above for more explanation), almost the same as above but only for your two example hosts. Note I dropped the attribute defined filter taking for granted the var will exist.
- name: Show list of test_var valuse for dc1 and dc2 hosts
vars:
host_list:
- dc1.com
- dc2.com
debug:
msg: "{{ host_lists | map('extract', hostvars) | map(attribute='test_var') }}"
Upvotes: 4