在覆盖现有变量时,我发现了Ansible的set_fact
模块的某些意外行为。
我尝试使用Ansible设置以下“代码”(JavaScript中的示例):
let old_var = "test"
let cache_var = old_var
let new_var = "hacked"
console.log(old_var) // "test"
console.log(cache_var) // "test"
console.log(new_var) // "hacked"
old_var = new_var
console.log(old_var) // "hacked"
console.log(cache_var) // "test"
console.log(new_var) // "hacked"
这是我的结果:
---
- hosts: 127.0.0.1
connection: local
vars:
old_var: test
cache_var: "{{ old_var }}"
new_var: hacked
tasks:
- debug:
var: old_var
- debug:
var: cache_var
- debug:
var: new_var
- set_fact:
old_var: "{{ new_var }}"
- debug:
var: old_var
- debug:
var: cache_var
- debug:
var: new_var
但是Ansible的输出对我来说是意外的:
PLAY [127.0.0.1] ************************************************************
TASK [Gathering Facts] ******************************************************
ok: [127.0.0.1]
TASK [debug] ****************************************************************
ok: [127.0.0.1] => {
"old_var": "test"
}
TASK [debug] ****************************************************************
ok: [127.0.0.1] => {
"cache_var": "test"
}
TASK [debug] ****************************************************************
ok: [127.0.0.1] => {
"new_var": "hacked"
}
TASK [set_fact] *************************************************************
ok: [127.0.0.1]
TASK [debug] ****************************************************************
ok: [127.0.0.1] => {
"old_var": "hacked"
}
TASK [debug] ****************************************************************
ok: [127.0.0.1] => {
"cache_var": "hacked"
}
TASK [debug] ****************************************************************
ok: [127.0.0.1] => {
"new_var": "hacked"
}
PLAY RECAP ******************************************************************
127.0.0.1 : ok=8 changed=0 unreachable=0 failed=0
有人可以解释一下,为什么set_fact
也会覆盖cache_var
吗,我可以解决这个问题吗?
答案 0 :(得分:0)
我想出了一个解决方法:您也需要使用set_fact
设置相关事实,固定示例是:
---
- hosts: 127.0.0.1
connection: local
vars:
old_var: test
new_var: hacked
tasks:
- set_fact:
cache_var: "{{ old_var }}"
- debug:
var: old_var
- debug:
var: cache_var
- debug:
var: new_var
- set_fact:
old_var: "{{ new_var }}"
- debug:
var: old_var
- debug:
var: cache_var
- debug:
var: new_var
也许有更好的解决方案,但这可行。