Ansible "The conditional check failed" - Fix when/Variable Errors
A when: condition could not be evaluated because a variable it references is undefined or the wrong type. The Jinja2 expression errors instead of returning true/false.
What this error means
A task fails with The conditional check failed, usually adding that a variable is undefined. It is deterministic - the same inventory/vars fail the same way. The play stops at that task.
fatal: [app01]: FAILED! => {"msg": "The conditional check 'deploy_env == \"prod\"'
failed. The error was: error while evaluating conditional (deploy_env == \"prod\"):
'deploy_env' is undefined"}Common causes
Variable undefined in this context
The variable referenced in when: was never set for this host/play - missing from inventory, group_vars, or --extra-vars - so Jinja2 cannot evaluate it.
Type or quoting mistake
Comparing a string to a bool, or mis-quoting so a literal is read as a variable, makes the conditional raise rather than return a boolean.
How to fix it
Guard against undefined with a default
Provide a default so the expression always evaluates, and define required vars explicitly.
- name: Deploy to prod only
ansible.builtin.command: /opt/deploy.sh
when: deploy_env | default('dev') == 'prod'Define the variable for the run
- Set the var in inventory, group_vars/host_vars, or pass
--extra-vars "deploy_env=prod". - Run with
-vto see which variables are actually defined for the host. - Use
is defined/is not definedchecks where a variable may legitimately be absent.
How to prevent it
- Provide
| default(...)for optional variables used in conditionals. - Define required variables explicitly and assert them early with
assert. - Keep types consistent - compare strings to strings, bools to bools.