How to run a task when variable is undefined in ansible?

sakhunzai picture sakhunzai · May 8, 2015 · Viewed 193.2k times · Source

I am looking for a way to perform a task when ansible variable is not registers /undefined e.g

-- name: some task
   command:  sed -n '5p' "{{app.dirs.includes}}/BUILD.info" | awk '{print  $2}'
   when: (! deployed_revision) AND ( !deployed_revision.stdout )
   register: deployed_revision

Answer

Kyle picture Kyle · May 8, 2015

From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:

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

So in your case, when: deployed_revision is not defined should work