commit d48099f715f98944f6b68f5a1d3394559b8bd2ea parent 2c687f75265082385fd3d8068080b03ae254df1c Author: pyratebeard <root@pyratebeard.net> Date: Wed, 2 Feb 2022 12:07:42 +0000 publish ansible_reachable_hosts Diffstat:
A | entry/20220202-ansible_reachable_hosts.md | | | 34 | ++++++++++++++++++++++++++++++++++ |
1 file changed, 34 insertions(+), 0 deletions(-)
diff --git a/entry/20220202-ansible_reachable_hosts.md b/entry/20220202-ansible_reachable_hosts.md @@ -0,0 +1,34 @@ +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](https://stackoverflow.com/a/55190002). + +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 (¬_¬). +