Forivin
Forivin

Reputation: 15508

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

Upvotes: 35

Views: 42334

Answers (2)

Cigizmoond Vyhuholev
Cigizmoond Vyhuholev

Reputation: 431

Also without explicit group name:

vars:
    HOST_COUNT: "{{ ansible_play_hosts | length }}"

Upvotes: 29

helloV
helloV

Reputation: 52393

  vars:
    HOST_COUNT: "{{ groups['maingroup'] | length }}"

Upvotes: 68

Related Questions