How to check if multiple ansible variables are defined without warnings?

Viewed 2259

I have a task at the beginning of a role:

- name: check if pg_* variables are defined
  fail: msg="variable {{item}} is undefined"
  when: "{{item}} is undefined"
  with_items:
    - pg_dbname
    - pg_host
    - pg_port
    - pg_username
    - pg_password

But newer versions of Ansible raise the following warning:

[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{item}} is undefined

Removing the Jinja2 braces when: item is undefined doesn't work because the final evaluation is essentially equivalent to:

"pg_dbname" is undefined` # False
"pg_host" is undefined` # False
.
.
"pg_password" is undefined` # False

This is not what I want.

1 Answers

Variable called item is always defined inside with_items loop and your task should have skipped status for all five strings that you assign to it.


You want to check if the actual variable exists:

when: vars[item] is undefined
Related