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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# playbook.yml --- - hosts: localhost connection: local vars: ip_addresses: - 10.0.0.10 - 10.0.0.11 tasks: - block: - name: Copy using inline content to first file copy: content: | ip_address={{ item }} dest: /etc/some_config_file.conf - name: Copy using inline content to second file copy: content: | ip_address={{ item }} dest: /etc/some_other_config_file.conf loop: "{{ ip_addresses }}" |
SOLUTION:
1 2 3 4 5 6 7 8 9 10 11 12 |
# playbook.yml --- - hosts: localhost connection: local vars: ip_addresses: - 10.0.0.10 - 10.0.0.11 tasks: - name: deploy files with network address in them include_tasks: network_files.yml loop: "{{ ip_addresses }}" |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# network_files.yml --- - name: Copy using inline content to first file copy: content: | ip_address={{ item }} dest: /etc/some_config_file.conf - name: Copy using inline content to second file copy: content: | ip_address={{ item }} dest: /etc/some_other_config_file.conf |
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.