Aurora Store now has four servers, four roles, templates, secrets, checks, tags and a rolling deployment. All of that comes at a cost: ansible-playbook site.yml takes considerably longer than at the beginning of the course, and with every new server and every new task it will take longer still. A slow playbook isn't just a nuisance: it gets run less often (and drift builds up), it drags out deployments and urgent interventions, and in a CI/CD system it eats up machine time. In this lesson you'll learn to measure where the time goes with the profiling callbacks, and to apply the optimizations that depend on how you write your playbooks: controlling fact gathering, using modules that accept lists instead of loops, avoiding unnecessary command tasks and false changes, launching long tasks in the background with async/poll, and taking advantage of parallelism. You'll only mention the configuration optimizations (pipelining, ControlPersist, fact caching): they're covered in depth in Lesson 9.3.

Contents

  1. Measure before optimizing
  2. Timing callbacks: timer, profile_tasks and profile_roles
  3. Reading Aurora's profile
  4. Facts: gather_facts and gather_subset
  5. Modules that accept lists instead of loops
  6. Fewer command and shell tasks
  7. changed_when against false changes
  8. Long tasks: async and poll
  9. Parallelism: forks and the free strategy
  10. Configuration optimizations (Lesson 9.3)
  11. Verifying and saving the work

  1. Measure before optimizing

The golden rule of any optimization: measure first. Intuition is often wrong: a task that "seems" slow may last half a second, and the fact gathering that nobody looks at may be half of the total time.

The method you'll follow:

flowchart LR
    A[Measure the initial situation] --> B[Identify the tasks<br/>that take the longest]
    B --> C[Apply ONE optimization]
    C --> D[Measure again]
    D --> E{Does it improve without<br/>breaking anything?}
    E -- Yes --> F[Save and carry on]
    E -- No --> G[Undo]
    F --> B

And a warning: optimizing never justifies losing idempotency, checks or security. A fast playbook that leaves servers in an uncertain state isn't an improvement.

  1. Timing callbacks: timer, profile_tasks and profile_roles

Callbacks are plugins that react to the events of a run (Lesson 1.4). Besides the one that displays the output (stdout_callback), you can enable others that add information. Three of them, in the ansible.posix collection (included in the ansible package), measure times:

Callback What it shows
ansible.posix.timer The total time of the run, at the end
ansible.posix.profile_tasks The time and duration of each task as it runs, and at the end the slowest tasks
ansible.posix.profile_roles At the end, the total time consumed by each role

They're enabled with the callbacks_enabled option in [defaults] of ansible.cfg (a comma-separated list) or with the ANSIBLE_CALLBACKS_ENABLED environment variable, which replaces it.

