Loops and Conditionals in Ansible¶
- In this section, we will cover Loops and Conditionals in Ansible.
- Loops assist in efficiently performing repetitive tasks.
- Conditions allow tasks to be executed based on specific criteria.
- See documentation about Loops and Conditionals in Ansible.

What will we learn?¶
- How to use
loopto iterate over lists and dictionaries - How to use nested loops
- How to use the
whenclause for conditional task execution - How to combine loops and conditionals
Prerequisites¶
- Complete the previous lab in order to have
Ansibleset up.
01. Ansible Loops¶
Basic loop¶
- Ansible provides a
loopkeyword to execute tasks multiple times with different inputs:
---
- hosts: localhost
tasks:
- name: Install multiple packages
apt:
name: "{{ item }}"
state: present
loop:
- git
- curl
- vim
Loop with dictionaries¶
- Loops can be used with dictionaries to process structured data:
---
- hosts: localhost
tasks:
- name: Add multiple users
user:
name: "{{ item.name }}"
shell: "{{ item.shell }}"
loop:
- { name: "alice", shell: "/bin/bash" }
- { name: "bob", shell: "/bin/zsh" }
Nested loops¶
- Nested loops allow iterating over multiple lists:
---
- hosts: localhost
tasks:
- name: Assign permissions
file:
path: "/home/{{ item.0 }}/{{ item.1 }}"
state: touch
owner: "{{ item.0 }}"
loop:
- ["alice", "bob"]
- ["file1.txt", "file2.txt"]
loop_control:
loop_var: item
02. Ansible Conditionals¶
Using the when clause¶
- Conditionals can be defined using the
whenclause:
---
- hosts: localhost
tasks:
- name: Install Apache only on Ubuntu
apt:
name: apache2
state: present
when: ansible_os_family == "Debian"
Complex conditionals¶
- Multiple conditionals can be combined with
and,or, andnotclauses:
---
- hosts: localhost
tasks:
- name: Restart service only if running
service:
name: nginx
state: restarted
when: ansible_os_family == "RedHat" and ansible_distribution_major_version | int >= 7
03. Combining loops and conditionals¶
- Loops and conditionals can be used together:
---
- hosts: localhost
tasks:
- name: Create users only if home directory does not exist
user:
name: "{{ item }}"
state: present
loop:
- alice
- bob
when: not ansible_facts['getent_passwd'][item] is defined
04. Hands-on¶
- Try writing a playbook that installs different packages based on the OS family.
- Try to use as many parts as you can (external vars, vars, loops, conditions etc) while doing so.
05. Summary¶
loop:(and the olderwith_items:) iterates a task over a list - the current item is accessed as{{ item }}when:conditionals accept Jinja2 expressions; the task is skipped when the condition evaluates to falseansible_facts['os_family']andansible_facts['distribution']are commonly used in conditionals for cross-platform playbooks- Loops and conditionals can be combined:
when:is evaluated per iteration, not once for the whole loop loop_control: label:shortens verbose loop output by displaying only a meaningful variable instead of the full item dict