So far, every task in Aurora Store's playbooks runs always and only once on each host. Reality is more varied: some tasks only make sense on certain distributions or environments, and others have to be repeated for every team user, every database or every web server. In this lesson you'll learn the two tools that provide that flexibility: conditionals with when, which decide whether a task runs, and loops with loop, which repeat it for each item in a list. You'll also see loop_control, the equivalence with the old with_* keywords, how to iterate over dictionaries with dict2items and how to retry a task until a condition is met with until. With them, Aurora will have its team users declared in code, packages per distribution, several databases and a playbook that waits for the website to respond.

Contents

  1. Conditionals with when
  2. Operators and tests in conditions
  3. Multiple conditions
  4. Practice: common packages per distribution
  5. Loops with loop
  6. Loops over lists of dictionaries
  7. loop_control: label, index_var and pause
  8. Loops with conditions
  9. Practice: the Aurora team users
  10. Iterating over dictionaries with dict2items
  11. Practice: several databases and access from the web servers
  12. The old with_* keywords and their loop equivalents
  13. Retrying until a condition is met: until, retries and delay

  1. Conditionals with when

The when task keyword holds an expression that Ansible evaluates for each host. If it's true, the task runs; if it's false, it's skipped (skipping):

- name: Warn if the server is low on memory
  ansible.builtin.debug:
    msg: "{{ inventory_hostname }} has only {{ ansible_facts['memtotal_mb'] }} MB of RAM"
  when: ansible_facts['memtotal_mb'] < 1500

In the lab, web1 and web2 (1 GB) will show the warning and db1 (2 GB) will appear as skipping.

A fundamental rule: when is already a Jinja2 expression, so variables are written without {{ }}:

when: aurora_env == 'production'          # correct
when: "{{ aurora_env }} == 'production'"  # wrong: Ansible warns and it may fail

You can use any variable in when: from the inventory, facts, registered variables (Lesson 3.7) or magic variables.

  1. Operators and tests in conditions

Type Operators / tests Example
Comparison ==, !=, <, >, <=, >= ansible_facts['processor_vcpus'] >= 2
Logical and, or, not, parentheses aurora_env == 'lab' or aurora_env == 'staging'
Membership in, not in 'webservers' in group_names
Definition is defined, is undefined aurora_lb_weight is defined
Booleans the variable alone, not variable when: aurora_maintenance
Versions is version(value, operator) ansible_facts['distribution_version'] is version('24.04', '>=')
Text is match, is search (regular expressions) inventory_hostname is match('web')

Some cases that deserve an explanation:

Boolean variables. If the variable is a real boolean (true/false in YAML), naming it is enough. If it may arrive as text (for example, from -e aurora_maintenance=false, Lesson 3.5), convert it with the bool filter:

when: aurora_maintenance | bool

Variables that may not exist. If you use an undefined variable in a condition, the task fails. Guard it with is defined:

- name: Show the load balancer weight
  ansible.builtin.debug:
    msg: "Weight of {{ inventory_hostname }}: {{ aurora_lb_weight }}"
  when: aurora_lb_weight is defined

aurora_lb_weight is defined in host_vars/web1.yml and web2.yml, but not on db1, which appears as skipping.

Group membership. group_names (Lesson 3.5) lets a task in a general play run only on certain groups: when: 'dbservers' in group_names.

  1. Multiple conditions

