# Nested conditional loop

**URL:** <https://forum.ansible.com/t/nested-conditional-loop/23432>\
**Category:** Ansible Project\
**Created:** [January 11, 2017, 11:08am UTC](https://forum.ansible.com/t/nested-conditional-loop/23432 "2017-01-11T11:08:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Miguel\_David](https://avatars.discourse-cdn.com/v4/letter/m/ce73a5/32.png) [@Miguel\_David](https://forum.ansible.com/u/Miguel_David)\
**Post date:** [January 11, 2017, 11:08am UTC](https://forum.ansible.com/t/nested-conditional-loop/23432/1 "2017-01-11T11:08:15Z")

</div>

Hi all,

I have a dictionary on my site\_vars.yml something like this:

services:

- name: “service1”  
…  
foo: “bar”

The playbook calls the role:

- name: Configure backend  
hosts: backend  
gather\_facts: true  
become: yes  
roles:
- { role: myrole, type: ‘bar’ }

And on the tasks main.yml

- name: do stuff  
file: path=/var/www/html/{{ item.name }} state=directory  
with\_items: “{{ services }}”  
when: type == “bar” and item.foo == “bar”

I am aware this is not elegante. What I would like to do is to have a task which will only execute when the type passed from the invocation of the role matches the value of the variable foo. I tried a couple of with\_x alternatives, but as I don’t know the order with which when and with\_items executes, I’m stuck.

Can anyone chip in with a solution to this basic problem?

Thanks,  
Miguel

---

<div class="post-metadata">

**Author:** ![Johannes\_Kastl](https://avatars.discourse-cdn.com/v4/letter/j/bbe5ce/32.png) [@Johannes\_Kastl](https://forum.ansible.com/u/Johannes_Kastl)\
**Post date:** [January 20, 2017, 1:53pm UTC](https://forum.ansible.com/t/nested-conditional-loop/23432/2 "2017-01-20T13:53:15Z")

</div>

Hi,

did you already solve your problem?

> And on the tasks main.yml
> 
> - name: do stuff  
> &nbsp;&nbsp;file: path=/var/www/html/{{ item.name }} state=directory  
> &nbsp;&nbsp;with\_items: "{{ services }}"  
> &nbsp;&nbsp;when: type == "bar" and item.foo == "bar"

Normally this should be "split" up into as many separate tasks as you  
have services in {{ services }}. Each one is run evaluating the  
when-conditition. So one of them should work...

[https://docs.ansible.com/ansible/playbooks\_loops.html](https://docs.ansible.com/ansible/playbooks_loops.html)

> Also be aware that when combining when with with\_items (or any other loop statement), the when statement is processed separately for each item. See The When Statement for an example.

[https://docs.ansible.com/ansible/playbooks\_conditionals.html#the-when-statement](https://docs.ansible.com/ansible/playbooks_conditionals.html#the-when-statement)

Try to debug this using the debug task, drop the type in when and see,  
what works:

&nbsp;&nbsp;- debug: msg="Works with {{ item.name }}"  
&nbsp;&nbsp;&nbsp;&nbsp;when: 'item.foo == "bar"'

Johannes
