2
votes

I'm trying to write a playbook that will load vars from a group vars file then check if a variable exists

my playbook is like this:

---
- hosts: "{{ target }}"
  roles:
    - app

  tasks:
  - name: alert if variable does not exist
    fail:
      msg: "{{ item }} is not defined"
    when: "{{ item }}" is not defined
    with_items:
      - country
      - city
      - street
...

My inventory file contains

[app]
ansible-slave1
ansible-slave2

[db]
ansible-db

[multi:children]
app
db

and I have the roles/app/vars/main.yml containing

country: "France"
city: "Paris"

What I was expecting is the playbook to output "street is not defined" but I have a syntax issue I can't resolve

[vagrant@ansible-master vagrant]$ ansible-playbook --inventory-file=ansible_master_hosts test_variables.yml --extra-vars "target=ansible-slave1" --syntax-check
ERROR! Syntax Error while loading YAML.

The error appears to have been in '/vagrant/test_variables.yml': line 10, column 24, but may be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

  msg: "{{ item }} is not defined"
when: "{{ item }}" is not defined
                   ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

I'd be happy with any hints.

Thanks

2

2 Answers

2
votes

there is on open issue conditional is defined fails to capture undefined var .

as a workaround I'd suggest to change the where condition to the following:

when: "{{ item }}" == ""

2
votes

You have "" in invalid place of "when" statement. This should be like this:

    msg: "{{ item }} is not defined"
 when: "{{ item }} is not defined"

So the output will be:

failed: [hostname] (item=street) => {"changed": false, "item": "street", "msg": "street is not defined"}