Aurora will enable timer permanently (one line at the end that doesn't get in the way and helps you notice when something starts taking longer) and the profiles on demand, because they fill up the output. In ansible.cfg, [defaults]:

# Additional callbacks: total time of each run.
# To profile: ANSIBLE_CALLBACKS_ENABLED=ansible.posix.timer,ansible.posix.profile_tasks
callbacks_enabled = ansible.posix.timer

Check it:

ansible-config dump --only-changed | grep -i callbacks
ansible-playbook site.yml
...
PLAY RECAP *********************************************************************
...
Playbook run took 0 days, 0 hours, 1 minutes, 52 seconds

(The times in this lesson are approximate: they depend on your computer and on the lab network.)

  1. Reading Aurora's profile

Run site.yml with both profiles:

ANSIBLE_CALLBACKS_ENABLED=ansible.posix.timer,ansible.posix.profile_tasks,ansible.posix.profile_roles \
  ansible-playbook site.yml

During the run, profile_tasks adds a line to each task with the time, the duration of the previous task and the accumulated time:

TASK [common : Install the common packages (Debian family)] ********************
Wednesday 26 November 2026  11:02:14 +0100 (0:00:01.932)       0:00:03.118 *****
ok: [lb1]
ok: [web1]
...

And at the end, the summary of the slowest tasks (here, an excerpt) and the summary of the roles:

===============================================================================
Gathering Facts ------------------------------------------------------------ 9.84s
common : Install the common packages (Debian family) ----------------------- 4.21s
nginx : Install nginx ------------------------------------------------------ 3.12s
postgresql : Install PostgreSQL and the Ansible module dependencies -------- 2.37s
Wait for the store website to respond -------------------------------------- 1.46s
Reload the load balancer without this server ------------------------------- 1.40s
...
===============================================================================
common --------------------------------------------------------------------- 14.62s
nginx ---------------------------------------------------------------------- 13.88s
aurora_app ----------------------------------------------------------------- 7.05s
postgresql ----------------------------------------------------------------- 6.71s

(The summary is sorted from longest to shortest duration and, by default, shows the twenty slowest tasks.) What a profile like Aurora's usually reveals:

  • Gathering Facts is the "task" that takes the longest: it runs at the start of every play (four plays) and, in webservers.yml, once per batch because of serial. It adds up to many seconds that do nothing useful if the play doesn't use facts.
  • Package installations take time even when they don't install anything: apt has to query the state of the packages (and cache_valid_time fortunately avoids updating the cache on every run).
  • The rolling deployment multiplies: with serial: 1, the web servers play is, in practice, two plays in a row. That's the price of safety, and it isn't touched.

  1. Facts: gather_facts and gather_subset

Gathering facts (Lesson 3.5) runs the setup module, which queries dozens of pieces of system data: hardware, network, disks, mounts, services… It's a relatively expensive task, and by default it's done at the start of every play. There are two ways to reduce its cost:

Option Effect When
gather_facts: false Gathers nothing The play doesn't use facts
gather_subset: [min] Gathers only a small subset The play uses few facts (system, distribution, local facts)

The min subset includes, among other things, the distribution (distribution, distribution_major_version, os_family), the local facts (ansible_local), the date, the user and the package and service managers. It doesn't include hardware (memory, CPU), network (interfaces, default_ipv4) or disks. Other subsets you can add: hardware, network, virtual, facter, ohai; and with ! in front, you exclude them (gather_subset: ['!hardware']).

Which facts does each Aurora play use? Review it by searching for ansible_facts in the roles and playbooks:

grep -rn "ansible_facts\|ansible_local" roles/ *.yml
Play Facts it uses Decision
common.yml os_family (packages) and ansible_local (re-read with setup after publishing them) gather_subset: [min]
dbservers.yml distribution, distribution_major_version and os_family (per-distribution variables) gather_subset: [min]
loadbalancers.yml None gather_facts: false
webservers.yml None gather_facts: false

Apply the changes to the header of each play. common.yml:

---
- name: Common configuration for Aurora Store servers
  hosts: aurora
  become: true
  gather_subset:
    - min

  roles:
    - common

dbservers.yml (only the header changes; roles and post_tasks stay the same):

---
- name: Configure the Aurora Store database servers
  hosts: dbservers
  become: true
  gather_subset:
    - min

loadbalancers.yml and webservers.yml, adding gather_facts: false after become: true (in webservers.yml, before serial: 1):

  become: true
  gather_facts: false

A risk you should keep in mind: if tomorrow someone adds a task to nginx or aurora_app that uses ansible_facts, it will fail with an undefined variable in those plays. That's why it's a good idea to document it (for example, in each role's README.md: "Doesn't need facts") and, if a role needs them, to have it gather them itself explicitly with ansible.builtin.setup and gather_subset.

  1. Modules that accept lists instead of loops

Each iteration of a loop is a full run of the module: connection (or connection reuse), transfer, execution and response. Many package modules accept a list and do all the work in one go:

# Slow: four apt runs, four queries to the package manager
- name: Install the common packages
  ansible.builtin.apt:
    name: "{{ item }}"
    state: present
  loop: "{{ common_packages }}"

# Fast: a single apt run with the whole list
- name: Install the common packages
  ansible.builtin.apt:
    name: "{{ common_packages }}"
    state: present

The second form isn't only faster (in the lab, around four times less for that task): it's also more correct, because apt resolves the dependencies of all the packages at once. Aurora has used it in the common and postgresql roles from the start.

Module Accepts a list? Alternative to the loop
apt, dnf, package, pip Yes (name) Pass the list
user, group No The loop is necessary
copy, template No (one file per task) For many files: ansible.posix.synchronize or an archive with unarchive
file No Loop; for whole trees, state: directory with recurse where applicable
community.general.ufw No Loop (Aurora has two rules: not worth it)
postgresql_user, postgresql_db No Loop

In Aurora, the remaining loops (users, static pages, PostgreSQL users and databases) belong to modules that work with one element at a time, and they're short lists anyway.

  1. Fewer command and shell tasks

command and shell tasks have a double cost: each one is one more remote execution and, if you're not careful with them, they break idempotency. Before writing one, ask yourself whether the information is already available:

To get… Instead of command Use
The system version lsb_release -a Facts (ansible_facts['distribution_version'])
Whether a file exists test -f ... ansible.builtin.stat
Installed packages dpkg -l ansible.builtin.package_facts
The state of services systemctl is-active ... ansible.builtin.service_facts
The content of a remote file cat ... ansible.builtin.slurp
Data from an HTTP response curl -I ... ansible.builtin.uri (and its result)

Aurora has a clear case in webservers.yml: "Get the nginx version" runs nginx -v just to show the version. But the "Wait for the store website to respond" task already makes an HTTP request to nginx, and uri returns the response headers in its result, with lowercase names. The Server header contains the version (nginx/1.24.0 (Ubuntu)). Remove the "Get the nginx version" task from the post_tasks and change the one that shows it:

    - name: Show the nginx version
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }}: {{ aurora_web_check.server | default('unknown') }}"
      tags:
        - never
        - info
