Checking for undefined, empty or null variables

This is my example playbook:

This should work

when: vars[item] is not defined or vars[item] == ""

I was too fast with my answer.

/roles/defaults/main.yml

I was too fast with my answer.

/roles/defaults/main.yml
---
applicationname: ""
description: ""

required_vars:
- applicationname

<snip />

But this doesn't work:
- name: check required vars undefined
  fail: msg="Variable '{{ item }}' is null"
  when: vars[item] is not defined
  with_items: "{{ required_vars }}"

It does, when I do a test

Hi Kai

You used the variable in a playbook, maybe that works. But I want to make sure that the role is not being executed when someone forgets to set the variable.
So the trick here is: “{{ APPLICATIONNAME }}” is not set.
Normaly this is a variable in vars/app1.yml
Here is the full code:

/vars/app1.yml

Hi Kai

You used the variable in a playbook, maybe that works. But I want to make
sure that the role is not being executed when someone forgets to set the
variable.
So the trick here is: "{{ APPLICATIONNAME }}" is not set.
Normaly this is a variable in vars/app1.yml
Here is the full code:

The full code make is clear whats happening.

/vars/app1.yml
---
#APPLICATIONNAME: "app1"
#normally this var is set, but we want to provoke an error

playbook.yml
---
- name: play1
   hosts: app1
   vars_files:
   - "vars/app1.yml"

  tasks:
  - include_role:
      name: role1
    vars:
      applicationname: "{{ APPLICATIONNAME }}"
      description: "{{ DESCRIPTION }}"

/roles/defaults/main.yml
---
required_vars:
- applicationname

applicationname: ""
description: ""

role default will always set applicationname to "" and therefor always be defined.
So checking if that variable "is not defined" has no purpose since it will be defined.

I don’t fully agree with you.
Because I set “applicationname” to “{{ APPLICATIONNAME }}” when I call the role in the playbook:

  • include_role:
    name: role1
    vars:
    applicationname: “{{ APPLICATIONNAME }}”
    description: “{{ DESCRIPTION }}”

Problem is, that “{{ APPLICATIONNAME }}” at this point is undefined.

And again, I think the problem with

  • name: check required vars when applicationname is not defined
    debug: msg=“Variable ‘{{ item }}’ is not defined”
    when: vars[item] is not defined
    with_items: “{{ required_vars }}”

is, that vars[item] is not undefined.
Why? Because “applicationname” seems to have a value:

TASK [role1 : debug] ***********************************************

ok: [server1] => {
“vars”: {

“applicationname”: “{{ APPLICATIONNAME }}”
}
}

Maybe it is misinterpreted as a string “{{ APPLICATIONNAME }}”
Therefore, when: vars[item] is not defined does not work as expected

Hope you can follow me.