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:
Testing Multiple Conditions
One when statement can be used to evaluate multiple conditionals.
Example:
These can be in a list when needed the and
:
- More complex conditional statements can be expressed by grouping conditions with parentheses.
Example: