Conditional with dict2item is falied

Hi guys,

I have a task with equal below, but when I validate it is defined it not recognized.

  • name: include vars virtual_machine
    include_tasks: virtual_machine.yml
    when:
  • gms_az_vm_action == ‘create_virtual_machine’
  • virtual_machine is defined
    loop: “{{ virtual_machine|dict2items }}”

How I do for doesn’t read loop and not stop playbook when virtual_machine not defined?

In the case of using when and loop, the when statements is applied to each iteration of the loop, and not before it.

As such, you cannot prevent a loop from happening using a when statement.

Instead you want to do this in loop, like:

loop: ‘{{ virtual_machine|default({})|dict2items }}’

OK, thanks!

Hi guys,

I have a task with equal below, but when I validate it is defined it not recognized.
- name: include vars virtual_machine
include_tasks: virtual_machine.yml
when:
- gms_az_vm_action == 'create_virtual_machine'
- virtual_machine is defined
loop: "{{ virtual_machine|dict2items }}"

How I do for doesn't read loop and not stop playbook when virtual_machine not defined?

  loop: "{{ virtual_machine | default({}) | dict2items }}"

This produces an empty dict ({}) if virtual_machine is undefined and the loop goes over zero iterations.

Regards
        Racke