Is it possible to force Ansible when replacing the var in yml files, which is undefined, throw out an error instead silently replaced by an empty string?
Asked
Active
Viewed 1.4k times
4 Answers
9
Yes, it is possible. Check the online documentation, under accessing complex variable data.
An example is provided to do exactly that:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out: this play requires 'bar'"
when: bar is not defined
9
Add this line to the [defaults]
section of your ansible.cfg:
error_on_undefined_vars = True
You'll now get an error message if a variable is undefined.

Lorin Hochstein
- 5,028
- 15
- 56
- 72
-
I believe that option requires 1.3, which is coming soon but has not yet been released. – mblakele Aug 16 '13 at 15:52
1
You can use mandatory-values
If you configure Ansible to ignore undefined variables, you may want to define some values as mandatory. By default, Ansible fails if a variable in your playbook or command is undefined. You can configure Ansible to allow undefined variables by setting DEFAULT_UNDEFINED_VAR_BEHAVIOR to false. In that case, you may want to require some variables to be defined. You can do this with:
{{ variable | mandatory }}

Fangxing
- 121
- 4
1
Define your variables in
roles/<role_name>/defaults/main.yml
like:
SUPERVAR:
VAR1:foo
VAR2:bar
and then do in
roles/<role_name>/tasks/main.yml
like:
- fail: msg="{{ item }} is not defined"
when: not {{ item }}
with_items:
- SUPERVAR.VAR1
- SUPERVAR.VAR2

Ravindranath Akila
- 121
- 4