ANSIBLE: RUN PLAY ONLY ON REACHABLE HOST

During one of my Ansible trainings in Singapore one candidate asked me, is there some way that we execute the play only on reachable hosts. She also insisted that the playbook should show no errors. Showing errors would report the Job as failed in Ansible Tower. So, finally we came out with a solution and it worked really well.
Our First play would be to check reachable hosts, and create a new group of the reachable hosts.
- name: check reachable hosts
hosts: all
gather_facts: no
tasks:
- command: ping -c1 {{ inventory_hostname }}
delegate_to: localhost
register: ping_result
ignore_errors: yes
- group_by: key=reachable
when: ping_result|success
- We use
command
module to ping a host and delegate the task to localhost - using
group_by
module, if the host is reachable we add it to a new group calledreachable
Next play would be the one that you want to run only on reachable hosts.
- name: your actual play
hosts: reachable
gather_facts: yes
tasks:
- debug: msg="this is {{ ansible_hostname }}"
happy ;)
This playbook is also available on GitHub
Like it? Click here to Tweet your feedback