ansible-playbook webservers.yml --tags info
TASK [Show the nginx version] **************************************************
ok: [web1] =>
    msg: 'web1: nginx/1.24.0 (Ubuntu)'

One task fewer, and the information comes from something that was already being done. The default('unknown') covers the day you hide the nginx version (server_tokens off, Lesson 9.2): the header would still exist, but only with nginx.

  1. changed_when against false changes

You've worked on this in Lessons 3.7 and 5.5, but it deserves a reminder from a performance angle: a false changed isn't free. If a task reports a change without there being one, it notifies handlers that reload or restart services on every run, and an unnecessary reload costs time (and, in PostgreSQL, a restart drops connections). What's more, changed=0 stops being a reliable sign that there's no drift, and you start ignoring changes.

Review it periodically with a second run:

ansible-playbook site.yml | grep -E '^(changed|RUNNING HANDLER)'

In Aurora nothing should come out. The command, shell and uri tasks that only query have changed_when: false, and so do the load balancer tasks in the rolling deployment (Lesson 5.7).

  1. Long tasks: async and poll

By default, Ansible runs each task and waits with the connection open for it to finish. For very long tasks (a full system upgrade, a large backup, a compilation) that has two problems: the SSH connection may be dropped due to inactivity, and Ansible can't do anything else in the meantime. With async the task is launched in the background on the server and Ansible checks its status periodically:

Keyword Meaning
async: N Maximum time (seconds) the task can last; if it exceeds it, it's considered failed
poll: M How often (in seconds) Ansible checks whether it has finished. With poll: 0, it doesn't wait ("fire and forget")

In Lesson 2.4 you used it ad hoc with -B and -P. In a playbook, Aurora will have a maintenance playbook to upgrade the servers' packages. Create upgrade.yml at the root of the project:

---
# Maintenance: upgrade the system packages on the Aurora Store servers.
# Usage: ansible-playbook upgrade.yml [--limit <hosts>]
# Warning: if nginx or PostgreSQL are upgraded, their services are restarted. On the
# web servers, apply it outside business hours or server by server with --limit.
- name: Upgrade the packages on the Aurora Store servers
  hosts: aurora
  become: true
  gather_facts: false

  tasks:
    - name: Upgrade all the system packages
      ansible.builtin.apt:
        upgrade: dist
        update_cache: true
        cache_valid_time: 3600
      async: 1800
      poll: 15

    - name: Check whether the system needs a reboot
      ansible.builtin.stat:
        path: /var/run/reboot-required
      register: aurora_reboot_required

    - name: Report the servers that need a reboot
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} needs a reboot to complete the upgrade"
      when: aurora_reboot_required.stat.exists
  • async: 1800: the upgrade can last up to 30 minutes. poll: 15: Ansible checks every 15 seconds whether it has finished, without keeping an execution blocked on the connection.
  • There's no automatic reboot: the playbook reports, and the reboot is decided on (and done in a rolling fashion, like the deployment in Lesson 5.7). The ansible.builtin.reboot module exists for when you want to automate it.

