Ansible empty dictionary conditional

ansibleansible-playbook

I had an error when I run this code:

- set_fact:
    my_var: "{{ my_var|default({}) | combine( {item.key: item.value} ) | default({}) }}"
    with_dict: "{{ my_dict }}"
    when: my_id in authorised[item.key]

FAILED! => {"failed": true, "msg": "The conditional check 'my_id in authorises[item.key]' failed. The error was: error while evaluating conditional (my_id in authorised[item.key]): Unable to look up a name or access an attribute in template string ({% if my_id in authorised[item.key] %} True {% else %} False {% endif %}).\nMake sure your variable name does not contain invalid characters like '-': argument of type 'StrictUndefined' is not iterable\n\nThe error appears to have been in '': but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:…

my_id is a global variable and authorised is an empty dictionary (authorised: {} )

is there a way to add a conditional to skip the tasks when authorised is an empty dictionary. I have just tried

when: authorised is defined
when: authorised

but it doesn't work. any suggestions?

Best Answer

I'm hoping you figured this out on your own, but the issue is that the with and when clauses are improperly indented. As written, they are attributes of the module not a loop and a conditional on the task.

Corrected:

- set_fact:
    my_var: "{{ my_var|default({}) | combine( {item.key: item.value} ) | default({}) }}"
  with_dict: "{{ my_dict }}"
  when: my_id in authorised[item.key]