我的 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
[DEPRECATION WARNING]: evaluating 'is_A_ok' as a bare variable, this behaviour will go away and you might need to add |bool to the expression in the future. Also see CONDITIONAL_BARE_VARS configuration toggle. This feature will be removed in version 2.12.
但是,逻辑工作正常,并且当两个变量都为真时执行重启。但我不能让它保持原样,因为此功能将在 2.12 版中删除。
仅供引用,bash 脚本的结尾如下:
if [[ "$my_var" == true ]]; then
true
else
false
fi
我正在运行 Arch Linux,所以 bash 是新的。
警告加ansible docs让我认为这是正确的:
- name: reboot if OK
reboot:
when:
- is_A_OK|bool
- is_B_OK|bool
警告消失,但不会执行重启,即使两个变量都为真。我想我不明白文档。 (我是 Ansible 的新手。)
我发现了这个问题,但它不相关: Ansible 条件语句未正确评估 - 爱编程的大狗 Ansible conditional statements not evaluating correctly
我做错了什么,没有理解?
最佳答案
简答:要么测试注册字典的属性rc
,要么使用task results测试成功。
详细信息:命令的返回码保存在注册字典的属性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') }}"
作为 /bin/true
的结果返回 rc=0
。使用 task results测试成功。裸变量 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
,任务将失败。
fatal: [localhost]: FAILED! => {"changed": true, "cmd": ["/bin/false"], "delta": "0:00:00.003322", "end": "2020-06-14 07:07:17.620345", "msg": "non-zero return code", "rc": 1, "start": "2020-06-14 07:07:17.617023", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []} ...ignoring
测试成功失败,result_B
测试给出 True
,因为变量不为空。
"result_B.rc": "1"
"msg": "KO"
"msg": "OK"
关于ansible - 警告 : Ansible evaluating bare variable. 如何正确实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62368115/