Run it first on a single server:

ansible-playbook upgrade.yml --limit db1

Fire and forget: poll: 0 and async_status

With poll: 0, the task is launched and Ansible moves on to the next one immediately. Later, you can wait for the result with ansible.builtin.async_status:

- name: Launch the database backup in the background
  ansible.builtin.command:
    cmd: pg_dump -Fc -f /var/backups/aurora.dump aurora
  become_user: postgres
  async: 3600
  poll: 0
  register: aurora_backup_job

- name: Do other tasks in the meantime
  ansible.builtin.debug:
    msg: "The backup is still running..."

- name: Wait for the backup to finish
  ansible.builtin.async_status:
    jid: "{{ aurora_backup_job.ansible_job_id }}"
  become_user: postgres
  register: aurora_backup_result
  until: aurora_backup_result.finished
  retries: 120
  delay: 30
  • register on the launched task stores the job identifier (ansible_job_id).
  • async_status with until/retries/delay (Lesson 3.6) waits for finished to be true, for up to 120 × 30 s = 1 hour.
  • async_status must run as the same user that launched the task (hence the become_user), because the job's status is stored in that user's home directory.

The example is illustrative: Aurora's backups will be designed in the final project. Keep it in mind for long, independent tasks that can overlap with others.

Configuration Behavior
Without async Normal execution: Ansible waits with the connection open
async: N, poll: M > 0 Background; Ansible waits, checking every M seconds
async: N, poll: 0 Background; Ansible doesn't wait; result via async_status

  1. Parallelism: forks and the free strategy

Two reminders from earlier lessons, now as performance tools:

  • forks (Lesson 2.3) is the maximum number of hosts Ansible processes at the same time. Aurora uses 10, which is enough for its four servers. On large fleets, raising it speeds things up a lot, at the cost of more load on the control node (memory and processes) and on shared services (package repositories, for example).
  • strategy: free (Lesson 5.7) lets each host advance at its own pace. It speeds up plays with heterogeneous, independent hosts, such as common.yml (db1 has no reason to wait for lb1). Measure it before adopting it: with four similar hosts the gain is small and the output becomes harder to read, so Aurora stays with linear. Never in webservers.yml, because of the rolling deployment.

  1. Configuration optimizations (Lesson 9.3)

There's another group of optimizations that doesn't depend on how you write playbooks, but on how Ansible is configured. They're very effective and are covered in depth, with measurements, in Lesson 9.3, Performance Tuning:

Optimization Idea Status in Aurora
Pipelining Sends modules over the SSH connection without first copying them to a temporary file, reducing the operations per task pipelining = False since Lesson 2.3
ControlPersist Reuses the SSH connection between tasks instead of opening a new one each time Enabled with 60 s in ssh_args (Lesson 2.3)
Fact caching Keeps facts between runs so they aren't gathered every time Not configured
ansible-pull, Mitogen and others Deeper changes to the execution model Not applicable

Don't change them now: each one has requirements and implications (for example, pipelining interacts with become and the sudo configuration) that you'll see in its lesson.

  1. Verifying and saving the work

Measure again with the same callbacks as in section 3:

ANSIBLE_CALLBACKS_ENABLED=ansible.posix.timer,ansible.posix.profile_tasks \
  ansible-playbook site.yml

Compare with the initial measurement. With the facts changes and the command task removed, you'll see something along these lines:

