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
Possibly-Related Posts

Comment

Leave a comment . . .

Tiny Print:

  1. For private messages, e-mail me: dannyman@toldme.com.
  2. You must provide an e-mail address.
  3. You can use a bogus e-mail address, but I like to know who you are.
  4. I will not spam you. I will not publish or share your e-mail address.
  5. First-time commenters will be held for review.
  6. You can use these HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>