Iterative tasks with loops
Loops deserve a special mention in this chapter. So far, we have focused on controlling the flow of a playbook in a top-to-bottom fashion—we have changed the various conditions that might be evaluated as the playbook runs, and we have also focused on creating concise, efficient code. What happens, however, if you have a single task, but need to run it against a list of data; for example, creating several user accounts, directories, or indeed something more complex?
Looping changed in Ansible 2.5—prior to this, loops were generally created with keywords such as with_items
and you may still see this in legacy code. Although some backward compatibility remains, it is advisable to move to the newer loop
keyword instead.
Let's take a simple example—we need to create two directories. Create loop.yaml
as follows:
--- - name: looping demo hosts: localhost gather_facts: false...