Ubuntu – ansible: setting variable according to ansible_os_family

ansibleredhatUbuntu

Using ansible 2.0.2.0, I want to deploy a file to destination server. The destination folder is different on Debian and RedHat family.

I have used set_fact, but it seems that it used the last defined, ignoring the when: option.

I don't want to use variable files, because this variable is only used in this particular playbook

Duplicating the copy task into RedHat and Debian, while possible, will complicate maintenance in the future.

The playbook below will fail when executed against Ubuntu server because destination was expanded to become /etc/nrpe.d which is for RedHat

- set_fact:
  destination: "/etc/nagios/nrpe.d/"
  when: ansible_os_family == "Debian"

- set_fact:
  destination: "/etc/nrpe.d/"
  when: ansible_os_family == "RedHat"

- name: Ensure Nagios custom checks directory exists
  file: path=/usr/local/lib/nagios/plugins state=directory mode=0755

- name: Install check_cpu_steal
  copy: src=eprepo/sysadmin/nagios_checks/check_cpu_steal dest=/usr/local/lib/nagios/plugins/check_cpu_steal mode=0755 owner=root group=root

- name: Install check_cpu_steal command to /etc/nrpe.d
  copy: src=eprepo/sysadmin/files/check_cpu_steal.conf dest="{{ destination }}/check_cpu_steal.conf mode=0644 owner=root group=root"

Best Answer

I have solved my own problem.

In essence, you can set variable according to os_family, but you have to do it correctly.

See my fixed playbook below:

---
- name: Set fact for Debian
  set_fact:
    destination: "/etc/nagios/nrpe.d/"
    nrpe_server: "nagios-nrpe-server"
  when: ansible_os_family == "Debian"

- name: Set fact for RedHat
  set_fact:
    destination: "/etc/nrpe.d/"
    nrpe_server: "nrpe"
  when: ansible_os_family == "RedHat"

- name: Ensure Nagios custom checks directory exists
  file: path=/usr/local/lib/nagios/plugins state=directory mode=0755

- name: Install check_cpu_steal nagios check
  copy: src=eprepo/sysadmin/nagios_checks/check_cpu_steal dest=/usr/local/lib/nagios/plugins/check_cpu_steal mode=0755 owner=root group=root

- name: Install check_cpu_steal nrpe config
  copy: src=eprepo/sysadmin/files/check_cpu_steal.conf dest="{{ destination }}/check_cpu_steal.cfg" mode=0644 owner=root group=root

- name: Restart nrpe daemon
  service: name={{ nrpe_server }} state=restarted