10

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?

Ryan
  • 5,831
  • 24
  • 72
  • 91

4 Answers4

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
dawud
  • 15,096
  • 3
  • 42
  • 61
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
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