I want to combine a loop in ansible with a when-statement applied to it. When-statements are applied to each loop iteration however, which takes away the possibility to apply one to the complete loop. Does anyone know how to do this?
I've run into this problem before, but in this specific case it concerns a variable that might or might not exist. What I would want to do is something like:
- name: Loop
debug:
msg: "{{ item }}"
with_items: x.y|default([])
but-only-run-this-loop-when: x is defined
The default-filter takes care of those instances where y is not defined. Since in my case x might als be not defined, I need the but-only-run-this-loop-when. Obviously, this is not a real ansible statement. What should I use in stead?
Currently, I use something horrible like:
- name: kludge1
set_fact:
fake_y : "{{ [] }}"
- name: kludge2
set_fact:
fake_y : "{{ x.y|default([]) }}"
when: x is defined
- name: Loop
debug:
msg: "{{ item }}"
with_items: '{{ fake_y }}'
With for example in host_vars:
x:
y:
- "foo"
- "bar"
But I'm sure that's not the way to go.
There's similar answer here. You can use several defaults in a row:
And there is no way to bound
when
statement to looped task as a whole (at least in current Ansible 2.2).