You can combine conditions with and/or or write a list, in which case all of them must be met (it's equivalent to and):

- name: Notice for Ubuntu 24.04 or later web servers
  ansible.builtin.debug:
    msg: "Modern web server"
  when:
    - "'webservers' in group_names"
    - ansible_facts['distribution'] == 'Ubuntu'
    - ansible_facts['distribution_version'] is version('24.04', '>=')

The list is more readable than a long line with and, and each condition can be commented. Notice the quotes on the first condition: it starts with a single quote, a special character in YAML, so the whole expression goes inside double quotes (Lesson 3.2).

For conditions with or, use a single expression, with parentheses if you mix operators. If it's very long, split it with a folded block:

  when: >-
    aurora_env in ['staging', 'production']
    and ('webservers' in group_names or 'dbservers' in group_names)

  1. Practice: common packages per distribution

All of Aurora's servers are Ubuntu, but it's likely that some day another distribution will join (for example, a Rocky Linux server from a provider). Get common.yml ready for it.

First, define the list of common packages in inventory/group_vars/all/aurora.yml:

---
aurora_domain: aurora-store.example
aurora_env: lab
aurora_timezone: Europe/Madrid
aurora_admin_email: [email protected]
aurora_common_packages:
  - htop
  - curl
  - vim
  - tree

Then, in common.yml, replace the Install htop task with these two:

    - name: Install the common packages (Debian family)
      ansible.builtin.apt:
        name: "{{ aurora_common_packages }}"
        state: present
        update_cache: true
        cache_valid_time: 3600
      when: ansible_facts['os_family'] == 'Debian'

    - name: Install the common packages (Red Hat family)
      ansible.builtin.dnf:
        name: "{{ aurora_common_packages }}"
        state: present
      when: ansible_facts['os_family'] == 'RedHat'
  • name: receives the whole list. Package modules accept lists and install them in a single transaction: much faster than repeating the task with a loop for each package. If the module accepts a list, pass it the list.
  • Each task runs only on the corresponding family of systems. In Aurora you'll see the second one as skipping on all three servers.
  • Another option is the generic ansible.builtin.package module, which picks the right package manager automatically; but package names often differ between distributions (vim versus vim-enhanced), and separate tasks let you adjust each case.
ansible-playbook common.yml
TASK [Install the common packages (Debian family)] *****************************
changed: [web1]
changed: [web2]
changed: [db1]

TASK [Install the common packages (Red Hat family)] ****************************
skipping: [web1]
skipping: [web2]
skipping: [db1]

  1. Loops with loop

The loop task keyword receives a list and runs the task once per item. On each iteration, the item is in the item variable:

- name: Create the Aurora working directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    mode: "0755"
  loop:
    - /srv/aurora
    - /srv/aurora/releases
    - /srv/aurora/shared

The output shows one line per item:

TASK [Create the Aurora working directories] ***********************************
changed: [web1] => (item=/srv/aurora)
changed: [web1] => (item=/srv/aurora/releases)
changed: [web1] => (item=/srv/aurora/shared)

The list can be written in the task or, better, come from a variable: loop: "{{ my_list }}" (with quotes, because it starts with {{). It can also come from a magic variable: loop: "{{ groups['webservers'] }}" iterates over the names of the web servers.

  1. Loops over lists of dictionaries

The most common case is iterating over a list of dictionaries, where each item groups several pieces of data. You access each field with item.field:

- name: Create the Aurora groups
  ansible.builtin.group:
    name: "{{ item.name }}"
    gid: "{{ item.gid }}"
    state: present
  loop:
    - { name: aurora-dev, gid: 2001 }
    - { name: aurora-ops, gid: 2002 }

(The compact { ... } style is handy for short lists written in the task itself; for inventory data, use block style.)

When a field is optional, the default filter provides a value if it doesn't exist: item.state | default('present'). You'll see it in the practice in section 9.

  1. loop_control: label, index_var and pause

loop_control adjusts the loop's behavior:

Option What it's for Example
label What to show of each item in the output label: "{{ item.name }}"
index_var Variable holding the iteration index (from 0) index_var: idx
loop_var Rename item (useful with nested loops in roles, Module 4) loop_var: user
pause Seconds to wait between iterations pause: 5
extended Extra information in ansible_loop (first, last, length…) extended: true

label is the most useful. Without it, Ansible shows the whole item on each line, which with large dictionaries (or sensitive data) is unreadable:

ok: [web1] => (item={'name': 'laura', 'comment': 'Laura Gómez - Development', 'admin': True})

With label: "{{ item.name }}":

ok: [web1] => (item=laura)

index_var and pause in a single example:

- name: Show the web servers in order
  ansible.builtin.debug:
    msg: "Server {{ idx + 1 }} of {{ groups['webservers'] | length }}: {{ item }}"
  loop: "{{ groups['webservers'] }}"
  loop_control:
    index_var: idx
    pause: 2

length returns the number of items in the list. pause is useful, for example, to avoid flooding an API or to space out actions on several services.

  1. Loops with conditions

If a task has loop and when, the condition is evaluated on each iteration, and it can use item:

- name: Create only the directories marked as needed
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: directory
    mode: "0755"
  loop:
    - { path: /srv/aurora/cache, enabled: true }
    - { path: /srv/aurora/legacy, enabled: false }
  loop_control:
    label: "{{ item.path }}"
  when: item.enabled
changed: [web1] => (item=/srv/aurora/cache)
skipping: [web1] => (item=/srv/aurora/legacy)

It's a very convenient way to filter items. (With Jinja2 filters such as selectattr you can filter the list before the loop; you'll see that in Lesson 5.3.)

  1. Practice: the Aurora team users

In Lesson 2.4 you created the deploy user with an ad hoc command, and it was lost when the machines were restored. Now you'll declare it in code, together with the rest of the team. Create the inventory/group_vars/all/team.yml file:

---
# Aurora Store team users (on every server).
# admin: true  -> member of the sudo group
# state: absent -> the user is removed
aurora_team_users:
  - name: deploy
    comment: Aurora Store deployments
  - name: laura
    comment: Laura Gómez - Development
    admin: true
  - name: marc
    comment: Marc Soler - Operations
    admin: true
  - name: jordi
    comment: Former contributor
    state: absent

And add these two tasks to common.yml, after the time zone task:

    - name: Manage the Aurora team users
      ansible.builtin.user:
        name: "{{ item.name }}"
        comment: "{{ item.comment }}"
        shell: /bin/bash
        state: "{{ item.state | default('present') }}"
      loop: "{{ aurora_team_users }}"
      loop_control:
        label: "{{ item.name }}"

    - name: Grant administrator privileges to the team admins
      ansible.builtin.user:
        name: "{{ item.name }}"
        groups: sudo
        append: true
      loop: "{{ aurora_team_users }}"
      loop_control:
        label: "{{ item.name }}"
      when:
        - item.admin | default(false)
        - item.state | default('present') == 'present'
  • The first task creates or removes each user. For those without a state, default('present') treats them as present.
  • The second adds only the administrators (admin: true) who are still active to the sudo group. append: true is essential: without it, the module would replace all of the user's secondary groups with sudo.
  • jordi has state: absent: if the user existed, it would be removed (its home directory is kept; add remove: true if you want to delete that too). This is how users are offboarded with Ansible: mark them absent and, once they no longer exist on any server, take them off the list.
  • Users are created without a password; access will be through SSH keys. Managing public keys (ansible.posix.authorized_key) and hardening sudo belongs to Lesson 9.2. In a real environment, the account and privilege policy must be reviewed by whoever is responsible for security.

Run it and check:

ansible-playbook common.yml
ansible aurora -a 'id laura'
TASK [Grant administrator privileges to the team admins] ***********************
skipping: [web1] => (item=deploy)
changed: [web1] => (item=laura)
changed: [web1] => (item=marc)
skipping: [web1] => (item=jordi)
...
web1 | CHANGED | rc=0 >>
uid=1002(laura) gid=1002(laura) groups=1002(laura),27(sudo)

Now that deploy exists in code, the website directory can belong to it, as in Lesson 2.5. In webservers.yml, change the owner of the root directory:

    - name: Create the web root directory
      ansible.builtin.file:
        path: "{{ aurora_web_root }}"
        state: directory
        owner: deploy
        group: deploy
        mode: "0755"

This creates a dependency: webservers.yml needs common.yml to have been applied first. site.yml already guarantees that order (Lesson 3.4); that's why, from now on, the normal way to configure Aurora is ansible-playbook site.yml.

  1. Iterating over dictionaries with dict2items

loop needs a list. If your data is in a dictionary, convert it with the dict2items filter, which produces a list of items with two fields: key and value.

aurora_static_pages:
  robots.txt: "..."
  status.html: "..."
# "{{ aurora_static_pages | dict2items }}" produces:
- key: robots.txt
  value: "..."
- key: status.html
  value: "..."

Use it to publish static pages on the web servers. Add to inventory/group_vars/webservers.yml:

aurora_static_pages:
  robots.txt: |
    User-agent: *
    Disallow: /admin/
  status.html: |
    <p>OK</p>

And to webservers.yml, after Publish the store home page:

    - name: Publish the store static pages
      ansible.builtin.copy:
        dest: "{{ aurora_web_root }}/{{ item.key }}"
        content: "{{ item.value }}"
        owner: root
        group: root
        mode: "0644"
      loop: "{{ aurora_static_pages | dict2items }}"
      loop_control:
        label: "{{ item.key }}"

A dictionary is ideal when each item has a unique name (here, the file name): if someone adds another entry with the same name at another level of the inventory, it replaces the original instead of duplicating it. The reverse filter, items2dict, also exists.

  1. Practice: several databases and access from the web servers

Aurora Store needs a second database for reports and a read-only user for the analytics tool. Instead of duplicating tasks, turn the ones in dbservers.yml into loops. Add to inventory/group_vars/dbservers.yml:

postgresql_users:
  - name: "{{ aurora_db_user }}"
  - name: aurora_reporting
postgresql_databases:
  - name: "{{ aurora_db_name }}"
    owner: "{{ aurora_db_user }}"
  - name: aurora_analytics
    owner: aurora_reporting

In dbservers.yml, replace the Create the application user in PostgreSQL and Create the store database tasks with:

    - name: Create the PostgreSQL users
      community.postgresql.postgresql_user:
        name: "{{ item.name }}"
        state: present
      become_user: postgres
      loop: "{{ postgresql_users }}"
      loop_control:
        label: "{{ item.name }}"

    - name: Create the databases
      community.postgresql.postgresql_db:
        name: "{{ item.name }}"
        owner: "{{ item.owner }}"
        state: present
      become_user: postgres
      loop: "{{ postgresql_databases }}"
      loop_control:
        label: "{{ item.name }}"

Order still matters: first the users and then the databases that have them as owners.

In addition, PostgreSQL only accepts local connections by default. The web servers need a rule in pg_hba.conf (the access control file) for each web server. Iterate over groups['webservers'] and use hostvars (Lesson 3.5) to get each IP. Add, right after the previous ones:

    - name: Allow the web servers to access the store database
      community.postgresql.postgresql_pg_hba:
        dest: "/etc/postgresql/{{ postgresql_version }}/main/pg_hba.conf"
        contype: host
        databases: "{{ aurora_db_name }}"
        users: "{{ aurora_db_user }}"
        address: "{{ hostvars[item]['ansible_host'] }}/32"
        method: scram-sha-256
        state: present
      loop: "{{ groups['webservers'] }}"
      register: postgresql_hba

    - name: Reload PostgreSQL if access control has changed (temporary)
      ansible.builtin.systemd_service:
        name: postgresql
        state: reloaded
      when: postgresql_hba.changed
  • Each iteration adds a rule: host aurora aurora 192.168.56.11/32 scram-sha-256 and the equivalent for web2. If you add web3 to the inventory tomorrow, it will get its rule without touching the playbook.
  • register on a loop stores the results of all iterations, and postgresql_hba.changed is true if any iteration changed something (you'll see this in detail in Lesson 3.7).
  • Changes to pg_hba.conf only need a reload (reloaded), not a restart. Again, the temporary pattern until handlers.
  • The module may reorder the lines of the file when writing it. The aurora user doesn't have a password yet, so the real connection from the website will be tested once it does (Lesson 5.4).
ansible-playbook site.yml --limit db1
ansible db1 -a 'psql -tAc "SELECT datname FROM pg_database WHERE datname LIKE $$aurora%$$"' -b --become-user postgres
ansible db1 -a 'grep scram /etc/postgresql/16/main/pg_hba.conf' -b

The first query lists aurora and aurora_analytics (the $$...$$ are a way of writing strings in PostgreSQL without fighting the terminal's quotes); the second shows the two new rules.

  1. The old with_* keywords and their loop equivalents

Before Ansible 2.5, loops were written with with_<lookup> keywords. They still work and you'll find them in many old projects and roles, but loop is the recommended form. Equivalents:

Old form loop equivalent
with_items: "{{ list }}" loop: "{{ list | flatten(levels=1) }}" (or loop: "{{ list }}" if there are no nested lists)
with_list: "{{ list }}" loop: "{{ list }}"
with_dict: "{{ dict }}" loop: "{{ dict | dict2items }}"
with_indexed_items: "{{ list }}" loop: "{{ list }}" + loop_control: {index_var: idx}
with_sequence: start=1 end=3 loop: "{{ range(1, 4) | list }}"
with_together: [a, b] loop: "{{ a | zip(b) | list }}"
with_nested: [a, b] loop: "{{ a | product(b) | list }}"
with_subelements: [list, field] loop: "{{ list | subelements('field') }}"
with_fileglob: "*.conf" loop: "{{ query('fileglob', '*.conf') }}"

Details:

  • with_items "flattens" one level of nested lists; loop doesn't. That's why its exact equivalent includes flatten(levels=1).
  • The with_* keywords are actually lookups (plugins that fetch data); with loop they're used through query(). Lookups are covered in Lesson 5.3.
  • Don't convert working old code just for looks, but write all of Aurora's new code with loop.

  1. Retrying until a condition is met: until, retries and delay

Sometimes a task must be repeated over time until something is ready: a service that takes a while to start, an API that isn't responding yet. That's what until, retries and delay are for:

Keyword Meaning Default
until Condition that must be met for the task to count as successful —
retries Maximum number of retries 3
delay Seconds between attempts 5

The condition needs to look at the task's result, so it's combined with register (you'll study it in depth in Lesson 3.7). Add a post_tasks section to webservers.yml (after tasks) that waits for the website to respond:

  post_tasks:
    - name: Wait for the store website to respond
      ansible.builtin.uri:
        url: "http://localhost:{{ nginx_port }}/"
      register: aurora_web_check
      until: aurora_web_check.status == 200
      retries: 5
      delay: 3
  • The ansible.builtin.uri module makes an HTTP request from the web server itself (hence localhost) and returns, among other things, the status code in status.
  • If the response isn't 200 (or the connection fails), Ansible waits 3 seconds and tries again, up to 5 times. If the retries run out, the task fails.
  • It's the perfect place for the verification you announced in Lesson 3.4: post_tasks runs at the end, after all the configuration tasks.

It will normally respond on the first attempt. To see the retries you need nginx to be stopped just when this task arrives, but the Ensure nginx is started... task would start it first. The trick is to start the playbook directly at the waiting task with --start-at-task (an option you'll study in Lesson 3.7). Stop nginx on web1, launch the playbook and, in another terminal, start it again a few seconds later:

ansible web1 -m ansible.builtin.systemd_service -a 'name=nginx state=stopped' -b
ansible-playbook webservers.yml --limit web1 --start-at-task "Wait for the store website to respond"
# In another terminal, while it retries:
ansible web1 -m ansible.builtin.systemd_service -a 'name=nginx state=started' -b
TASK [Wait for the store website to respond] ***********************************
FAILED - RETRYING: [web1]: Wait for the store website to respond (5 retries left).
FAILED - RETRYING: [web1]: Wait for the store website to respond (4 retries left).
ok: [web1]

To wait for a port to be open, without making an HTTP request, there's the ansible.builtin.wait_for module (port: 5432, timeout: 60).

Run the full site.yml to check that everything is idempotent and commit the work:

ansible-playbook site.yml
ansible-playbook site.yml      # changed=0 on every host
git add common.yml webservers.yml dbservers.yml inventory/
git commit -m "Conditionals and loops: packages per distribution, team, static pages, databases and pg_hba"

Common Mistakes and Tips

  • {{ }} inside when: when: "{{ aurora_env }} == 'lab'" triggers a warning and may misbehave. In when, until and changed_when/failed_when, variables go without braces.
  • Comparing a boolean or a number with text: when: aurora_maintenance == 'true' isn't met if the variable is the boolean true. Use when: aurora_maintenance | bool.
  • 'dict object' has no attribute 'admin': an item in the loop doesn't have the field. Use item.admin | default(false) for optional fields.
  • Forgetting append: true when adding groups with ansible.builtin.user: the user loses all their other secondary groups.
  • Using loop to install packages one by one: it works but it's much slower. Pass the list directly to the name parameter.
  • until without register: the condition has no data to evaluate and fails. They always go together.
  • Confusing loop with with_items on nested lists: loop doesn't flatten; if a variable contains lists of lists, use flatten.
  • Tip: always set label on loops over dictionaries; the output will be readable and won't expose data you don't want to show.

Exercises

Exercise 1: A lab-only task

Add a task to common.yml that installs the cowsay package only when aurora_env is lab and the host belongs to the webservers group. Use a list of conditions. Run it and check which hosts skip it. Then remove it (first with state: absent, as you learned in Lesson 3.4).

Exercise 2: A new team member

Add Nuria Vidal, from support, to aurora_team_users without administrator privileges, and offboard marc. What changes when common.yml runs? What happens to marc's membership of the sudo group?

Exercise 3: Directories from a dictionary

In a test play, define the aurora_dirs variable as a dictionary where the key is the path and the value is the mode (/srv/aurora/uploads: "0770", /srv/aurora/logs: "0750"), and create the directories with a loop and dict2items, showing only the path in the output.

Solutions

Exercise 1.

    - name: Install cowsay on the lab web servers
      ansible.builtin.apt:
        name: cowsay
        state: present
      when:
        - aurora_env == 'lab'
        - "'webservers' in group_names"

db1 appears as skipping (it isn't in webservers). To remove it: change to state: absent, run ansible-playbook common.yml and delete the task.

Exercise 2. In inventory/group_vars/all/team.yml:

  - name: marc
    comment: Marc Soler - Operations
    admin: true
    state: absent
  - name: nuria
    comment: Nuria Vidal - Support

The first task creates nuria and removes marc on every server; the second skips nuria (she isn't an administrator) and marc (thanks to the second condition, which avoids trying to add a removed user to sudo). When the user is removed, their sudo membership disappears too. If, instead of offboarding him, you only removed admin: true, he would remain in sudo: the task only adds, it doesn't take away. Explicitly revoking privileges is a good improvement for Lesson 9.2.

Exercise 3.

---
- name: Aurora test directories
  hosts: webservers
  become: true
  vars:
    aurora_dirs:
      /srv/aurora/uploads: "0770"
      /srv/aurora/logs: "0750"
  tasks:
    - name: Create the directories
      ansible.builtin.file:
        path: "{{ item.key }}"
        state: directory
        mode: "{{ item.value }}"
      loop: "{{ aurora_dirs | dict2items }}"
      loop_control:
        label: "{{ item.key }}"

The modes are in quotes so they're strings with the leading zero (Lesson 3.2). Delete the test file when you're done (and, if you like, the directories with state: absent).

Conclusion

Your playbooks can now decide and repeat. With when you run tasks based on facts, variables, booleans, group membership or versions, combining conditions with operators or with lists; with loop you repeat a task for each item in a list or a dictionary (dict2items), adjust the output and pace with loop_control and filter iterations with when; you know the equivalence with the old with_* keywords; and with until, retries and delay you wait for a service to be ready. Aurora takes advantage of all of it: common packages per distribution, the team (including deploy) declared in team.yml, static pages, two databases with their users, pg_hba.conf rules for each web server and a post_tasks section that waits for the website to respond. In several of these tasks you've used register without going into it in depth. In the next lesson, Registering Results and Debugging Playbooks, you'll discover exactly what a registered result contains, how to control when a task counts as changed or failed, and every tool for diagnosing a playbook that doesn't do what you expect.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved