Bootstrap FreeKB - Ansible - when variable is empty or not empty
Ansible - when variable is empty or not empty

Updated:   |  Ansible articles

Let's say you have a playbook that should only be executed when the "foo" variable is defined and contains a value. The length filter is used to determine the length of the foo variable. 

---
- hosts: all
  vars:
    foo: ""
  tasks:
    - name: fail when the 'foo' variable is undefined
      fail: 
       msg: the 'foo' variable is undefined
      when: foo is undefined

    - name: fail when the 'foo' variable is empty
      fail: 
       msg: the 'foo' variable is empty
      when: foo | length == 0

 

Invoking this playbook should return something like this. The ansible-doc fail command can be used to show the Ansible documention on the fail module.

When fail evaluates to true, all of the subsequent tasks are skipped.

PLAY [all]

TASK [fail when the 'foo' variable is undefined] 
skipping: [server1.example.com]

TASK [fail when the 'foo' variable is empty]
fatal: [server1.example.com]: FAILED => {"changed": false, "msg": "the 'foo' variable is empty"}

PLAY RECAP
server1.example.com : ok=2  changed=0  unreacable=0  failed=1

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d4785c in the box below so that we can be sure you are a human.