有条件地包含 ansible 角色变量文件

Conditionally incude ansible role's variable files

通常我会在 roles/myrole/defaults/main.yml 中转储变量。我不需要明确地包含它们 - 这是自动为我完成的。

但是假设我需要支持 Debian 和 CentOS,并且具有不同值的相同变量。常见的建议是:

roles/myrole/defaults/main.yml       # common defaults
roles/myrole/vars/debian.yml         # debian overrides
roles/myrole/vars/centos.yml         # centos overrides

然后我们应该"conditionally include"正确的变量集。

但是具体在哪里?在主任务中,或 "main" 变量文件,或其他地方?

Q: "But where exactly? In the main task, or a "main" variables file, or somewhere else?"

在主线任务中,我会说。例如

- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"

用户可以在 vars 中保留自定义变量。将默认值放入目录 vars/defaults。这样,自定义变量将在角色的潜在更新后继续存在。

# Default variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars/defaults"

# Custom variables
- include_vars: "{{ item }}"
  with_first_found:
    - files:
        - "{{ ansible_distribution }}-{{ ansible_distribution_release }}.yml"
        - "{{ ansible_distribution }}.yml"
        - "{{ ansible_os_family }}.yml"
        - "default.yml"
        - "defaults.yml"
      paths: "vars"

available at GitHub