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

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

问题描述

情景ansible-playbook通过传入额外的var来调用:

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 )事实",并且托管事实优先级较低.优先级比分配值的顺序重要.

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天全站免登陆