Ansible Loops

Saurabh Sharma

Ansible offers powerful looping mechanisms that can significantly enhance your playbooks’ efficiency and readability. In this blog post, we’ll dive deep into Ansible loops, exploring various elements and providing practical examples to help you master this essential feature.

Table of Contents

  1. Introduction to Loops
  2. Basic Loop Usage
  3. loop_control and loop_var
  4. Looping Over Dictionaries
  5. Nested Loops
  6. Using Loops with Include Statements
  7. Advanced Loop Techniques
  8. Best Practices and Tips

Introduction to Loops

Loops in Ansible allow you to repeat a task multiple times with different input values. This can dramatically reduce the amount of code you need to write and maintain, making your playbooks more efficient and easier to read.

Basic Loop Usage

The most common way to use loops in Ansible is with the loop keyword. Here’s a simple example:

In this example, the task will run three times, creating users named john, jane, and bob. The loop variable item takes on each value in the list.

loop_control and loop_var

The loop_control directive allows you to fine-tune how your loops behave. One of its most useful features is loop_var, which lets you rename the loop variable:

Here, we’ve used loop_var: package to rename the loop variable from item to package, making the playbook more readable.

Looping Over Dictionaries

Loops become even more powerful when working with dictionaries:

This example demonstrates how to loop over a list of dictionaries, creating users with specific properties.

Nested Loops

Ansible supports nested loops, allowing you to iterate over multiple lists:

This loops through two loops

Using Loops with Include Statements

Loops can be used with include_tasks to dynamically include task files:

This includes and executes the user_setup.yml task file for each user in the loop.

Advanced Loop Techniques

Ansible offers several advanced looping techniques:

  1. with_items: An older syntax, still supported but loop is preferred.
  2. with_dict: For iterating over dictionary key-value pairs.
  3. with_fileglob: For looping over files matching a pattern.
  4. with_sequence: For generating a sequence of items to iterate over.

Example of with_sequence:

This creates directories named dir01 through dir05.

Best Practices and Tips

  1. Use meaningful names for your loop variables with loop_var.
  2. Keep your loops simple and readable. If a loop becomes too complex, consider breaking it into separate tasks.
  3. Use loop instead of with_items for better performance and consistency.
  4. Be mindful of the performance impact when looping over large datasets.
  5. Use loop_control: label to customize the output of your loops for better readability in Ansible output.

Happy looping!