# when and with on same variable

**URL:** <https://forum.ansible.com/t/when-and-with-on-same-variable/18773>\
**Category:** Ansible Project\
**Created:** [July 15, 2015, 1:52pm UTC](https://forum.ansible.com/t/when-and-with-on-same-variable/18773 "2015-07-15T13:52:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alexander\_Popov1](https://avatars.discourse-cdn.com/v4/letter/a/a183cd/32.png) [@Alexander\_Popov1](https://forum.ansible.com/u/Alexander_Popov1)\
**Post date:** [July 15, 2015, 1:52pm UTC](https://forum.ansible.com/t/when-and-with-on-same-variable/18773/1 "2015-07-15T13:52:22Z")

</div>

- debug: msg=“test for items” # skip because condition is not fullfiled  
when: groups.unexisting is defined

- debug: msg=“test for items”  
when: groups.unexisting is defined

with\_items: unexisting #failed here with with\_items expects a list or a set

---

<div class="post-metadata">

**Author:** ![Martin2](https://avatars.discourse-cdn.com/v4/letter/m/9de053/32.png) [@Martin2](https://forum.ansible.com/u/Martin2)\
**Post date:** [July 15, 2015, 2:04pm UTC](https://forum.ansible.com/t/when-and-with-on-same-variable/18773/2 "2015-07-15T14:04:45Z")

</div>

- debug: msg=“test for items”  
when: groups.unexisting is defined

with\_items: groups.unexisting #might work if you reference the same variable?

---

<div class="post-metadata">

**Author:** ![Brian\_Coca](https://avatars.discourse-cdn.com/v4/letter/b/6de8d8/32.png) [@Brian\_Coca](https://forum.ansible.com/u/Brian_Coca)\
**Post date:** [July 15, 2015, 2:10pm UTC](https://forum.ansible.com/t/when-and-with-on-same-variable/18773/3 "2015-07-15T14:10:54Z")

</div>

when gets evaluated INSIDE the with loop, so it cannot condition the  
executing of with, this is done so you can do when: item == 'blah' for  
example to condition each iteration in the loop.

to deal with undeinfed with\_ vars, do the following:

with\_ : "{{ myvar|default()}}"

^ the empty will skip the task as there is nothing to loop over.

some times you need more complex conditions, ternary filter can help:

with\_ : "{{ unexisting is defined|ternary( groups['unexisting'], ) }}"
