首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ansible Variables:覆盖时set_fact的意外行为

Ansible Variables:覆盖时set_fact的意外行为
EN

Stack Overflow用户
提问于 2019-03-22 00:56:25
回答 1查看 33关注 0票数 0

在覆盖现有变量时,我发现了Ansible的set_fact模块的一些意外行为。

我尝试用Ansible设置下面的“代码”(JavaScript中的例子):

代码语言: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"

这是我的结果:

代码语言:javascript
复制
---

- 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的输出对我来说是意想不到的:

代码语言:javascript
复制
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,我能解决这个问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-22 02:15:33

我想出了一个解决办法:你也需要用set_fact设置依赖事实,修正后的例子是:

代码语言:javascript
复制
---
- 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

也许有更好的解决方案,但这是可行的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55285548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档