Harinder
Harinder

Reputation: 21

Ansible condition on dictionary item

I have one dictionary list defined:

members_list:
          any:
             name: any
             username: any
          anyone:
             name: 
             username: anyone

In my Ansible playbook, I am running multiple docker containers:

docker_container:
     name: "{{ item.key }}"
when: "{{ item.key }} != any"
with_dict: "{{ members_list }}"

But I am getting following error:

The conditional check '{{ item.key }} != any' failed. The 
error was: error while evaluating conditional ({{ item.key 
}} != any): 'any' is undefined   

When I run the playbook without when conditional operator it works fine.

Thanks in advance.

Upvotes: 0

Views: 5412

Answers (1)

larsks
larsks

Reputation: 311606

You need to quote the word any, because otherwise it is interpreted as a variable reference. Also, you don't need Jinja templating markers in a when expression (the expression is already evaluated as a jinja expression):

- docker_container:
       name: "{{ item.key }}"
  when: "item.key != 'any'"
  with_dict: "{{ members_list }}"

I find nested quotes like this can be confusing, and often opt for one of YAMLs alternative quoting mechanisms, e.g.:

- docker_container:
       name: "{{ item.key }}"
  when: >-
    item.key != 'any'
  with_dict: "{{ members_list }}"

This is identical to the previous version; I just find it easier to read and understand.

Upvotes: 1

Related Questions