dannyman.toldme.com


Ansible, Technical

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.

Read More

Next:
Previous:
Categories: Ansible, Technical

Discover more from dannyman.toldme.com

Subscribe now to keep reading and get access to the full archive.

Continue reading