Sunday, July 23, 2017

failed_when Module

Failed When

When failed_when is not used, ansible will consider that task as failed for that particular task and will ignore all other tasks from running. Basically this is used for idempotency. 

Eg. If there is a task to create a DB and if the DB already exists then it will throw an error. In this case it is better to use failed_when. If failed_when is not used then the task will exit with the error. Which will lead other tasks not to run.

Another Example with file deletion. Hope this will make more clarification.

Below task will delete a file. (FYI.. this can be done with file module also for better understanding explaining with the help of this module)

---
 - hosts: ss
   tasks:
    - name: to check failed when
      command: rm /tmp/file1
      register: testoutput
      failed_when: "'Operation not permitted' in testoutput.stderr"
    - name:
      command: echo hi
...

We are using failed_when for idempotency in above task. When we run the above yaml for the first run it will remove the file1 but if the task is ran again then it will throw an error "No such file of directory" which is ignorable. 

If failed_when is not used above task will fail at this level and it wont continue. But when the error is permission denied - Operation not permitted we need to consider that error. So we are insisting the task that it is considered as failed only when we get "Operation not pemitted" error and other errors are ignorable and can be considered as success.

No comments:

Post a Comment