Loops in Ansible playbooks can be used to execute tasks multiple times with different values, making your automation scripts more efficient and concise. Here’s how you can implement loops in various scenarios:
1. Basic Loop with loop
You can use the loop keyword to iterate over a list of items. For example, to install multiple packages:
---
- name: Install multiple packages
hosts: localhost
tasks:
- name: Install packages
apt:
name: "{{ item }}"
state: present
loop:
- package1
- package2
- package3
2. Looping Over Dictionaries
You can loop over key-value pairs in a dictionary using the dict2items filter:
---
- name: Create users from a dictionary
hosts: localhost
tasks:
- name: Create users
user:
name: "{{ item.key }}"
state: present
uid: "{{ item.value }}"
loop: "{{ users_dict | dict2items }}"
Here, users_dict might look like this:
users_dict:
user1: 1001
user2: 1002
3. Loop Control with loop_control
You can customize loop behavior using loop_control. For example, to keep track of the index:
---
- name: Install packages with index
hosts: localhost
tasks:
- name: Install packages
apt:
name: "{{ item }}"
state: present
loop:
- package1
- package2
loop_control:
index_var: idx
register: result
- debug:
msg: "Installed {{ item }} at index {{ idx }}"
loop: "{{ result.results }}"
4. Nested Loops
You can nest loops to handle more complex data structures:
---
- name: Create multiple users with multiple groups
hosts: localhost
tasks:
- name: Create users and assign groups
user:
name: "{{ item.user }}"
groups: "{{ item.group }}"
state: present
loop:
- { user: 'user1', group: 'group1' }
- { user: 'user2', group: 'group2' }
5. Using Loops with Conditionals
You can combine loops with conditionals to execute tasks based on specific criteria:
---
- name: Install packages conditionally
hosts: localhost
tasks:
- name: Install packages if not already installed
apt:
name: "{{ item }}"
state: present
loop:
- package1
- package2
when: item not in installed_packages
Further Learning
To practice using loops in Ansible playbooks, consider exploring relevant labs on LabEx that focus on task automation and playbook development.
If you have more questions or need further clarification, feel free to ask! Your feedback is always appreciated.
