Using 'include' in a loop

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!

"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.