'Execute a ansible playbook if other playbooks fails
I have multiple play books, I have to run create_silence.yml at the starting of the execution and delete_silence.yml at the last, which I'm able to do.
But after create_silence.yml if any playbook fails delete_silence.yml should execute whatever the case is.
Below is delete_silence.yml
- hosts: all
tasks:
- name: Executing block for silencing an alert
block:
- name: block for deleting silence
block:
- name: delete silence
uri:
url: http://127.0.0.1:9093/alert-manager/api/v2/silence/{{silence_id}}
method: DELETE
HEADER_Content-Type: "application/json"
status_code: 200
delegate_to : "{{ admin_server }}"
register : delete_silence_output
ignore_errors: true
when: env is search("PROD") or env is search("PSE") or env is search("QA1")
Below is main.yml
- import_playbook: create_silence.yml
when: job_type is search("REMOVE") or job_type is search("DEPLOY")
- import_playbook: Remove.yml
when: job_type is search("REMOVE")
- import_playbook: Deploy.yml
when: job_type is search("DEPLOY")
- import_playbook: delete_silence.yml
when: job_type is search("REMOVE") or job_type is search("DEPLOY")
So if any task fails in Deploy.yml or Remove.yml , delete_silence.yml should execute
Thanks in advance
Solution 1:[1]
My suggestion is that you transform your create_silence
, Remove
, Deploy
and delete_silence
playbooks into roles and call those roles either from independent playbooks or 1 playbook only using a state
variable.
If you call the create_silence
role from the create playbook you can add a block
/rescue
block to catch errors and call the delete_silence
role.
Something like this...
- hosts: all
tasks:
block:
- name: "Call create_silence role"
import_role:
name: 'create_silence'
rescue:
- name: "Call delete_silence role"
import_role:
name: 'delete_silence'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Antonio Costa |