ansible

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors


I am learning Ansible. I have a playbook to clean up resources, and I want the playbook to ignore every error and keep going on till the end , and then fail at the end if there were errors.

I can ignore errors with

ignore_errors: yes

If it was one task, I could do something like ( from ansible error catching)

- name: this command prints FAILED when it fails
  command: /usr/bin/example-command -x -y -z
  register: command_result
  ignore_errors: True

- name: fail the play if the previous command did not succeed
  fail: msg="the command failed"
  when: "'FAILED' in command_result.stderr"

How do I fail at the end ? I have several tasks, what would my "When" condition be?


Solution

  • Use Fail module.

    1. Use ignore_errors with every task that you need to ignore in case of errors.
    2. Set a flag (say, result = false) whenever there is a failure in any task execution
    3. At the end of the playbook, check if flag is set, and depending on that, fail the execution
    - fail: msg="The execution has failed because of errors."
      when: flag == "failed"
    

    Update:

    Use register to store the result of a task like you have shown in your example. Then, use a task like this:

    - name: Set flag
      set_fact: flag = failed
      when: "'FAILED' in command_result.stderr"