Using Ansible loops
Often, you may need to run a task inside an Ansible playbook to loop over some data. Ansible loops allow you to iterate over a variable (a dictionary or a list) multiple times to achieve this behavior. In this recipe, we will outline how to use Ansible loops and how to customize how they work.
The first step will be to create a group_vars file called arista_ceos.yml (matching the group name used in the inventory). This is where we will define the specific NTP server variable data for this group:
root@cookbook-lab:~/cookbook-lab/chapters/ch02# vi group_vars/arista_ceos.yml
---
ntp:
- 192.168.3.10
- 192.168.5.10
Next, we construct an Ansible playbook (limited to Arista devices via the hosts configuration) that will execute the only task as many times as items are contained in the ntp variable:
root@cookbook-lab:~/cookbook-lab/chapters/ch02# vi pb_loops.yml
---
- name: LOOP THROUGH A ...