Ansible 组变量优先级 [英] Ansible group vars priority
问题描述
假设我在 group_vars 中有 3 个文件:
Let's say I have 3 files in group_vars:
abc.yml
all.yml
xyz.yml
以及在它们中定义的相同变量:
And the same variable defined in them:
- my_var: abc
- my_var: all
- my_var: xyz
Ansible 文档 说:
Ansible documentation says:
在任何部分中,重新定义一个 var 都会覆盖之前的实例.如果多个组具有相同的变量,则最后加载的组获胜.如果您在一个 play 的 vars: 部分定义了两次变量,则第 2 个获胜.
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
的优先级最高,还是取决于组的顺序主机
?
Does it mean that load order is alphabetical one and abc.yml
has the lowest priority, whereas xyz.yml
the highest, or it depends on order of groups in hosts
?
加载顺序是什么?
有趣的是,改变 hosts
中组的顺序也会改变结果,但方式不可预测.
It is interesting, that changing the order of groups in hosts
changes results as well, but in unpredictable way.
我尝试使用以下所有组合运行 ansible-playbook my_var.yml -c local
(仅返回变量值):
I tried running ansible-playbook my_var.yml -c local
(that only returns variable value) with all the combinations of:
[all]
localhost
[xyz]
localhost
[abc]
localhost
但我仍然无法弄清楚它是如何工作的.
but I still cannot figure out how it works.
推荐答案
ansible 文档现在对这种行为非常清楚...
The ansible documentation is quite clear on this behaviour now...
https://docs.ansible.com/ansible/2.6/user_guide/intro_inventory.html#how-variables-are-merged
当同一父/子级别的组合并时,按字母顺序完成,最后加载的组覆盖之前的组.例如,a_group 将与 b_group 合并,匹配的 b_group 变量将覆盖 a_group 中的变量.
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.
从 Ansible 2.4 版本开始,用户可以使用组变量 ansible_group_priority 来更改同级别组的合并顺序(在父/子顺序解决后).数字越大,合并越晚,优先级越高.如果未设置,此变量默认为 1.例如:
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
在这个例子中,如果两个组具有相同的优先级,结果通常是 testvar == b,但由于我们给 a_group 一个更高的优先级,结果将是 testvar == a.
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.
这篇关于Ansible 组变量优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!