I just did something very similar:
- name: Check Nodes
hosts: all
gather_facts: false
tasks:
- name: ping hosts
ping:
ignore_errors: True
ignore_unreachable: True
register: ping_results
- hosts: localhost
gather_facts: false
tasks:
- name: Add failed hosts to failed_group
add_host:
hostname: "{{ item }}"
groups: unreachable
when: hostvars[item]['ping_results'] is unreachable
loop: '{{groups["all"]}}'
- name: just for show, but here you can do any actions like
'bootstraping' the machines, removing from inventory, etc
debug:
msg: "{{ groups['unreachable'] }}"