# Using 'include' in a loop

**URL:** <https://forum.ansible.com/t/using-include-in-a-loop/12709>\
**Category:** Ansible Project\
**Tags:** ansible-project\
**Created:** [April 22, 2013, 1:12pm UTC](https://forum.ansible.com/t/using-include-in-a-loop/12709 "2013-04-22T13:12:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Michael\_DeHaan2](https://avatars.discourse-cdn.com/v4/letter/m/da6949/32.png) [@Michael\_DeHaan2](https://forum.ansible.com/u/Michael_DeHaan2)\
**Post date:** [April 22, 2013, 1:12pm UTC](https://forum.ansible.com/t/using-include-in-a-loop/12709/1 "2013-04-22T13:12:20Z")

</div>

Sure…

include + with\_items can be confusing, so we have been trying to remove it from the docs to explain better ways to do it. Can you let me know where you found documentation on this subject in the docs so I can remove it and explain the better approach?

The way you fix this is to move your “with\_items” statement into your tasks/role file, like so:

- shell: do\_x.sh {{ item }}  
with\_items: foo

So basically, the loop goes inside the task.

# note that I’m using 1.2 syntax for variables and with\_items, 1.1 looks like:

- shell: do\_x.sh ${item}  
with\_items: ${foo}

Should you ever need to do a nested loop, you can (again, using 1.2 convention):

- shell: do\_x.sh {{ item[0] }} {{ item[1] }}  
with\_nested:
- “{{ foo }}”
- “{{ bar }}”

And that allows you to loop over the permutations of two lists.

(I should tweak things in with\_nested so the template expansion above is not required to explode the variables)

In short, you can do everything you need to do using 'with\_items" and “with\_nested” and so on, and “include + with\_items” is something of an anti-pattern.

My apologies on the confusion/complexity of having to work through that, again, let me know what docs continue to reference it and I’ll see about improving them.

Thanks!

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan](https://avatars.discourse-cdn.com/v4/letter/m/c4cdca/32.png) [@Michael\_DeHaan](https://forum.ansible.com/u/Michael_DeHaan)\
**Post date:** [April 22, 2013, 1:28pm UTC](https://forum.ansible.com/t/using-include-in-a-loop/12709/2 "2013-04-22T13:28:49Z")

</div>

"If we use with\_items on every task step as suggested in the bug report the play becomes less composable "

BTW, I disagree with this, the content is just as reusable.

Because the variable name is mentioned in one file or the other should not matter. In this case, you can even keep the definition in a 1.2 role.

It’s also nicer because the variable could come host\_vars/group\_vars, vars\_files, it would not matter, as long as it were defined.