Measurement Before After
Gathering Facts (total) ~10 s ~3 s
Total time of site.yml with no changes ~1 min 52 s ~1 min 35 s
command tasks in webservers.yml 1 0
changed on the second run 0 0

The last row is the most important: the optimization hasn't changed the result. Also check that filtered runs still work:

ansible-playbook site.yml --tags users --check
ansible-playbook webservers.yml --tags info

Save the work:

git add ansible.cfg common.yml dbservers.yml loadbalancers.yml webservers.yml upgrade.yml
git commit -m "Optimization: timer callback, facts only where used, fewer commands; upgrade.yml playbook"

The state of the repository at the end of Module 5:

aurora-infra/
├── ansible.cfg            ← roles_path, force_handlers, ansible_managed, vault_identity_list, callbacks_enabled
├── site.yml               ← common.yml → dbservers.yml → loadbalancers.yml → webservers.yml
├── common.yml             ← gather_subset: [min]
├── dbservers.yml          ← gather_subset: [min]; checks with the store's credentials
├── loadbalancers.yml      ← new (5.7): nginx role in load balancer mode
├── webservers.yml         ← serial: 1, delegated load balancer, gather_facts: false
├── upgrade.yml            ← new (5.8): maintenance with async/poll
├── inventory/
│   ├── hosts.yml          ← + loadbalancers: lb1
│   ├── group_vars/
│   │   ├── all/{aurora.yml, common.yml, team.yml, vault.yml}
│   │   ├── dbservers/{vars.yml, vault.yml}
│   │   ├── loadbalancers.yml
│   │   └── webservers.yml
│   └── host_vars/{db1.yml, web1.yml, web2.yml}
├── roles/
│   ├── common/      (+ templates/{motd.j2, facts.fact.j2}; tasks in tagged blocks)
│   ├── nginx/       (+ handlers/, templates/{nginx.conf.j2, site.conf.j2})
│   ├── postgresql/  (+ handlers/, templates/{parameters.conf.j2, pg_hba.conf.j2})
│   └── aurora_app/  (+ templates/{index.html.j2, db.conf.j2}; deployment with rollback)
├── lab/Vagrantfile        ← + lb1
├── .gitignore             ← + *.pass, .vault_pass*
└── .gitattributes         ← optional (diff of Vault files)

Common Mistakes and Tips

  • Optimizing without measuring: you change things that "should be faster" without knowing whether they were the problem. Profile first.
  • gather_facts: false and then an undefined ansible_facts: a role uses facts that the play no longer gathers. Review with grep before disabling them and document what each role needs.
  • async on short tasks: it adds overhead (launching the job, checking its status) with no benefit. Keep it for tasks that take minutes.
  • poll: 0 without checking the result: if the task fails in the background, Ansible doesn't find out. Use async_status, unless you really don't care about the result.
  • Raising forks without limit: the control node runs out of memory, or the shared services get overloaded. Raise it gradually and measure.
  • Removing checks to save time: the post_tasks and the assert tasks are what let you trust a deployment. Their cost is small compared with a failure in production.
  • Tip: keep the measurements (for example, the total time from timer) when you change something important. A run that goes from 2 to 4 minutes for no apparent reason usually points to a real problem (a slow repository, a server with network problems).

Exercises

Exercise 1: Performance review

Point out all the performance (and idempotency) problems in this play and rewrite it:

- name: Prepare reporting servers
  hosts: dbservers
  become: true
  tasks:
    - name: Install tools
      ansible.builtin.apt:
        name: "{{ item }}"
        update_cache: true
      loop: [postgresql-client, jq, unzip]

    - name: See whether the reports directory exists
      ansible.builtin.shell: ls /srv/reports
      register: reports
      ignore_errors: true

    - name: Create the reports directory
      ansible.builtin.command: mkdir /srv/reports
      when: reports.rc != 0

Exercise 2: Two long tasks in parallel

On db1, you want to compress two large files (/var/backups/a.dump and /var/backups/b.dump) with gzip, each of which takes several minutes, and you want both compressions to run at the same time. Write the tasks.

Exercise 3: Interpreting a profile

A colleague shows you this profile_tasks summary from a playbook with 30 hosts and forks = 5:

