Skip to content

Loopsintro

Ansible supports iterating a task over a set of items using the loop keyword, which enabled you to write a task that iterates over a list.

Simple Loops

A simple loop iterates a task over a list of items.

Example:

- name: Ensure services are running
  service:
    name: "{{ item }}"
    state: started
  loop:
    - httpd
    - firewalld

Loops over a List of Hashes or Dictionaries

Items in the list can be a hash or a dictionary.

Example:

- name: Users exist and in groups
  user:
    name: "{{ item.name }}"
    state: present
    groups: "{{ item.groups }}"
  loop:
    - name: john
      groups: admins
    - name: joe
      groups: developers

Earlier-Style Loop Keywords

Before Ansible 2.5, most playbooks used a different syntax for loops, typically using with_items.

Using Register Variables with Loops

The register keyword can also capture the output of a task that loops.

Example:

- name: Looping Echo Task
    shell: "echo This is my item: {{ item }}"
    loop:
    - one
    - two
    register: echo_results

- name: Show echo_results variable
    debug:
    var: echo_results

 - name: Show stdout from the previous task.
      debug:
        msg: "STDOUT from previous task: {{ item.stdout }}"
      loop: "{{ echo_results['results'] }}"

Running Tasks Conditionally

Ansible can use conditionals to execute tasks or plays when certain conditions are met.

The when statement is used to run a task conditionally.

Example:

---
- name: Boolean Demo
  hosts: all
  vars:
    run_my_task: true

  tasks:
    - name: httpd package is installed
      yum:
        name: httpd
      when: run_my_task is defined

Example Conditionals

Common conditionals include:

==
<
>
<=
>=
!=
is defined
is not defined
in

Testing Multiple Conditions

One when statement can be used to evaluate multiple conditionals.

Example:

when: ansible_distribution == "RedHat" or ansible_distribution == "Fedora"

These can be in a list when needed the and:

when: 
  - ansible_distribution == "RedHat" 
  - ansible_kernel == "3.10.0-327.el7.x86_64"
  • More complex conditional statements can be expressed by grouping conditions with parentheses.

Example:

when: >
    ( ansible_distribution == "RedHat" and
      ansible_distribution_major_version == "7" )
    or
    ( ansible_distribution == "Fedora" and
    ansible_distribution_major_version == "28" )