Loops

Learn how to use loops in Ansible to perform repeated tasks.

Overview

Loops are a fundamental construct in Ansible, allowing us to repeat a set of tasks multiple times, iterating over a list or another iterable. Loops enable us to automate repetitive actions and manage multiple resources efficiently. In Ansible, loops can be used single-handedly in tasks or used within Jinja2 template files.

Press + to interact

Working with loops

There are several keywords and constructs to work with loops that make them flexible and adaptable for various use cases. Common keywords for working with loops include:

  • loop
  • with_items
  • with_nested
  • with_<lookup term>
  • until

The loop keyword

The loop keyword is used to iterate over a list or other iterable within a task. It’s typically used with tasks that involve iterating through a list of items and performing actions on each item. Here is an example:

Press + to interact
---
- name: Using loop to create multiple directories
hosts: web_servers
tasks:
- name: Create necessary directories
file:
path: "{{ item }}"
state: directory
owner: root
group: root
mode: 0775
loop:
- /home/config_files/nginx
- /home/config_files/apache
...