ansible reachable hosts

I use AWX for Ansible in work quite a bit. We have a number of workflows that will run on multiple hosts. One issue we had was that some systems may be offline when the templates in the workflow run, and this would result in a template (and ultimately a workflow) failure even though all the other systems were successful.

Stackoverflow to the rescue! Thanks to Alex Cohen for this solution.

To combat the offline hosts the playbook can be modified to perform a check on the inventory first, loading any online systems into a “reachable” group. The rest of the playbook would only be run against the online systems.

---
- hosts: all
  gather_facts: false
  tasks:
    - block:
      - wait_for_connection:
          timeout: 5
      - group_by:
          key: "reachable"
      tags: always
      check_mode: false
      rescue:
      - debug:
          msg: "unable to connect to {{ inventory_hostname }}"

- hosts: reachable
  tasks:
    - name: normal playbook tasks from here
    ...

As you can see this is achieved using the block feature in Ansible. The key parameter in the group_by module specifies the name of our ad-hoc inventory group, in this case “reachable”.

Using the debug module message in rescue allows us to mark the offline systems as rescued so it doesn’t fail the playbook. Then the rest of the playbook is run against all systems in the “reachable” group.

This now doesn’t cause my workflows to fail and I don’t have to explain why I’m not concerned when there is red on the dashboard (¬_¬).