Reputation: 6337
My Ansible conditional statements are not evaluating correctly.
- 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.
However, the logic works correctly, and the reboot is performed when both variables are true. But I can't leave it as-is given that this feature will be removed in version 2.12.
FYI, the bash scripts conclude like this:
if [[ "$my_var" == true ]]; then
true
else
false
fi
I'm running Arch Linux, so bash is new.
The warning plus the ansible docs made me think this would be correct:
- name: reboot if OK
reboot:
when:
- is_A_OK|bool
- is_B_OK|bool
The warning goes away, but the reboot is not preformed, even when both variables are true. I guess I don't understand the docs. (I'm new to Ansible.)
I found this question, but it is not relevant: Ansible conditional statements not evaluating correctly - Stack Overflow Ansible conditional statements not evaluating correctly
What am I doing wrong and not understanding?
Upvotes: 2
Views: 4393
Reputation: 68034
Short answer: Either test the attribute rc
of the registered dictionary or use task results to test success.
Details: The return code of the command is stored in the attribute rc
of the registered dictionary. The command
- 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') }}"
returns rc=0
as a result of /bin/true
. Use task results to test success. Testing of bare variable result_A
gives True
because the variable is not empty. It also produces the deprecation warning.
"result_A.rc": "0"
"msg": "OK"
"msg": "OK"
In the case of /bin/false
the command
- 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') }}"
returns rc=1
and the task would fail without 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
The test success fails and testing of result_B
gives True
because the variable is not empty.
"result_B.rc": "1"
"msg": "KO"
"msg": "OK"
Upvotes: 6