Execute task (or handler) if any task failed


I am using Ansible to deploy a Django website into my servers (production, staging, etc), and I would like to get a notification (via slack in this case) if and only if any task fails.

I can only figure out how to do it if a specified task fails (so I guess I could add a handler to all tasks), but intuition tells me there has to be an easier and more elegant option.

Basically what I am thinking of is:

I have been diving into the Ansible documentation, specially in the error handling section, and answers here at SO, but I’m struggling to find an answer to my question. So any help will be much appreciated.


I don’t think a handler is a solution, because a handler will only be notified if the task reports a changed state. On a failed state the handler will not be notified.

Also, handlers by default will not be fired if the playbook failed. But that can be changed. For that you will need to set this in your ansible.cfg:

But yes, there are better options available.

If you use Ansible 2 you can use the new blocks feature. Blocks group tasks together and have a rescue section which will be only triggered if any of the tasks have failed.

Another option and especially interesting if you’re using Ansible 1.x might be callback plugins. As the name suggests with these kind of plugins you can write callbacks which can be fired on various events.

Again, if you’re using Ansible 2 you’re lucky, because there already is a slack callback plugin available: https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/callback/slack.py

To use this plugin you need to enable it in your ansible.cfg:

And define some environment variables on your system for configuration:

That plugin might need some modifications to fit your needs. If that’s the case copy the source and store it relative to your playbook as callback_plugins/custom_slack.py and then enable it in your ansible.cfg:

If you use Ansible 1.x you’ll have to see how you can convert it. The API is different, examples for the old API can be found here: https://github.com/ansible/ansible/tree/v1.9.4-1/plugins/callbacks

Leave a Reply