Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
Illusionist Avatar asked Aug 10 '16 14:08

Illusionist


People also ask

What happens when one playbook fails a task?

If you use ignore_errors, ansible will continue attempting to run tasks against that host. The default workflow is to fail, then ignore that host for the rest of the playbook. Then at the end, admin researches why the hosts failed, fixes them, then reruns the playbook against the ones that failed. The .

What keyword can be used at a task or block level to ignore failures if target host is unreachable?

Boolean that allows you to ignore task failures and continue with play. It does not affect connection errors. Boolean that allows you to ignore task failures due to an unreachable host and continue with the play.

How do you execute a failed playbook again?

You can achieve similar effect by just using the --step flag e.g: ansible-playbook playbook. yml --step . The step asks you on before executing each task and you could choose (N)o/(y)es/(c)ontinue . With this approach you selectively execute tasks when needed and also continue from point where it failed, after fixes.

Which key is used to instruct Ansible to treat any failure as a fatal error?

These directives are written at the same level as the hosts: directive. Here are subset of the keys that can be used is described: any_errors_fatal : This Boolean directive is used to instruct Ansible to treat any failure as a fatal error to prevent any further tasks from being attempted.


1 Answers

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" 
like image 135
clever_bassi Avatar answered Sep 24 '22 01:09

clever_bassi