Ubuntu

ansible:根據ansible_os_family設置變數

  • July 21, 2016

使用 ansible 2.0.2.0,我想將文件部署到目標伺服器。Debian 和 RedHat 系列的目標文件夾不同。

我使用了 set_fact,但似乎它使用了最後定義的,忽略了 when: 選項。

我不想使用變數文件,因為這個變數只在這個特定的劇本中使用

將複製任務複製到 RedHat 和 Debian 中雖然可能,但將來會使維護變得複雜。

下面的劇本在針對 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"

我已經解決了我自己的問題。

本質上,你可以根據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

引用自:https://serverfault.com/questions/790999