Ansible - Loop over a block of tasks
by
Jeremy Canfield |
Updated: July 06 2023
| Ansible articles
Let's say you want to loop over a sequence of tasks. Unfortunately this isn't something Ansible has a great solution for, as loops are done task by task, not over a group of tasks. To loop over a group of tasks, I'll typically create a role YAML file that contains the multiple tasks I want to loop over, perhaps something like this.
- name: create TAR archives
archive:
path: "{{ item.path }}"
dest: /tmp/{{ item.path | regex_replace('/', '.') }}.{{ ansible_date_time.iso8601_basic_short }}.tar.gz
- name: rsync (upload) TAR archive to file server
synchronize:
mode: push
src: /tmp/{{ item.path | regex_replace('/', '.') }}.{{ ansible_date_time.iso8601_basic_short }}.tar.gz
dest: rsync://fileserver.example.com/usr/local/backups
- name: delete the TAR archive
file:
path: /tmp/{{ item.path | regex_replace('/', '.') }}.{{ ansible_date_time.iso8601_basic_short }}.tar.gz
state: absent
And then in my parent playbook, I would use include_role and with_items to loop through the tasks, one at a time. Or, include_tasks could be used.
---
- hosts: all
tasks:
- name: find target directories
find:
paths: /opt/example
file_types: directory
register: out
- name: include_role create_tar_archives.yml
include_role:
name: create_tar_archives
with_items: "{{ out.files }}"
...
Did you find this article helpful?
If so, consider buying me a coffee over at