警告:Ansible 正在评估裸变量.如何正确实现这一点?



我的 Ansible 条件语句计算不正确。

- name: A
shell:
cmd: /usr/local/bin/is_A_OK #returns bash true or false (not strings)
register: is_A_OK
- name: B
shell:
cmd: /usr/local/bin/is_B_OK 
register: is_B_OK
- name: reboot if both are OK
reboot:
when:
- is_A_OK
- is_B_OK

[弃用警告]:将"is_A_ok"评估为裸变量,此行为将消失,将来可能需要在表达式中添加 |bool。另请参阅CONDITIONAL_BARE_VARS配置切换。此功能将在版本 2.12 中删除。

但是,逻辑工作正常,当两个变量都为 true 时,将执行重新启动。但是我不能保持原样,因为此功能将在 2.12 版中删除。

仅供参考,bash 脚本的结论是这样的:

if [[ "$my_var" == true ]]; then
true
else
false
fi

我正在运行 Arch Linux,所以 bash 是新的。

警告加上 ansible 文档让我认为这是正确的:

- name: reboot if OK
reboot:
when:
- is_A_OK|bool
- is_B_OK|bool

警告消失,但不会预先启动,即使两个变量都为 true。我想我不明白文档。(我是 Ansible 的新手。

我发现了这个问题,但它无关紧要: Ansible 条件语句未正确计算 - 堆栈溢出 Ansible 条件语句未正确求值

我做错了什么,不明白什么?

简短回答:测试已注册字典的属性rc或使用任务结果来测试成功。

详细信息:命令的返回码存储在已注册字典的属性rc中。命令

- command: /bin/true
register: result_A
- debug:
var: result_A.rc
- debug:
msg: "{{ (result_A is success)|ternary('OK', 'KO') }}"
- debug:
msg: "{{ result_A|ternary('OK', 'KO') }}"

返回rc=0作为/bin/true的结果。使用任务结果来测试成功与否。测试裸变量result_A会给出True,因为变量不为空。它还会产生弃用警告。

"result_A.rc": "0"
"msg": "OK"
"msg": "OK"

/bin/false

命令的情况下
- command: /bin/false
register: result_B
ignore_errors: true
- debug:
var: result_B.rc
- debug:
msg: "{{ (result_B is success)|ternary('OK', 'KO') }}"
- debug:
msg: "{{ result_B|ternary('OK', 'KO') }}"

返回rc=1,任务将在没有ignore_errors: true的情况下失败。

致命: [本地主机]: 失败! => {"已更改": 真, "cmd": ["/bin/false"], "delta": "0:00:00.003322", "结束": "2020-06-14 07:07:17.620345", "msg": "非零返回代码", "RC": 1, "开始": ">

2020-06-14 07:07:17.617023", "stderr": ", "stderr_lines": [], "stdout": ", "stdout_lines": []} ...忽略

测试成功失败,result_B测试会给出True,因为变量不为空。


"result_B.rc": "1"
"msg": "KO"
"msg": "OK"

最新更新