Bootstrap FreeKB - Ansible - Loop over a block of tasks
Ansible - Loop over a block of tasks

Updated:   |  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
    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
    mode: push
    src: /tmp/{{ item.path | regex_replace('/', '.') }}.{{ ansible_date_time.iso8601_basic_short }}.tar.gz
    dest: rsync://

- name: delete the TAR archive
    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
  - name: find target directories
      paths: /opt/example
      file_types: directory
    register: out

  - name: include_role create_tar_archives.yml
      name: create_tar_archives
    with_items: "{{ out.files }}"


Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee


Add a Comment

Please enter 573bb8 in the box below so that we can be sure you are a human.