ansible - 防止 Ansible 2 中出现重复的键警告

标签 ansible ansible-2.x

我在角色中使用了大量 YAML anchor 和引用,以将逻辑保持在一个位置,而不是在多个任务中重复自己。以下是一个非常非常基本的示例。

- &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”条件。您只是想干燥。

因此,我没有两次定义整个任务,而是使用第一个任务的 anchor ,并将其所有内容合并到一个新任务中,然后覆盖不同的部分。效果很好。

需要明确的是,这是基本的 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 现在具有在任务中多次定义键时进行投诉的功能。它仍然有效,但在运行剧本时会产生不必要的噪音:

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_warningscommand_warnings 。有没有办法也防止这种警告?

最佳答案

迟到了,我不同意其他答案并支持 YAML 合并。 Playbook 布局非常主观,最适合您的布局取决于您需要描述的配置。

是的,ansible 具有与 includes 类似合并的功能或 with_items/with_dict loops .

我发现 YAML 合并的用例是任务只有几个异常值,因此可以覆盖的默认值是最紧凑和可读的表示。 ansible 提示完全有效的语法是令人沮丧的。

relevant ansible code中的评论建议开发人员比用户更了解。

Most of this is from yaml.constructor.SafeConstructor. We replicate it here so that we can warn users when they have duplicate dict keys (pyyaml silently allows overwriting keys)

PyYAML 默默地允许“覆盖”键,因为键优先级在 the YAML standard 中显式处理。 .

关于ansible - 防止 Ansible 2 中出现重复的键警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34940352/

相关文章:

ansible - Ansible处理程序-独占重启或重新加载

Ansible 远程模板

python - ansible 条件模板

ansible - 通过ansible运行Python脚本

ansible - 我可以指定参数不能与 Ansible 模块规范中的特定选项一起使用吗?

random - 如何创建随机字符串并在 Ansible 的 jinja 中使用它

Ansible-忽略错误时间

ubuntu - Ansible:本地 .ansible 文件夹是以 root 为所有者创建的(权限错误)

google-compute-engine - Google Compute Engine 的 Ansible 提供的 JSON 凭证文件在哪里?

stdout - Ansible寄存器结果result.stdout result.rc等dict变量未找到,如何使用直到循环