如何将一个Ansible角色的`defaults / main.yml`文件分割成多个文件?

时间:2018-08-13 08:36:21

标签: ansible ansible-role file-organization

在一些烦人的角色中(例如roles/my-role/),我有一些很大的默认变量文件(defaults/main.yml)。我想将main.yml分成几个较小的文件。可以这样做吗?

我尝试创建文件defaults/1.ymldefaults/2.yml,但是ansible不会加载它们。

2 个答案:

答案 0 :(得分:10)

我在下面描述的功能自Ansible 2.6起就可用,但在v2.6.2中有一个错误修复,而在v2.7中有一个(次要)错误修正。
要查看旧版本的解决方案,请参阅Paul的答案。


defaults/main/

创建一个目录- defaults/main.yml -而不是创建defaults/main/并将所有YAML文件放在其中。

  • defaults/main.yml defaults/main/*.yml

Ansible将在该目录中加载任何*.yml文件,因此您可以将文件命名为roles/my-role/defaults/main/{1,2}.yml

注意,旧文件— defaults/main.yml —一定不存在。参见this Github comment


vars/main/

顺便,上述解决方案也适用于vars/

  • vars/main.yml vars/main/*.yml

更多详细信息

此功能已在v2.6中引入-git commitPull Requestmain Github issue

有两个错误修正:

答案 1 :(得分:1)

如果您不使用2.6(您可能应该使用2.6,但我知道这并不总是一种选择),那么您可能会include_vars有用。

- name: Include vars of stuff.yaml into the 'stuff' variable (2.2).
  include_vars:
    file: stuff.yaml
    name: stuff

- name: Conditionally decide to load in variables into 'plans' when x is 0, otherwise do not. (2.2)
  include_vars:
    file: contingency_plan.yaml
    name: plans
  when: x == 0

- name: Load a variable file based on the OS type, or a default if not found. Using free-form to specify the file.
  include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution }}.yaml"
    - "{{ ansible_os_family }}.yaml"
    - default.yaml

- name: Bare include (free-form)
  include_vars: myvars.yaml

- name: Include all .json and .jsn files in vars/all and all nested directories (2.3)
  include_vars:
    dir: vars/all
    extensions:
        - json
        - jsn

- name: Include all default extension files in vars/all and all nested directories and save the output in test. (2.2)
  include_vars:
    dir: vars/all
    name: test

- name: Include default extension files in vars/services (2.2)
  include_vars:
    dir: vars/services
    depth: 1

- name: Include only files matching bastion.yaml (2.2)
  include_vars:
    dir: vars
    files_matching: bastion.yaml

但是请注意,这是一个任务指令。它不只是能够将其包含到默认文件本身中那样整洁。