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.
On Thu, May 19, 2016 at 11:09 AM, Julien Tognazzi <[email protected]
> wrote:
> 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
> ---
> - hosts: localhost
>
> tasks:
> - name: "some loop"
> debug: var=item
> with_items:
> - "{{ my_var}}"
> when: my_var is defined
>
>
> If my_var is not defined for the current host, the task is skipped without
> error or warning.
>
> But with ansible2 I know have a warning.
> [DEPRECATION WARNING]: Skipping task due to undefined Error, in the future
> this will be a fatal error.. This feature will be removed in a future
> release.
>
> My error is that the when statement is evaluated for each element in the
> loop...
>
> But then my question is how should I do to have the tasks skipped it the
> variable is undefined ?
>
> a workaround to have the same behaviour than ansible 1.x is to use the
> default filter like this
> ---
> - hosts: localhost
>
> tasks:
> - name: "some loop"
> debug: var=item
> with_items:
> - "{{ my_var|default({}) }}"
> when: item is defined
>
> Do you have some other suggestion ?
>
> thanks for your help.
>
> Julien.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/f597b07f-8b8a-4ef9-9dcd-f3440ff494e2%40googlegroups.com
> <https://groups.google.com/d/msgid/ansible-project/f597b07f-8b8a-4ef9-9dcd-f3440ff494e2%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>
--
Matt Martz
@sivel
sivel.net
--
You received this message because you are subscribed to the Google Groups
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/ansible-project/CAD8N0v8FM9KRspOkDG92_aUu5o%3D5z-3yhH8P6a%3D6XhChbjjLSQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.