Ansible

Ansible 使用 When Contition 定義全域變數

  • July 27, 2022

我想定義一個基於Linux發行版的全域變數(_cfg_chrony):如果OS系列是Redhat,定義配置路徑/etc/chrony.conf;如果作業系統系列是 Debian,請定義/etc/chrony/chrony.conf

我試圖在我的劇本開頭做這樣的事情,但似乎它只應用了最後一個變數並忽略了條件:

 vars:
   _cfg_chrony: /etc/chrony.conf
   when: ansible_facts['os_family'] == "RedHat"
   _cfg_chrony: /etc/chrony/chrony.conf
   when: ansible_facts['os_family'] == "Debian"

如何正確設置?

在任務中定義一個事實

- name: "facts for debian - family"
 set_fact:
   _cfg_chrony: /etc/chrony.conf
 when:
   - ansible_os_family == "Debian"

- name: "facts for RH - family"
 set_fact:
   _cfg_chrony: /etc/chrony/chrony.conf
 when:
   - ansible_os_family == "RedHat"

- name: a task
 ansible.builtin.debug:
   var: _cfg_chrony

或另一種更短但可讀性更低的方式:

- name: a task
 ansible.builtin.debug:
   var: _cfg_chrony
 vars:
   _cfg_chrony: "{{ ('/etc/chrony.conf' if (ansible_os_family == 'Debian')) or ('/etc/chrony/chrony.conf' if (ansible_os_family == 'RedHat')) }}"

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