我在我的角色中使用了很多 YAML 锚点和引用来将逻辑保持在一个位置,而不是在多个任务中重复自己。以下是一个非常非常基本的示例。
- &sometask
name: "Some Task"
some_module: with a lot of parameters
with_items: list_A
- <<: *sometask
name: "Some OTHER Task"
with_items: list_B
这个例子可能没有显示这实际上是如何有用的,但它确实有用。想象一下,你遍历一个字典列表,将每个字典的各种键传递给模块,可能有相当复杂的“when”、“failed_when”和“changed_when”条件。你只是想干。
因此,我没有将整个任务定义两次,而是使用第一个锚点并将其所有内容合并到一个新任务中,然后覆盖不同的部分。这很好用。
需要明确的是,这是基本的 YAML 功能,与 Ansible 本身无关。
上述定义的结果(以及 Ansible 在解析 YAML 文件时看到的内容)将评估为:
- name: "Some Task"
some_module: with a lot of parameters
with_items: list_A
- name: "Some Task"
some_module: with a lot of parameters
with_items: list_A
name: "Some OTHER Task"
with_items: list_B
Ansible 2 现在具有在任务中多次定义键时抱怨的功能。它仍然有效,但在运行 playbook 时会产生不必要的噪音:
TASK [Some OTHER Task] *******************************************************
[WARNING]: While constructing a mapping from /some/file.yml, line 42, column 3, found a duplicate dict key (name). Using last defined value only.
[WARNING]: While constructing a mapping from /some/file.yml, line 42, column 3, found a duplicate dict key (with_items). Using last defined value only.
Ansible 配置允许防止deprecation_warnings
和command_warnings
. 有没有办法也可以防止这种警告?