Calling Ansible handlers based on OS distributions

Sometimes you’ve got an Ansible task that should notify another task after a change. In Ansible this is called a handler and a description can be found here. Mostly the handler can be defined OS-independent. In this blog post, we show you, how to use a list of handlers for different OS distributions.

Our solution is quite simple. In the task, we set a list of OS-dependent Ansible handlers. And in the handler-section, we set a when condition that triggers only for the defined OS distribution.

So in this example below we notify two Ansible handlers named redhat handler and debian handler, which will only trigger when their condition matches.

If you run this playbook on a Debian system, you’ll see that both Ansible handlers will be notified. While the Debian handler is executed, the handler for Red Hat will be skipped, because the when condition doesn’t match ( ansible_distribution == "RedHat").

This solution can be useful for example to manage certificate authorities, where different commands should be executed after adding a new certificate. Debian => /usr/sbin/update-ca-certificates, RedHat => /bin/update-ca-trust.

Please feel free to leave a comment, if you’ve got another solution.

One Comment

  • Tomáš Havlas Reply

    I really like your idea, but I don’t like listing handlers for all the possible distributions in notify, so why don’t use a variable when calling a handler. Simply replacing handlers in your example with following “{{ ansible_os_family|lower }} handler”, should have the same outcome. I’d like to hear your opinion about this solution.

Leave a Reply

Your email address will not be published. Required fields are marked *