DevOps
Infrastructure as Code
Ansible Logic: Conditionals & Loops

Ansible Logic: Conditionals & Loops

Make your playbooks intelligent and concise. Conditionals allow you to execute tasks based on specific criteria, while Loops let you repeat a single task across multiple items without duplicating code.


🚦 Decision Making with Conditionals (when)

The when statement allows you to run a task only if a certain condition is met. This is often used to handle environmental differences, like different Operating Systems.

1. Basic Conditional Syntax

Tasks only execute if the expression in the when clause evaluates to true.

- name: Install Apache on Debian-based systems
  apt:
    name: apache2
    state: present
  when: ansible_os_family == "Debian"

2. Common Logical Operators

OperatorDescriptionExample
==Equal Towhen: var == "value"
!=Not Equal Towhen: var != "value"
> / <Comparisonwhen: memory_gb > 2
is definedCheck existencewhen: my_var is defined
and / orLogical Joinwhen: os == "Linux" and ram > 1024

🔄 Efficiency with Loops (loop)

Loops allow you to repeat a task multiple times using different values. This follows the DRY (Don't Repeat Yourself) principle.

1. Simple List Iteration

The loop keyword replaces the older with_items syntax. The current item is accessed using {{ item }}.

- name: Install multiple packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - zip
    - curl
    - git
    - htop

2. Iterating over Dictionaries

Loops can also handle complex data structures like a list of dictionaries.

- name: Create multiple users with specific groups
  user:
    name: "{{ item.name }}"
    group: "{{ item.group }}"
    state: present
  loop:
    - { name: 'alice', group: 'admin' }
    - { name: 'bob', group: 'developers' }
    - { name: 'charlie', group: 'qa' }

đź’ˇ Practical Masterclass: Logic in Action

Combining conditionals and loops creates powerful, adaptive infrastructure.

- name: Smart Package Deployment
  hosts: all
  tasks:
    - name: Multi-package installation (Debian)
      apt:
        name: "{{ item }}"
        state: present
      loop:
        - nginx
        - git
      when: ansible_os_family == "Debian"
 
    - name: Multi-package installation (RedHat)
      yum:
        name: "{{ item }}"
        state: present
      loop:
        - nginx
        - git
      when: ansible_os_family == "RedHat"

[!TIP] Use Ansible Facts for Logic! Most conditionals rely on "Facts"—system data that Ansible automatically collects at the start of a play. You can see all available facts by running: ansible localhost -m setup