I try to pass a condition to failed_when as a variable in a role:
my-role/defaults/main.yml:
# list of commands to execute in form [command, changed_when, failed_when]
my_commands:
- ["myapp init", "cmd_result.rc == 0", "(cmd_result.rc != 0) and ('Non-critical error' not in cmd_result.stdout) and ('Non-critical error' not in cmd_result.stderr)"]
- [...]
This would allow me to loop through the command list with custom changed_when and failed_when conditions:
if I copy the condition line into failed_when statement explicitly, like failed_when: "(cmd_result.rc != 0) and ('Non-critical error' not in cmd_result.stdout) and ('Non-critical error' not in cmd_result.stderr)", task works
I suppose it may be that
the statement is not evaluated properly
cmd_result variable is not injected into the conditional statement
Can anyone explain this, and maybe suggest an elegant and functional way to get this work?
failed_when is evaluated to literal string ā(cmd_result.rc != 0) and (āNon-critical errorā not in cmd_result.stdout) and (āNon-critical errorā not in cmd_result.stderr)ā
What you want is to have same literal string ā(cmd_result.rc != 0) and (āNon-critical errorā not in cmd_result.stdout) and (āNon-critical errorā not in cmd_result.stderr)ā to be used as condition.
In your case there is only one evaluation - my_command[2] is evaluated to string, ansible does just one evaluation.
The solution is
failed_when: "{{ my_command[2] }}"
In this case {{ my _command[2] }} is evaluated to as string (variable evaluation) and when string (condition you wrote) is evaluated as condition.