Loop

Learn about loops to repeat tasks in our Ansible playbook.

Loop statements automate repetitive tasks in our Ansible playbook. Computers are better at repeating identical or similar tasks without errors than humans. The repeated execution of a set of statements is called iteration.

Iteration statements in Ansible

Ansible has several statements for iteration. We will focus on the following two statements:

  • The loop statement
  • The with_items statement

The loop statement

A simple loop iterates a task over a list of items. The loop statement is added to the task and takes the list of items over which the task should be iterated as a value.

Press + to interact
---
- name: Check services
hosts: all
tasks:
- name: httpd and sshd are running
ansible.builtin.service:
name: "{{ item }}"
state: started
loop:
- apache2
- sshd

In our playbook, we used the ...