Search code examples
ansibleansible-2.xansible-facts

ansible run rescue only for instance where task failed


I am trying to run block of tasks and have rescue statement in case the task in block fails.

- block:
    - name: Set shell session
      shell: xyz
    - fail:
        msg: shell failed
  rescue:
    set_fact:
      gist: "abc"
    shell: abc

I am running this for 5 servers and see that if task in block fails for 1 server, it is running rescue block for all servers. My requirement is to run rescue block only for instances where block task has failed.

Am I doing something wrong here? Can someone please guide?


Solution

  • Ansible already works like you want, the issue is in your code.

    In your case, the behavior you describe is expected because you're running fail task on all your instances. So Ansible runs rescue for the failed shell on one server, and for the fail on the others.

    You should remove the fail task from your block. Also, your rescue block uses invalid syntax so it actually shouldn't work - the tasks should be defined as a list, not as a dict:

    - block:
        - name: Set shell session
          shell: xyz
      rescue:
        - set_fact:
            gist: "abc"
        
        - shell: abc