Junior — Middle
Can you explain how loops work in an Ansible playbook and how to use them?
sobes.tech AI
Answer from AI
In an Ansible playbook, loops are used to repeat tasks with different parameters, which helps avoid code duplication.
The main method is the loop directive, which takes a list of values and executes the task for each element.
Example of using a loop:
- name: Install multiple packages
apt:
name: "{{ item }}"
state: present
loop:
- git
- curl
- vim
There is also the deprecated with_items syntax, but it is recommended to use loop.
Loops can be combined with conditions, filters, and other Ansible features for flexible automation.