Ansible: implementing a looping block using include_tasks

Ansible blocks provide a convenient way to logically group tasks.  So it is unfortunate that native Ansible syntax does not allow looping to be combined with a block.  Consider the simple conditional block below controlled by a variable ‘do_block_logic’:

 - name: simple block with conditional
   block:
     - name: simple block task1
       debug: msg="hello"
     - name: simple block task2
       debug: msg="world"
   when: do_block_logic|bool

It would be nice to simply add a ‘loop’ or ‘with_items’ that would loop on this block and provide access to an {{item}} from within these tasks.  But this Ansible syntax does not exist, so we have to construct a syntax as described by Eric Anderson where we use loop and include_tasks.

 - name: calling block with conditional on loop
   include_tasks: conditional_block.yml
   loop: ['world','universe']

Then your block is defined in a file ‘conditional_block.yml’

- name: included block with conditional
  block:
    - name: included block task1
      debug: msg="hello"
    - name: included block task2
      debug: msg="{{item}}"
  when: do_block_logic|bool

Which allows access to {{item}} from within the block tasks.

A full example is provided at playbook-block-loop.yml.

REFERENCES

ericsysmin.com, how to loop blocks of code in Ansible

Ansible include_tasks

Ansible blocks

Ansible loops