我想根据 Linux 发行版定义一个全局变量 (_cfg_chrony):如果操作系统系列是 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"
如何正确设置?
答案1
在任务中定义事实
- 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')) }}"