One of the biggest shortcomings of the Ansible syntax is the ability to loop over a block with tasks in it. It is possible to loop over multiple arrays, nested objects etc. But looping over a set of tasks is not possible within the same playbook.
To be able to loop over a group of task, you can use the include playbook option. This will include the playbook for each item in your list / object. Like the following example:
main.yml playbook:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
--- - hosts: localhost gather_facts: true vars: fdirs: - 'test' - 'test1' - 'test2' tasks: - name: Create folder on linux foreach dir in fdir list include: taskblock.yml dirname={{ prefix }} vars: prefix: "pr_{{ item }}" with_items: "{{ fdirs }}" |
Include playbook ‘taskblock.yml’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
--- - name: Ansible create {{ dirname}} directory and set permission file: path: "/tmp/{{ dirname }}" state: directory mode: "u=rw,g=wx,o=rwx" recurse: yes - name: Get raw foldersize command: "du -sk /tmp/{{ dirname }}" register: folder_size_raw - set_fact: folder_size: "{{ folder_size_raw.stdout.split()[0] }}" - debug: msg: "Foldersize is: {{ folder_size }}" |
The playbook result, including folder size.