Search code examples
ansibleansible-2.xansible-inventory

Ansible Five random hosts from /etc/ansible/hosts


I have this playbook, it work using max_index but always takes the first 3 hosts from /etc/ansible/hosts , i need to take 3 random (and not repeated) hosts from that file.

playbook.yml

---
- hosts: ciscos
  connection: local
  gather_facts: false
  tasks:
    - group_by: key=limited_selection
      when: play_hosts.index(inventory_hostname) < max_index | int

- hosts: limited_selection
  gather_facts: no

/etc/ansible/hosts

[ciscos]
stagin ansible_host=10.xx.xx.1
stagin2 ansible_host=10.xx.xx.1
stagin3 ansible_host=10.xx.xx.1
stagin4 ansible_host=10.xx.xx.1
stagin5 ansible_host=10.xx.xx.1

Solution

  • Solution

    You need to shuffle the elements of the group and choose three first. The Jinja2 expression for that is:

    (groups['ciscos'] | shuffle)[0:3]
    

    Implementation which should work, but has problems

    You should be able to simply filter the group in the hosts declaration:

    - hosts: "{{ (groups['ciscos'] | shuffle)[0:3] }}"
      gather_facts: no
      tasks:
        - debug:
    

    However the results are undeterministic - although the play shows as running against three randomly chosen hosts, the tasks are sometimes executed on 1, 2, 3, or 0:

    PLAY [[u'stagin2', u'stagin4', u'stagin5']] *******************************************************************************
    
    TASK [debug] **************************************************************************************************************
    ok: [stagin2] => {
        "msg": "Hello world!"
    }
    ok: [stagin5] => {
        "msg": "Hello world!"
    }
    

    Workaround (implementation which works)

    Use add_host module to create a filtered group:

    - hosts: localhost
      connection: local
      gather_facts: no
      tasks:
        - add_host:
            name: "{{ item }}"
            groups: limited_selection
          loop:  "{{ (groups['ciscos'] | shuffle)[0:3] }}"
    
    - hosts: limited_selection
      gather_facts: no
      tasks:
        - debug: