To make Ansible run a command multiple times, the most reliable method is to use the loop keyword with the retries parameter. This instructs the task to execute the specified command repeatedly up to a set number of attempts, pausing briefly between each try. Alternatively, you can use the with_sequence or with_items built-in loops to iterate over a list of values, effectively repeating the command for each item in that list. The choice between repeating a single command against the same target or repeating the command against a list of targets depends entirely on whether the task needs to be retried on failure or needs to perform an action on multiple items.
Understanding the Need for Repetition
Automation scripts frequently fail not because the logic is flawed, but due to transient issues on the target host or network instability. A service might take a moment to start listening on a port, or a database might require a few seconds to become fully available. In these scenarios, simply running a command once is insufficient. The script must be resilient to these delays or temporary errors. Ansible provides specific constructs to handle this variability, ensuring that a single point of failure does not derail the entire deployment or configuration process.
Using the retries Keyword
The retries parameter is designed specifically for making a single task resilient. It tells Ansible to keep trying a specific command until it succeeds or the retry limit is reached. This is distinct from looping over a list of items; here, the loop is implicit and internal to the task.
- Start by defining a task that performs the command you want to repeat.
- Apply the
retrieskeyword directly to that task. - Specify the number of attempts you want Ansible to make.
- Optionally, use the
delaykeyword to set the number of seconds to wait between attempts.
For example, if you want to ping a host until it responds, you might configure the task to retry three times with a two-second delay between pings. If the host is down, Ansible will wait the total duration of the retries and delays before reporting a failure. This prevents the playbook from failing immediately if the target is momentarily unreachable.
Looping with loop and with_items
If your goal is to perform the same action on multiple different targets or multiple different parameters, you use a loop. The loop keyword is the modern, recommended way to iterate over a collection of values. The with_items keyword is a legacy method that still works but is generally superseded by loop for better readability and control.
- With
loop: You define a list of values, and Ansible creates a separate context for each value. Inside the task, you access the current value using theitemvariable. - With
with_items: Similar toloop, this keyword takes a list and iterates over it, making the current item available as theitemvariable.
Suppose you need to create three users. You can place the user creation task inside a loop. Ansible will execute the task three times, once for each user in the list. This effectively repeats the command three times, once per user.
Advanced Looping: with_sequence
When you need to repeat a command based on a numerical range—such as creating a set of files named file1.txt, file2.txt, and file3.txt—the with_sequence loop is highly effective. It allows you to define a start number, an end number, and an optional step value.
- Define a start number (e.g., 1).
- Define an end number (e.g., 3).
- Optionally, define a step (e.g., 1).
Ansible will generate an internal list of numbers from the start to the end, and the task will repeat once for each number in that generated list. This is a concise way to achieve repetition based on counting.
Retrying Failed Tasks with resilient or ignore_errors
There is a subtle difference between looping to cover multiple items and looping to recover from a failure. The retries keyword handles the latter by attempting the task again. However, if you are using a loop to process a list of items and one item fails, the entire loop typically stops. To handle failures within a loop gracefully, you can use the ignore_errors parameter or configure the task to continue on failure.
- Add the
ignore_errors: yesparameter to the task. - Ansible will mark the task as failed but continue to the next item in the loop.
- Alternatively, configure the playbook to continue on failure using the
any_errors_fatal: nosetting.
This approach is useful when you want to repeat a command for a list of items and ensure that a single item's failure does not prevent the processing of subsequent items.
Implementing a Custom Retry Logic
For complex scenarios where the standard retries parameter is not sufficient—for instance, if you need to check a specific condition before retrying—you can use a conditional statement within the task. You can write a small script or use a lookup plugin to generate a list of retry attempts dynamically.
- Create a task that checks the current state of the system.
- If the state is not as desired, use the
retrieskeyword to schedule another attempt. - If the state is correct, proceed with the next task.
This method provides maximum flexibility but requires more complex playbook structure. It is generally reserved for situations where the standard repetition mechanisms do not meet the specific requirements of the environment.
Frequently Asked Questions
Does Ansible run commands in parallel when looping?
No. By default, Ansible executes tasks sequentially within a play. This means it will complete the first item in the loop before moving on to the second item. To run tasks in parallel, you must configure the serial or parallelism settings in the playbook, though this is not part of the standard looping mechanism.
How do I pause between loops?
You can use the delay keyword within the retries parameter to pause between retries of the same task. However, between different items in a list loop, Ansible waits for the task to complete before starting the next one. To introduce artificial delays between items, you can use the ansible.builtin.pause module or add a sleep command in a shell task.
What happens if all retries fail?
If a task reaches the limit of retries defined in the retries parameter and has not succeeded, Ansible marks the task as failed. Depending on your playbook settings, this failure might stop the entire playbook execution or, if configured appropriately, allow the playbook to continue to the next task.
Can I combine loop with retries?
Yes. You can use the loop keyword to iterate over a list of items, and also include the retries parameter on the task. This means Ansible will repeat the task for each item in the list, and for each instance of the task, it will retry the command multiple times if it fails. This combination offers both high throughput and high resilience.
Is the with_items keyword deprecated?
While with_items is not strictly deprecated, it is considered legacy. The loop keyword is the recommended approach for iterating over lists in modern Ansible playbooks. It offers better performance, cleaner syntax, and more flexibility in how variables are accessed within the task.