Ansible: Set Conditional Handler
Link: https://dannyman.toldme.com/2014/10/07/ansible-set-conditional-handler/
I have a playbook which installs and configures NRPE. The packages and services are different on Red Hat versus Debian-based systems, but my site configuration is the same. I burnt a fair amount of time trying to figure out how to allow the configuration tasks to notify a single handler. The result looks something like:
# Debian or Ubuntu - name: Ensure NRPE is installed on Debian or Ubuntu when: ansible_pkg_mgr == 'apt' apt: pkg=nagios-nrpe-server state=latest - name: Set nrpe_handler to nagios-nrpe-server when: ansible_pkg_mgr == 'apt' set_fact: nrpe_handler='nagios-nrpe-server' # RHEL or CentOS - name: Ensure NRPE is installed on RHEL or CentOS when: ansible_pkg_mgr == 'yum' yum: pkg={{item}} state=latest with_items: - nagios-nrpe - nagios-plugins-nrpe - name: Set nrpe_handler to nrpe when: ansible_pkg_mgr == 'yum' set_fact: nrpe_handler='nrpe' # Common - name: Ensure NRPE will talk to Nagios Server lineinfile: dest=/etc/nagios/nrpe.cfg regexp='^allowed_hosts=' line='allowed_hosts=nagios.domain.com' notify: - restart nrpe ### A few other common configuration settings ...
Then, over in the handlers file:
# Common - name: restart nrpe service: name={{nrpe_handler}} state=restarted
The trick boiled down to using the set_fact module.