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
You can use the option --list-hosts. It will show all the host IPs from your inventory file.
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.
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.
vars: HOST_COUNT: "{{ groups['maingroup'] | length }}"
Also without explicit group name:
vars: HOST_COUNT: "{{ ansible_play_hosts | length }}"
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