Ansible – Count the total number of hosts in hosts/inventory file, print output using debug

Files

[bchoi@rhel01 ansible-helloworld-playbook]$ ls


ansible.cfg  count_hosts.yml  hosts

Hosts file content

[bchoi@rhel01 ansible-helloworld-playbook]$ cat hosts

[centos]
192.168.30.195
192.168.30.201

[ubuntu]
192.168.30.248

[web:children]
ubuntu

[centos:vars]
ansible_become_user=bchoi

ansible.cfg file

[bchoi@rhel01 ansible-helloworld-playbook]$ cat ansible.cfg

[defaults]
inventory = hosts

Actual host counting yaml file, here I am using the variable total_hosts to convert it into integer and then time it by 30 seconds and creating another variable called sleep_time. More hosts file there are longer the sleep time.

[bchoi@rhel01 ansible-helloworld-playbook]$ cat count_hosts.yml

---
- hosts: all
  gather_facts: False
  connection: local

  vars:
    total_hosts: "{{ groups['all'] | length }}"
    sleep_time: "{{ total_hosts | int * 30 }}"
  tasks:
    - name: "Total host count"
      debug:
        msg: "{{ total_hosts }}"

    - name: "Total sleep time"
      debug:
        msg: "{{ sleep_time }}" 

The Playbook run, there are three hosts in the hosts file, so it will print total hosts of 3 and then 90 seconds as the sleep time.

[bchoi@rhel01 ansible-helloworld-playbook]$ ansible-playbook count_hosts.yml

PLAY [all] **********************************************************************************************************************************************

TASK [Total host count] *********************************************************************************************************************************
ok: [192.168.30.248] => {
    "msg": "3"
}
ok: [192.168.30.195] => {
    "msg": "3"
}
ok: [192.168.30.201] => {
    "msg": "3"
}

TASK [Total sleep time] *********************************************************************************************************************************
ok: [192.168.30.201] => {
    "msg": "90"
}
ok: [192.168.30.195] => {
    "msg": "90"
}
ok: [192.168.30.248] => {
    "msg": "90"
}

PLAY RECAP **********************************************************************************************************************************************
192.168.30.195             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.30.201             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.30.248             : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Leave a comment