Question:
I am running an Ansible play and would like to list all the hosts targeted by it. Ansible docs mentions that this is possible, but their method doesn’t seem to work with a complex targeted group (targeting like hosts: web_servers:&data_center_primary)
I’m sure this is doable, but cant seem to find any further documentation on it. Is there a var with all the currently targeted hosts?
Answer:
You are looking for ‘play_hosts’ variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
--- - hosts: all tasks: - name: Create a group of all hosts by app_type group_by: key={{app_type}} - debug: msg="groups={{groups}}" run_once: true - hosts: web:&some_other_group tasks: - debug: msg="play_hosts={{play_hosts}}" run_once: true |
would result in
1 2 3 4 5 6 7 8 |
TASK: [Create a group of all hosts by app_type] ******************************* changed: [web1] => {"changed": true, "groups": {"web": ["web1", "web2"], "load_balancer": ["web3"]}} TASK: [debug msg="play_hosts={{play_hosts}}"] ********************************* ok: [web1] => { "msg": "play_hosts=['web1']" } |
inventory:
1 2 3 4 5 6 7 8 9 |
[proxy] web1 app_type=web web2 app_type=web web3 app_type=load_balancer [some_other_group] web1 web3 |