rescue for target failed connection question using localhost

Hi everyone. Good day.

When we have a regular task like creating a file, or something similar, we can use block and rescue to manage what happens in failure cases.

But can we do the same for the first task (connection) on a target and rescue using localhost?

What I would like to achieve is this.

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'] }}"

I forgot to mention, the reason your rescue does not work is because
the task did not fail, but the host was unreachable.
block/rescue/always only acts on task failure, not host being
unreachable.

In my example above I ignore unreachable and task errors so the '2nd
play' can handle them differently.

Hi Brian.

Using ignore unreachable and failing based on the condition of the register variable based on your example did the trick for me.

I appreciate your time and sharing.
Br