with_items task and when: statement

What is the proper way to skip a with_items tasks if the with_items variable is undefined ?

I’ll try to explain my use case:
I have some variable defined via the group_vars

And I want to do loop over this variable only if it is defined.

Before ansible 2 it worked without problem
with a playbook like

`

The correct way is to just drop the when statement and rely on the |default filter:

tasks:

  • name: “some loop”
    debug: var=item
    with_items:
  • “{{ my_var|default() }}”

when statements are evaluated for every iteration of the loop, not before the loop. So they are evaluated after ansible attempts to start looping.

The other thing you could do is define an empty value in a role default,
if you're in a role. (There doesn't seem to be a way to do that if you're
not in a role, i.e. to define a playbook default that can be overridden by
group or host variables, at least not that I see in the precedence list at
https://docs.ansible.com/ansible/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable .)

                                      -Josh (jbs@care.com)

(apologies for the automatic corporate disclaimer that follows)

This email is intended for the person(s) to whom it is addressed and may contain information that is PRIVILEGED or CONFIDENTIAL. Any unauthorized use, distribution, copying, or disclosure by any person other than the addressee(s) is strictly prohibited. If you have received this email in error, please notify the sender immediately by return email and delete the message and any attachments from your system.