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.
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:
---- name: Using loop to create multiple directorieshosts: web_serverstasks:- name: Create necessary directoriesfile:path: "{{ item }}"state: directoryowner: rootgroup: rootmode: 0775loop:- /home/config_files/nginx- /home/config_files/apache