How do I apply an Ansible with_items loop to the included tasks?

Question:

The documentation for import_tasks mentions

Any loops, conditionals and most other keywords will be applied to the included tasks, not to this statement itself.

This is exactly what I want. Unfortunately, when I attempt to make import_tasks work with a loop

I get the message

ERROR! You cannot use loops on ‘import_tasks’ statements. You should use ‘include_tasks’ instead.

I don’t want the include_tasks behaviour, as this applies the loop to the included file, and duplicates the tasks. I specifically want to run the first task for each loop variable (as one task with the standard with_items output), then the second, and so on. How can I get this behaviour?


Specifically, consider the following:

Suppose I have the following files:

playbook.yml

msg.yml

I would like the printed messages to be

Message 1: 1
Message 1: 2
Message 2: 1
Message 2: 2

However, with import_tasks I get an error, and with include_tasks I get

Message 1: 1
Message 2: 1
Message 1: 2
Message 2: 2

Answer:

You can add a with_items loop taking a list to every task in the imported file, and call import_tasks with a variable which you pass to the inner with_items loop. This moves the handling of the loops to the imported file, and requires duplication of the loop on all tasks.


Given your example, this would change the files to:

playbook.yml

msg.yml

Leave a Reply