 [](https://www.linkedin.com/in/nirgeier/) [](mailto:nirgeier@gmail.com) [](mailto:nirg@codewizard.co.il)
this project Lab 010 - Loops and Conditions in Ansible¶
- In this section, we will cover Loops and Conditions in Ansible.
- Loops help in performing repetitive tasks efficiently.
- Conditions allow tasks to be executed based on specific criteria.

01. Ansible Loops¶
01.01. 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
01.02. 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" }
01.03. 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. Conditions in Ansible¶
02.01. Using when¶
- Conditions are defined using the
whenclause.
---
- hosts: localhost
tasks:
- name: Install Apache only on Ubuntu
apt:
name: apache2
state: present
when: ansible_os_family == "Debian"
02.02. Complex Conditions¶
- Multiple conditions can be combined with
and,or, andnot.
---
- 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
02.03. Combining Loops and Conditions¶
- Loops and conditions 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
- 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)
:arrow_backward: /Labs/009-roles Back to labs list /Labs/011-jinja-templating :arrow_forward: