ansible:根据ansible_os_family设置变量

Sha*_*lan 6 ubuntu redhat ansible

使用ansible 2.0.2.0,我想将文件部署到目标服务器。Debian 和 RedHat 系列上的目标文件夹不同。

我已经使用了set_fact,但似乎它使用了最后定义的,忽略了when:选项。

我不想使用变量文件,因为这个变量仅在这个特定的剧本中使用

将复制任务复制到 RedHat 和 Debian 中虽然可能,但会使将来的维护变得复杂。

下面的 playbook 在 Ubuntu 服务器上执行时将会失败,因为目标已扩展为 /etc/nrpe.d(适用于 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"
Run Code Online (Sandbox Code Playgroud)

Sha*_*lan 4

我已经解决了我自己的问题。

本质上,您可以根据 os_family 设置变量,但必须正确执行。

请参阅下面我的固定剧本:

---
- 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
Run Code Online (Sandbox Code Playgroud)