How to loop over a list of hosts in a group in a template Ansible
Ansible is an open-source automation language that simplifies IT infrastructure deployment, configuration management, and application deployment.
To execute a task multiple times, Ansible offers the loop, with_<lookup> and until keywords. The loop keyword was added in Ansible 2.5. It's not a complete replacement for with_<lookup>, but it's suggested for most use cases.
Example
Repeated tasks can be represented as conventional loops over a simple list of strings. The list can be defined directly in the task using loop in the tasks/main.yml file, as follows:
---- name: loop over hostsansible.builtin.user:name: "{{ hosts }}"state: presentgroups: "my_group"loop:- host1- host2
Explanation
The line-by-line explanation of the code is provided below:
Line 2:
nameis the Ansible playbook task name, which isloop over hosts.Line 3: The Ansible built-in module named
useris used to create or modify user accounts on the target hosts.Line 4: This specifies the user's name to be created or modified. The value of the variable
hostswill be used here.Line 5: This specifies that the user account should be on the target hosts. If the user doesn't exist, it'll be created. If it already exists, it'll be modified as specified in the other parameters.
Line 6: This specifies the name of the primary group for the user account.
Lines 7–9:
loopwill iterate over the list of hosts specified (host1andhost2) and execute the tasks for each host in turn. In this case, theusermodule will be executed twice, once for each host in the list.
Sum-up
This example shows how we can perform the same task on multiple hosts while allowing dynamic parametrization based on the loop variable. By using loop, we can save time and reduce the chances of error when performing the same tasks on multiple hosts.
Free Resources