Loops
Often you need to repeat a task multiple times with different values – for example, installing several packages or creating multiple users. Ansible loops make this easy and keep your playbooks DRY (Don’t Repeat Yourself).
Basic Loop with
loopUse the
loop keyword with a list of items. The current item is available as {{ item }}.- name: Install multiple packages
apt:
name: "{{ item }}"
state: present
loop:
- git
- curl
- vimLooping Over a List of Hashes
If you need multiple attributes per item, use a list of dictionaries. Access values with
{{ item.key }}.- name: Create users with specific UIDs
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
state: present
loop:
- { name: 'alice', uid: 1001 }
- { name: 'bob', uid: 1002 }Looping Over the Output of a Task
Use
loop: "{{ some_command.stdout_lines }}" to iterate over lines from a command result.- name: Get list of files
command: ls /tmp
register: files
- name: Print each file
debug:
msg: "{{ item }}"
loop: "{{ files.stdout_lines }}"Using
loop_control to Customize Loop Variable NameYou can rename
item to something more descriptive:- name: Install packages
apt:
name: "{{ pkg }}"
loop:
- nginx
- postgresql
loop_control:
loop_var: pkgDo’s and Don’ts
Loops are powerful, but avoid nesting loops when possible. For complex scenarios, consider using roles or including tasks from files.
Two Minute Drill
- Use
loopwith a list to repeat a task. - Access each item with
{{ item }}. - Loop over dictionaries to set multiple parameters.
- Customize loop variable with
loop_control.
Need more clarification?
Drop us an email at career@quipoinfotech.com
