ericsysmin's DevOps Blog

How to loop blocks of code in Ansible

How to loop blocks of code in Ansible

In this blog post I will cover how we can loop groups/blocks of tasks within Ansible. Currently using - block: will not work. However you can use - include_tasks: my_grouped_tasks.yml to loop a group of tasks. Within that tasks file you can use {{ item }} on each of your tasks and It will copy from the item during the loop. At Avi Networks we’ve used this for much of our internal task groupings which have items that depend on creation of each other and cannot independently run loops without causing issues.

In the following I have some visual representations to show what the goal origianlly was, and how you can accomplish it.

PROBLEM:

SOLUTION:

This will effectively do a loop over your multiple tasks. I know it’s a bit annoying, but this is currently the only working solution to looping over blocks of tasks.