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?
You can use the option --list-hosts. It will show all the host IPs from your inventory file. You can use the below-given command.
Ansible uses a combination of a hosts file and a group_vars directory to pull variables per host group and run Ansible plays/tasks against hosts. group_vars/all is used to set variables that will be used for every host that Ansible is ran against.
One of the best things about Ansible is its ability to operate in parallel across multiple hosts. The number of hosts it can operate on at once depends on multiple factors. The largest factor is the forks parameter. This parameter has a default of 5, which will limit Ansible to operating on only five hosts at one time.
Ansible run_once parameter is used with a task, which you want to run once on first host. When used, this forces the Ansible controller to attempt execution on first host in the current hosts batch, then the result can be applied to the other remaining hosts in current batch.
You are looking for 'play_hosts' variable
--- - 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
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:
[proxy] web1 app_type=web web2 app_type=web web3 app_type=load_balancer [some_other_group] web1 web3
You can use the option --list-hosts
to only list hosts a playbook would affect.
Also, there is the dict hostvars
which holds all hosts currently known to Ansible. But I think the setup
module had to be run on all hosts, so you can not skip that step via gather_facts: no
.
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