Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Get number of hosts in group

I'm trying to get the number of hosts of a certain group.

Imagine an inventory file like this:

[maingroup] server-[01:05] 

Now in my playbook I would like to get the number of hosts that are part of maingroup which would be 5 in this case and store that in a variable which is supposed to be used in a template in one of the playbook's tasks.

At the moment I'm setting the variable manually which is far from ideal..

vars:   HOST_COUNT: 5 
like image 599
Forivin Avatar asked Mar 30 '16 13:03

Forivin


People also ask

How do I see ansible hosts?

You can use the option --list-hosts. It will show all the host IPs from your inventory file.

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 handle?

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 does Set_fact do in ansible?

This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.


2 Answers

  vars:     HOST_COUNT: "{{ groups['maingroup'] | length }}" 
like image 135
helloV Avatar answered Sep 20 '22 10:09

helloV


Also without explicit group name:

vars:     HOST_COUNT: "{{ ansible_play_hosts | length }}" 
like image 45
Cigizmoond Vyhuholev Avatar answered Sep 22 '22 10:09

Cigizmoond Vyhuholev