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 hosts
ansible.builtin.user:
name: "{{ hosts }}"
state: present
groups: "my_group"
loop:
- host1
- host2

Explanation

The line-by-line explanation of the code is provided below:

  • Line 2: name is the Ansible playbook task name, which is loop over hosts.

  • Line 3: The Ansible built-in module named user is 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 hosts will 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: loop will iterate over the list of hosts specified (host1 and host2) and execute the tasks for each host in turn. In this case, the user module 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

Copyright ©2025 Educative, Inc. All rights reserved