Skip to content

Example 4

hosts.yml

centos:
  hosts:
    provisioner:
      ansible_connection: local
    centos1:
      ansible_host: '192.168.77.22'
ubuntu:
  hosts:
    ubuntu1:
      ansible_host: '192.168.77.23'

playbook.yml

- hosts: all
  gather_facts: false
  vars:
    jobs: []
  tasks:
    - name: 1st sleep
      command: sleep 20
      when: inventory_hostname == 'provisioner'
      async: 45
      poll: 0
      register: out1
    - name: 2nd sleep
      command: sleep 5
      when: inventory_hostname == 'centos1'
      async: 10
      poll: 0
      register: out2
    - name: 3rd sleep
      command: sleep 5
      when: inventory_hostname == 'ubuntu1'
      async: 10
      poll: 0
      register: out3
    - name: 4th sleep
      command: sleep 5
      when: inventory_hostname == 'provisioner'
      async: 10
      poll: 0
      register: out4
    - name: 5th sleep
      command: sleep 5
      when: inventory_hostname == 'centos1'
      async: 10
      poll: 0
      register: out5
    - name: Capture started jobs
      set_fact:
        jobs: >
          {% if item.ansible_job_id is defined -%}
            {{ jobs + [item.ansible_job_id] }}
          {% else -%}
            {{ jobs }}
          {% endif -%}
      with_items:
        - "{{ out1 }}"
        - "{{ out2 }}"
        - "{{ out3 }}"
        - "{{ out4 }}"
        - "{{ out5 }}"
    - name: Show jobs
      debug:
        var: jobs

Tip

The user can register the job id's of started tasks in order to implement more complex behavior.

Execute the following command

ansible-playbook playbook.yml

Bonus round

Use Ansible's async_status module to wait for all the jobs to finish.