New feature: looping over items in playbooks


Hi everyone,

I've taught playbooks to do basic (and reasonably syntax-free!) loops.  Folks have been asking for this to eliminate copy/paste, in particular when creating lots of users (for example) that all share common attributes.

The question may come up… what if all hosts don't get the same packages? Easy answer.  You can use multiple plays and "include:" directives to facilitate sharing.  The "hosts: all" example below is just convient for demos.  Either you can have a playbook containing multiple plays, in which case, it can address different groups all in one file, or, if you want, you can keep multiple top level playbooks.  That's up to you.  

Here is examples/playbooks/loop_with_items.yml from the latest git checkout of Ansible:

It's really just a shorthand, so each "action:" line expands out to multiple real tasks, which is good, because we keep statistics on the number of tasks run, and keep all the output for each host neatly organized.  

You can of course use other variables besides $item, still, $item is just the magic variable used here for looping over the "with_items" list.

---
# this is an example of how to run repeated task elements over lists
# of items, for example, installing multiple packages or configuring
# multiple users

- hosts: all
  user: root

  tasks:

  - name: install $item
    action: yum pkg=$item state=installed
    with_items:
       - cobbler
       - httpd

  - name: configure user $item
    action: user name=$item state=present groups=wheel
    with_items:
       - testuser1
       - testuser2

  - name: remove user $item
    action: user name=$item state=absent
    with_items:
        - testuser1
        - testuser2

–Michael