# using when inside and outside a loop

**URL:** <https://forum.ansible.com/t/using-when-inside-and-outside-a-loop/32021>\
**Category:** Ansible Project\
**Created:** [January 21, 2020, 8:17pm UTC](https://forum.ansible.com/t/using-when-inside-and-outside-a-loop/32021 "2020-01-21T20:17:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Spiro\_Mitsialis](https://avatars.discourse-cdn.com/v4/letter/s/c57346/32.png) [@Spiro\_Mitsialis](https://forum.ansible.com/u/Spiro_Mitsialis)\
**Post date:** [January 21, 2020, 8:17pm UTC](https://forum.ansible.com/t/using-when-inside-and-outside-a-loop/32021/1 "2020-01-21T20:17:17Z")

</div>

I want to do something like this below:

`

- name: Create Simple list from Connection Dict  
set\_fact:  
connections: “{{ connections | default() + [ {  
‘switchid’: item.id,  
‘connectionid’: item.connections[0].id  
} ] }}”  
when: item.connections #only want to create facts if connections exist  
loop: “{{ connections\_result.json.0.switchPorts | flatten }}”  
when: connections\_result is defined #depending on the host,connection\_result.json may not be defined so need to check  
`

When I run the playbook, I get the following warning at the top

`[WARNING]: While constructing a mapping from /home/xxx/xxxxx.yml, line 245, column 5, found a duplicate dict key (when). Using last defined value only.`

Is there a way to get both when to work?

---

<div class="post-metadata">

**Author:** ![vbotka](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/vbotka/32/359_2.png) [@vbotka](https://forum.ansible.com/u/vbotka)\
**Post date:** [January 21, 2020, 9:09pm UTC](https://forum.ansible.com/t/using-when-inside-and-outside-a-loop/32021/2 "2020-01-21T21:09:33Z")

</div>

No. It's not possible. Instead, default to an empty list if the variable does  
not exist. For example

&nbsp;&nbsp;&nbsp;- name: Create Simple list from Connection Dict  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;set\_fact:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;connections: "{{ connections | default() + [ {  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'switchid': item.id,  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'connectionid': item.connections[0].id  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} ] }}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;when: item.connections  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;loop: "{{ connections\_result.json.0.switchPorts|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;default()|  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;flatten }}"

HTH,

&nbsp;&nbsp;-vlado
