I am administering a heterogeneous environment with a lot of stakeholders. It would be crucial to react on unreachable and failed hosts differently. So far my solution is:
`
hosts: all:localhost
tasks:
If fact gathering fails - > host unreachable
if the role has failed
set_fact:
failed_deployment: “{{ reachable_hosts | difference(ansible_play_hosts) }}”
delegate_to: localhost
run_once: True
Here could be the notification modules
debug:
msg: “unreachable: {{ unreachable_hosts }}, failed: {{ failed_connection }}”
delegate_to: localhost
run_once: True
`
It seems a little clumsy to me. Is there a way to check if a host is reachable with a module?
Is this the standard way of handling failed connections?
Thanks
vbotka
(Vladimir Botka)
November 11, 2019, 1:09pm
2
It's possible to test the connection, register and use the result. For example
- delegate_to: localhost
command: ping -c1 "{{ inventory_hostname }}"
register: result
ignore_errors: true
Your solution is cleaner. I'd propose to create a group of reachable
hosts and structure the the playbook into more plays. For example
- name: Create group of reachable hosts
hosts: all
gather_facts: true
tasks:
- add_host:
name: '{{ item }}'
groups: 'reachable'
loop: "{{ ansible_play_hosts }}"
run_once: true
- set_fact:
unreachable_hosts: "{{ ansible_play_hosts_all|
difference(ansible_play_hosts) }}"
delegate_to: localhost
delegate_facts: true
run_once: true
- name: Manage reachable hosts
hosts: reachable
gather_facts: true
tasks:
- debug:
var: inventory_hostname
- name: Manage unreachable hosts
hosts: localhost
gather_facts: true
tasks:
- debug:
var: item
loop: "{{ unreachable_hosts }}"
Notes:
1) "gather_facts: true" in the first play is necessary to
remove unreachable hosts from "ansible_play_hosts".
2) It's not necessary to delegate "add_hosts".
3) It's necessary "delegate_facts: true" to declare the variable
"unreachable_hosts" in the "hostvars['localhost']".
Cheers,
-vlado