Ansible set_fact 不会改变变量值 [英] Ansible set_fact doesn't change the variable value

查看:26
本文介绍了Ansible set_fact 不会改变变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景 ansible-playbook 被调用并传入额外的变量:

Scenario ansible-playbook is called with passed in extra var:

-e my_var=init_value

然后在角色代码中,该值应该通过 set_fact 调用更改(变量 other_var 值为new_value"):

Then in a role code the value is supposed to change via set_fact call (variable other_var value is "new_value"):

set_fact: my_var: {{ other_var }}

这会产生一个很好的输出,据说可以确认更改:

This results in a nice output supposedly confirming alteration:

{"ansible facts": {"my_var": "new_value"}}

但是在更改变量后回显变量显示旧值:

However echoing the variable after changing it shows the old value:

echo {{ my_var }}
-> "echo init_value"

补充一点,当我在上面的例子中设置两个变量时:

To add to that, when I set two variables in the above example:

set_fact: my_var: {{ other_var }}
set_fact: new_var: {{ other_var }}

new_var 设置正确.

The new_var is set properly.

变量在某种程度上是不可变的吗?如何使用 set_fact 更新变量的值?

Is the variable in some way immutable? How to use the set_fact to update the variable's value?

推荐答案

set_fact 模块有效地添加了另一个宿主事实,即.发现的有关系统的事实".从文档(http://docs.ansible.com/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) 你可以看到这些事实的优先级很低,并且会被 extra-vars 和其他各种覆盖东西.

The set_fact module effectively adds another host fact, ie. "a fact discovered about the system". From the documentation (http://docs.ansible.com/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) you can see that those facts have low priority, and will be overridden by extra-vars and various other things.

这可能会令人困惑,因为使用 set_fact 会使您看起来好像在那时正在更改变量的值,但也许名称是理解的关键 - 它不是set_variable",它是set_(host)fact",并且主机事实具有低优先级.优先级比赋值的顺序更重要.

This can be confusing because using set_fact can make it seem like you are changing the value of the variable at that point, but maybe the name is the key to understanding - it's not 'set_variable', it's 'set_(host)fact', and host facts have low precedence. Precedence is more important than the order in which the value is assigned.

如果您想通过 extra-vars 提供一个稍后被覆盖的值,一种解决方法是通过 set_fact 将该 extra-vars 值重新分配给不同的变量剧本的开始,然后再次使用 set_fact 重新分配该新变量.由于它们具有相同的优先级,因此覆盖"应该按您的预期工作.

One workaround if you want to supply a value via extra-vars that gets overwritten later would be to reassign that extra-vars value to a different variable via set_fact at the start of your playbook, and then reassign that new variable later using set_fact again. Since they're at the same precedence level, the 'overwrite' should work as you would expect.

这篇关于Ansible set_fact 不会改变变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