Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ansible

jinja2

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.

like image 732
Satyajeet Kanetkar Avatar asked Mar 08 '23 12:03

Satyajeet Kanetkar


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
like image 174
techraf Avatar answered May 09 '23 09:05

techraf