Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all currently targeted hosts in an Ansible play

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?

like image 566
xabram Avatar asked Feb 25 '15 01:02

xabram


People also ask

How do I get a list of hosts in Ansible?

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.

What is hosts all in Ansible?

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.

How many hosts can Ansible manage?

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.

What is Run_once in Ansible?

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.


2 Answers

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 
like image 196
sirkubax Avatar answered Oct 16 '22 08:10

sirkubax


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.

like image 26
udondan Avatar answered Oct 16 '22 07:10

udondan