In some cases, we need to run a task inside an Ansible playbook to loop over some data. Ansible's loops allow us to loop over a variable (a dictionary or a list) multiple times in order to achieve this behavior. In this recipe, we will outline how to use Ansible's loops.
Using Ansible's loops
Getting ready
In order to follow along with this recipe, an Ansible inventory file must be present and configured, as outlined in the previous recipes.
How to do it...
- Create a new playbook called ansible_loops.yml inside the ch1_ansible folder.
- Inside the group_vars/cisco.yml file, incorporate the following content:
snmp_servers:
- 10.1.1.1
- 10.2.1.1
- Inside the group_vars/juniper.yml file, incorporate the following content:
users:
admin: admin123
oper: oper123
- Inside the ansible_loops.yml file, incorporate the following content:
---
- name: Ansible Loop over a List
hosts: cisco
gather_facts: no
tasks:
- name: Loop over SNMP Servers
debug:
msg: "Router {{ hostname }} with snmp server {{ item }}"
loop: "{{ snmp_servers}}"
- name: Ansible Loop over a Dictionary
hosts: juniper
gather_facts: no
tasks:
- name: Loop over Username and Passowrds
debug:
msg: "Router {{ hostname }} with user {{ item.key }} password {{ item.value }}"
with_dict: "{{ users}}"
- Run the playbook as shown here:
$ ansible-playbook ansible_loops.yml -i hosts
How it works..
Ansible supports looping over two main iterable data structures: lists and dictionaries. We use the loops keyword when we need to iterate over lists (snmp_servers is a list data structure) and we use with_dicts when we loop over a dictionary (users is a dictionary data structure where the username is the key and the passwords are the values). In both cases, we use the item keyword to specify the value in the current iteration. In the case of with_dicts, we get the key using item.key and we get the value using item.value.
The output of the preceding playbook run is shown here:
See also...
For more information regarding the different Ansible looping constructs, please consult the following URL:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html