Gathering Facts ----------------------------------------------- 95.20s
app : Install dependencies ------------------------------------ 61.04s
app : Check the configuration --------------------------------- 2.10s

Propose three improvements, ordered by the impact you expect, and explain how you'd verify each one.

Solutions

Exercise 1. Problems: the apt loop runs the module three times and updates the cache on every iteration (update_cache without cache_valid_time); shell to check whether a directory exists (not idempotent, always changed, and ignore_errors shows a red failure on every run); command: mkdir instead of a module; and it gathers all the facts without using them.

- name: Prepare reporting servers
  hosts: dbservers
  become: true
  gather_facts: false
  tasks:
    - name: Install the reporting tools
      ansible.builtin.apt:
        name:
          - postgresql-client
          - jq
          - unzip
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Create the reports directory
      ansible.builtin.file:
        path: /srv/reports
        state: directory
        mode: "0755"

Two tasks instead of three, with no shell or command, idempotent (changed=0 on the second run) and without facts. file with state: directory already does "create it if it doesn't exist".

Exercise 2.

- name: Launch the compression of the dumps
  ansible.builtin.command:
    cmd: "gzip {{ item }}"
    creates: "{{ item }}.gz"
  loop:
    - /var/backups/a.dump
    - /var/backups/b.dump
  async: 1800
  poll: 0
  register: aurora_gzip_jobs

- name: Wait for the compressions to finish
  ansible.builtin.async_status:
    jid: "{{ item.ansible_job_id }}"
  loop: "{{ aurora_gzip_jobs.results }}"
  loop_control:
    label: "{{ item.item }}"
  register: aurora_gzip_status
  until: aurora_gzip_status.finished
  retries: 60
  delay: 30
  when: item.ansible_job_id is defined

With poll: 0, the loop launches both compressions without waiting, and both run at the same time on the server. The second task waits for each one. creates makes the task idempotent: if the .gz already exists, that iteration is skipped and there's no job to wait for (hence the when).

Exercise 3. (1) Facts: 95 s is the most expensive item. Check which facts the playbook uses and apply gather_facts: false or gather_subset; with 30 hosts, also fact caching (Lesson 9.3). (2) forks: with 5, the 30 hosts are processed in 6 rounds; raising it to 15 or 30 (if the control node can handle it) reduces all the times. (3) "Install dependencies": check whether it uses a loop instead of a list, whether it updates the package cache on every run (cache_valid_time) and whether a local repository or cache could be used. Each improvement is verified the same way: apply it on its own, profile again with profile_tasks and compare, checking that the second run still gives changed=0.

Conclusion

You've completed Module 5. You've learned to measure with the timer, profile_tasks and profile_roles callbacks (Aurora keeps ansible.posix.timer enabled in callbacks_enabled and profiles on demand with ANSIBLE_CALLBACKS_ENABLED), to gather only the facts you need (gather_subset: [min] in common.yml and dbservers.yml, gather_facts: false in loadbalancers.yml and webservers.yml), to prefer modules that accept lists, to replace command tasks with information you already have (the nginx version now comes from the Server header that uri returns), to avoid false changes and to launch long tasks with async and poll, as in the new upgrade.yml maintenance playbook; and you know that pipelining, ControlPersist and fact caching await you in Lesson 9.3. Looking back over the module, Aurora Store has taken a leap forward: handlers that validate before reloading, configuration in Jinja2 templates, filters that derive data from the inventory, passwords encrypted with Vault, a deployment that rolls itself back if it fails, tags to run only what's needed, a load balancer with a zero-downtime rolling deployment, and faster playbooks. Everything in aurora-infra/roles/ you've written yourself, from scratch. But many of the problems you've solved (installing nginx, managing PostgreSQL, configuring a firewall) are the same ones thousands of teams around the world face, and many of them share their solutions. In Module 6: Ansible Galaxy you'll start with the lesson What Is Ansible Galaxy?, where you'll discover the community's public repository of roles and collections, how to assess whether content can be trusted, and when it makes sense to reuse other people's work instead of writing your own.

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