CertGrid CertGrid
Hands-on Lab·Ansible

Ansible Loops and loop_control

One task with a loop replaces five near-identical tasks, and the loop is where playbooks stop being scripts. This covers a plain list, a list of dictionaries, looping over what a previous loop registered, the label that stops the output becoming unreadable, and until/retries for something that is not ready yet.

Plays and Playbooks Guide 13 of 45 Intermediate

loop: is the current keyword. with_items and the other with_* forms still work and are not slated for removal, but they are no longer recommended and every current example uses loop. Where with_items flattened nested lists automatically, loop does not - use the flatten filter if you need that.

One managed node. A loop runs per host, so a second would duplicate every result.
Server NameIP AddressOSRolesCPURAMHDD
ANS-CTL01192.168.0.36Ubuntu 26.04 LTSAnsible Control Node2 Core3 GB50 GB
ANS-A01192.168.0.37Ubuntu 26.04 LTSManaged Node (group: web)2 Core3 GB50 GB

This guide includes

Use this when five near-identical tasks want to be one. This matters because the loop is where the variable comes from - and a registered loop stores every iteration separately, which changes how you read the result.

Before you start

  1. The configuration this guide assumes

  2. A loop over a list

  3. A loop over dictionaries

  4. Looping over what you registered

  5. Retrying until something is true

Official sources