rescue for target failed connection question using localhost

93 views
Skip to first unread message

Daniel Barros

unread,
Aug 21, 2023, 2:16:59 PM8/21/23
to Ansible Project
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.

---
- name: Converge
  hosts: all
  gather_facts: false

  tasks:
    - name: Some Block
      block:

        - name: Gather Facts
          ansible.builtin.gather_facts:

      rescue:
        - name: Error Report
          ansible.builtin.debug:
            msg: Hi, Im failed
          delegate_to: localhost

But when I try that it never goes to rescue Error Report. It ends right away.

Would you happen to have any idea?

PLAY RECAP *********************************************************************
server                 : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0






Brian Coca

unread,
Aug 21, 2023, 2:24:03 PM8/21/23
to ansible...@googlegroups.com
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'] }}"

Brian Coca

unread,
Aug 21, 2023, 2:26:01 PM8/21/23
to ansible...@googlegroups.com
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.

--
----------
Brian Coca

Daniel Barros

unread,
Aug 21, 2023, 7:41:43 PM8/21/23
to ansible...@googlegroups.com
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

--
You received this message because you are subscribed to a topic in the Google Groups "Ansible Project" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ansible-project/z59OlEEry9s/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/CACVha7f1TPuddXu8fUJ%3DCgRM86AigR6PQ-yqRWLm%2BgPYFf1ugg%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages