Ansible 组变量优先级

Ansible group vars priority

假设我在 group_vars 中有 3 个文件:

abc.yml
all.yml
xyz.yml

和他们里面定义的同一个变量:

- my_var: abc
- my_var: all
- my_var: xyz

Ansible documentation 说:

Within any section, redefining a var will overwrite the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a play’s vars: section, the 2nd one wins.

是否表示加载顺序是字母顺序,abc.yml优先级最低,而xyz.yml最高,还是取决于hosts中的组顺序?

加载顺序是什么?


有趣的是,改变 hosts 中组的顺序也会改变结果,但方式不可预测。

我尝试了 运行 ansible-playbook my_var.yml -c local(只有 returns 变量值)的所有组合:

[all]
localhost

[xyz]
localhost

[abc]
localhost

但我还是不明白它是如何工作的。

我想说 Ansible 在这种情况下的行为是未指定的。

看起来来自 Ansible git 存储库的以下问题可能已经解决了您描述的行为:Ansible group_vars from inventory don't support repeated hosts

查看相关提交中的 code changes,看起来现在组应该按深度排序,然后按名称排序(按字母顺序)。

值得注意的是,此行为可能会因您使用的 Ansible 版本而异 运行,因为这些更改仅合并到 Ansible 存储库的 stable-2.2 分支中。

ansible 文档现在对这种行为非常清楚...

https://docs.ansible.com/ansible/2.6/user_guide/intro_inventory.html#how-variables-are-merged

When groups of the same parent/child level are merged, it is done alphabetically, and the last group loaded overwrites the previous groups. For example, an a_group will be merged with b_group and b_group vars that match will overwrite the ones in a_group.

Starting in Ansible version 2.4, users can use the group variable ansible_group_priority to change the merge order for groups of the same level (after the parent/child order is resolved). The larger the number, the later it will be merged, giving it higher priority. This variable defaults to 1 if not set. For example:

a_group:
    testvar: a
    ansible_group_priority: 10
b_group
    testvar: b

In this example, if both groups have the same priority, the result would normally have been testvar == b, but since we are giving the a_group a higher priority the result will be testvar == a.