# Using when and with\_items

**URL:** <https://forum.ansible.com/t/using-when-and-with-items/14903>\
**Category:** Ansible Project\
**Created:** [March 31, 2014, 10:56pm UTC](https://forum.ansible.com/t/using-when-and-with-items/14903 "2014-03-31T22:56:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![James\_Goodhouse](https://avatars.discourse-cdn.com/v4/letter/j/54ee81/32.png) [@James\_Goodhouse](https://forum.ansible.com/u/James_Goodhouse)\
**Post date:** [March 31, 2014, 10:56pm UTC](https://forum.ansible.com/t/using-when-and-with-items/14903/1 "2014-03-31T22:56:21Z")

</div>

I see in the documentation then combining when with with\_items will process the when statement for each item separately. Does this mean I cannot put a generic when statement on a task that has with\_items?

I’m trying to process a task only when a condition is met. For example, if variable xyz is desfined, then proceed with the task that has a with\_items statement. Unfortunately, this does not work and returns the error “with\_items expects a list or a set”. I’m using the following chunk of code:

- name: copy template to folder  
template:  
src: template.j2  
dest: /remote/file/location/{{ item.name }}  
owner: root  
group: root  
mode: 0600  
with\_items: variable\_array  
when: variable\_array is defined

---

<div class="post-metadata">

**Author:** ![James\_Goodhouse](https://avatars.discourse-cdn.com/v4/letter/j/54ee81/32.png) [@James\_Goodhouse](https://forum.ansible.com/u/James_Goodhouse)\
**Post date:** [March 31, 2014, 11:00pm UTC](https://forum.ansible.com/t/using-when-and-with-items/14903/2 "2014-03-31T23:00:52Z")

</div>

I need to make a correction. It seems to work fine when I have just a basic variable set, but I if I use the following it doesn’t work. Am I thinking about this wrong?

- name: copy template to folder  
template:  
src: template.j2  
dest: /remote/file/location/{{ [item.name](http://item.name/) }}  
owner: root  
group: root  
mode: 0600  
with\_items: variable[‘another\_var’]  
when: variable\_array is defined

---

<div class="post-metadata">

**Author:** ![Marko\_Lisica](https://avatars.discourse-cdn.com/v4/letter/m/a5b964/32.png) [@Marko\_Lisica](https://forum.ansible.com/u/Marko_Lisica)\
**Post date:** [April 1, 2014, 7:33pm UTC](https://forum.ansible.com/t/using-when-and-with-items/14903/3 "2014-04-01T19:33:47Z")

</div>

Hi can you show your vars also?  
Variable\_array particulary.
