In the previous lesson you designed the final project: requirements, an architecture with the new mon1 server, thirteen design decisions (ADRs), a seven-phase plan and eighteen acceptance criteria. Now it's time to build it. This lesson goes through the phases one by one with the reference code for the missing pieces: the upgrade to ansible-core 2.20 and aurora-ee 2.0.0, the PostgreSQL backup role with its restore test, monitoring with Prometheus, node_exporter and Alertmanager connected to the Event-Driven Ansible rulebook, the remote Terraform state, the staging and production environments in AWX and the staging → smoke tests → approval → production promotion workflow. Then you will organize the tests, write the deployment and rollback runbooks, complete the self-assessment checklist and release version 1.5.0 of the website end to end. This is the last lesson of the course: when you finish it, Aurora Store will be in production on a platform you have built piece by piece.

Contents

  1. How to use this lesson
  2. Phase 1: ansible-core 2.20 and aurora-ee 2.0.0
  3. Phase 2: PostgreSQL backups
  4. Phase 3: monitoring with Prometheus and Alertmanager
  5. Phase 4: from alerts to AWX with Event-Driven Ansible
  6. Phase 5: remote Terraform state and staging in AWX
  7. Phase 6: smoke tests and the promotion workflow
  8. The project's tests
  9. Deployment runbook
  10. Rollback runbook
  11. Final self-assessment checklist
  12. Extension ideas

  1. How to use this lesson

Every phase follows the same cycle, the one you have been using since Module 9:

flowchart LR
    R["Phase branch"] --> C["Code"]
    C --> V["Verify locally<br/>lint + check + Molecule"]
    V --> A["Apply to the lab"]
    A --> H["Check the milestone"]
    H --> P["PR + green CI<br/>+ CHANGELOG"]
    P --> M["Merge into main"]
  • The code in this lesson is reference code: it works with the course's names and versions, but read it, understand it and adapt it before copying it. Versions marked as "example" must be replaced with the latest released ones when you do the project.
  • When a piece was already explained in a previous lesson, you will only see the reference. What is new is explained in detail.
  • If you get stuck in a phase, don't move on: the milestones exist so that problems don't pile up.

  1. Phase 1: ansible-core 2.20 and aurora-ee 2.0.0

This phase comes first (ADR-10): everything you build afterwards must be born on supported tools.

cd ~/aurora-infra
git switch main && git pull
git switch -c ansible-core-2.20

2.1. Reading the porting guides

Going from 2.17 to 2.20 means three version jumps, and each one has its own porting guide in the official Ansible documentation. Read them in order and write down whatever affects Aurora. The most relevant points:

Series Changes to review What to look for in aurora-infra
2.18 Python 3.11 or later on the control node Your laptop (Ubuntu 24.04 ships 3.12) and the EE image (it had 3.11)
2.19 Overhauled templating engine (data tagging): conditionals must evaluate to a boolean, implicit conversions disappear and some errors that used to go unnoticed now stop the run when: with bare strings or lists, {{ }} templates inside when:, filters receiving unexpected types
2.20 Python 3.12 or later on the control node; deprecation warnings for facts injected as standalone variables (ansible_distribution instead of ansible_facts['distribution']) Aurora has used ansible_facts[...] since Module 3: there should be no warnings

An example of the most common 2.19 change. A conditional like this one worked because a non-empty string was considered true:

- name: Create the automation account
  ansible.builtin.user:
    name: "{{ common_automation_user }}"
  when: common_automation_user          # a STRING: an error in 2.19+

From 2.19 on, the conditional must be explicitly boolean:

  when: common_automation_user | length > 0

Find them all before upgrading:

grep -rnE '^\s*(when|changed_when|failed_when|until):\s+[a-z_]+\s*$' roles/ playbooks/
grep -rn 'when:.*{{' roles/ playbooks/

The first grep finds conditionals that are just a variable name (check whether that variable is a boolean: if it is, there's no problem). The second one finds templates inside conditionals, which were never correct.

2.2. The control node

pipx install --force --include-deps 'ansible==13.*'
pipx inject ansible kubernetes boto3 botocore
ansible --version | head -3
  • ansible 13 is the package that corresponds to ansible-core 2.20 (the table from Lesson 1.2, extended).
  • --force reinstalls the pipx environment from scratch, so you have to inject again the libraries you added in Module 8 (kubernetes, boto3, botocore).
  • The output must show ansible [core 2.20.x] and python version = 3.12.x.

2.3. CI and EDA tools

ci/requirements.txt:

# Tools for the CI and the local environment (.venv). PINNED versions.
# Final project: ansible-core 2.20 (the tools no longer have to exclude 2.17).
ansible-core>=2.20,<2.21
yamllint==1.38.0
ansible-lint==26.11.0       # example: the latest released
ansible-compat==26.11.0     # example: the one that goes with ansible-lint
awxkit==24.6.1
molecule==26.11.0           # example
molecule-plugins==26.7.8    # example
ansible-runner==2.4.1

To find out which versions exist and which one is the latest:

python3 -m pip index versions ansible-lint | head -2

Recreate the project's virtual environments (the cleanest way to switch ansible-core series):

rm -rf .venv && python3 -m venv .venv
.venv/bin/pip install -r ci/requirements.txt pytest

rm -rf .venv-eda && python3 -m venv .venv-eda
.venv-eda/bin/pip install -r rulebooks/requirements.txt

In rulebooks/requirements.txt, change only the ansible-core line to ansible-core>=2.20,<2.21.

2.4. The collections

Review requires_ansible and the changelog of each collection (the procedure from Lesson 6.3). The case that forces a change is community.general: the 12 series was the latest compatible with 2.17, but it no longer receives fixes. With 2.20 you can use the current series:

  # ufw and timezone. Current series for ansible-core 2.20 (final project).
  - name: community.general
    version: "14.2.0"       # example: the latest 14.x released

Check a version's compatibility before pinning it:

ansible-galaxy collection install community.general:==14.2.0 -p /tmp/test-cg
grep requires_ansible /tmp/test-cg/ansible_collections/community/general/meta/runtime.yml
rm -rf /tmp/test-cg

The other collections (community.postgresql, ansible.posix, community.docker, kubernetes.core, amazon.aws, aurora_store.infra) declare a minimum requires_ansible that 2.20 satisfies, but check it anyway with the same procedure; upgrade them too if there are new versions with fixes, but one at a time and verifying, so you know which change breaks what.

ansible-galaxy collection install -r collections/requirements.yml
ansible-galaxy role install -r roles/requirements.yml --force

2.5. aurora-ee 2.0.0

ee/execution-environment.yml changes in three ways: Python 3.12, ansible-core 2.20 and OpenTofu (to provision staging from AWX in phase 5):

---
# Aurora Store execution environment.
# Build from the root of aurora-infra:
#   ansible-builder build -f ee/execution-environment.yml -c ee/context
# 2.0.0 (final project): ansible-core 2.20 with Python 3.12 and OpenTofu.
version: 3

images:
  base_image:
    name: quay.io/centos/centos:stream9

dependencies:
  python_interpreter:
    package_system: python3.12
    python_path: /usr/bin/python3.12
  ansible_core:
    package_pip: ansible-core>=2.20,<2.21
  ansible_runner:
    package_pip: ansible-runner
  galaxy: ../collections/requirements.yml
  python:
    - psycopg2-binary
  system:
    - openssh-clients [platform:rpm]
    - git-core [platform:rpm]
    - unzip [platform:rpm]

additional_build_steps:
  # The aurora_store.infra collection is installed from Git (Lesson 10.1).
  prepend_galaxy:
    - RUN /usr/bin/dnf install -y git-core
  # OpenTofu, with its checksum verified (supply chain, Lesson 9.2).
  append_final:
    - ARG TOFU_VERSION=1.10.6
    - >-
      RUN cd /tmp
      && curl -fsSLO https://github.com/opentofu/opentofu/releases/download/v${TOFU_VERSION}/tofu_${TOFU_VERSION}_linux_amd64.zip
      && curl -fsSLO https://github.com/opentofu/opentofu/releases/download/v${TOFU_VERSION}/tofu_${TOFU_VERSION}_SHA256SUMS
      && grep " tofu_${TOFU_VERSION}_linux_amd64.zip$" tofu_${TOFU_VERSION}_SHA256SUMS | sha256sum -c -
      && unzip -o tofu_${TOFU_VERSION}_linux_amd64.zip tofu -d /usr/bin
      && rm -f tofu_${TOFU_VERSION}_*
      && /usr/bin/tofu version

options:
  package_manager_path: /usr/bin/dnf
  tags:
    - registry.aurora-store.example:5000/aurora/aurora-ee:2.0.0

What's new:

  • python3.12: ansible-core 2.20 requires Python 3.12 on the control node, and inside the EE the "control node" is the container.
  • unzip in system: the OpenTofu installation needs it.
  • append_final: instructions that ansible-builder adds at the end of the image. ARG pins the OpenTofu version (1.10.6 is an example: use the latest stable one). The >- line is a YAML folded block (Lesson 3.2): it becomes a single RUN instruction chained with &&, which fails if any step fails.
  • sha256sum -c: downloads the official checksum list and verifies the file before installing it. If someone tampers with the download, the build fails.
  • /usr/bin/tofu: the same path as aurora_staging_tf_binary in playbooks/vars/aws-staging.yml (Lesson 8.5), so the playbook works the same way on the laptop and in AWX.
  • Tag 2.0.0: a major version, because the ansible-core series changes (what worked with 1.4.0 might not work).

Build it and test it locally before opening the pull request (the CI will publish it on merge, Lesson 8.3):

ansible-builder build -f ee/execution-environment.yml -c ee/context
podman run --rm registry.aurora-store.example:5000/aurora/aurora-ee:2.0.0 ansible --version
podman run --rm registry.aurora-store.example:5000/aurora/aurora-ee:2.0.0 tofu version

And in ansible-navigator.yml, image: registry.aurora-store.example:5000/aurora/aurora-ee:2.0.0.

2.6. Verifying the phase

source .venv/bin/activate
ansible-lint && yamllint --strict .
(cd roles/common && molecule test --all)
ansible-playbook playbooks/site.yml --check --diff      # changed=0 expected
ansible-navigator run playbooks/site.yml --check        # the same, inside aurora-ee 2.0.0

If ansible-lint shows new rules (new versions add rules), fix them as in Lesson 9.4. If --check shows changes, it is usually a behavior change in a collection: read about it in its changelog before accepting it.

Save the work (CHANGELOG.md under [Unreleased]: "ansible-core 2.20, community.general 14, CI tools and aurora-ee 2.0.0"), open the pull request and, after merging it, check that the CI publishes aurora-ee:2.0.0. In AWX: create the aurora-ee 2.0.0 EE and set it as the EE of the Aurora Store organization (Lesson 7.6). Keep aurora-ee 1.4.0 around for a few days: it is your rollback.

Milestone M1: green CI with 2.20, site.yml --check with no changes and a successful Aurora - Check configuration job in AWX with aurora-ee 2.0.0 (you can see it in the job details, Execution Environment field).

  1. Phase 2: PostgreSQL backups

Branch backups. You are going to create the postgresql_backup role (ADR-06): a script that takes the backups, a systemd service and timer that launch it every night, and a metric that Prometheus will watch in phase 3.

ansible-galaxy role init --init-path roles postgresql_backup
cd roles/postgresql_backup && rm -rf files tests vars/main.yml && cd ../..

3.1. Role variables

roles/postgresql_backup/defaults/main.yml:

---
# Backup directory (accessible only by postgres).
postgresql_backup_dir: /var/backups/postgresql
# Databases to back up (list of names). Must be given a value.
postgresql_backup_databases: []
# Port of the local PostgreSQL server.
postgresql_backup_port: 5432
# Days the backups are kept.
postgresql_backup_retention_days: 7
# When it runs (systemd OnCalendar format).
postgresql_backup_on_calendar: "*-*-* 02:30:00"
# node_exporter textfile collector directory; empty = no metric.
postgresql_backup_metrics_dir: ""

roles/postgresql_backup/vars/main.yml:

---
postgresql_backup_script: /usr/local/sbin/postgresql-backup
postgresql_backup_unit: postgresql-backup
  • defaults/ holds what the role's user can change; vars/ holds the internal names (Lesson 4.2).
  • postgresql_backup_on_calendar uses systemd syntax: *-*-* 02:30:00 means "every day at 02:30". You can check any expression with systemd-analyze calendar "*-*-* 02:30:00".
  • Also create meta/argument_specs.yml with the six options (types path, list with elements: str, int, int, str, str) as you did in Lesson 4.6, and a meta/main.yml with the same authorship data as the other roles and dependencies: [] (the role needs PostgreSQL installed, but it doesn't depend on the postgresql role: that way it also works with a PostgreSQL installed some other way; note this in its README.md).

3.2. The backup script

roles/postgresql_backup/templates/postgresql-backup.sh.j2:

#!/bin/bash
# {{ ansible_managed }}
# Logical PostgreSQL backup (postgresql_backup role).
set -euo pipefail
umask 077

DIR="{{ postgresql_backup_dir }}"
DATE="$(date +%Y%m%d-%H%M%S)"
PORT="{{ postgresql_backup_port }}"
METRICS="{{ postgresql_backup_metrics_dir }}"

cd /

# 1. Cluster roles, passwords and privileges (they are not included in pg_dump).
runuser -u postgres -- pg_dumpall --port="$PORT" --globals-only > "$DIR/globals-$DATE.sql.partial"
mv "$DIR/globals-$DATE.sql.partial" "$DIR/globals-$DATE.sql"

# 2. One custom-format backup per database.
for DB in {{ postgresql_backup_databases | map('quote') | join(' ') }}; do
  runuser -u postgres -- pg_dump --port="$PORT" --format=custom \
    --file="$DIR/$DB-$DATE.dump.partial" "$DB"
  mv "$DIR/$DB-$DATE.dump.partial" "$DIR/$DB-$DATE.dump"
done

# 3. Retention: delete old backups and leftovers from failed runs.
find "$DIR" -maxdepth 1 -type f \( -name '*.dump' -o -name '*.sql' \) \
  -mtime +{{ postgresql_backup_retention_days }} -delete
find "$DIR" -maxdepth 1 -type f -name '*.partial' -mmin +60 -delete

# 4. Metric for Prometheus (only if everything above went well).
if [ -n "$METRICS" ] && [ -d "$METRICS" ]; then
  TMP="$(mktemp "$METRICS/.postgresql_backup.XXXXXX")"
  {
    echo '# HELP aurora_postgresql_backup_last_success_timestamp_seconds Time of the last successful backup.'
    echo '# TYPE aurora_postgresql_backup_last_success_timestamp_seconds gauge'
    echo "aurora_postgresql_backup_last_success_timestamp_seconds $(date +%s)"
  } > "$TMP"
  chmod 0644 "$TMP"
  mv "$TMP" "$METRICS/postgresql_backup.prom"
fi

Step by step:

  • set -euo pipefail: the script stops on any error (-e), undefined variable (-u) or failure inside a pipe (pipefail). This is what ensures the metric in step 4 is updated only if the backup went well.
  • umask 077: the files the script creates can only be read by their owner. A database backup contains all of the store's data and the password hashes.
  • runuser -u postgres --: the service runs as root (it needs to write the metric), but the backups are taken as postgres, which authenticates through peer on the local socket (the local all postgres peer rule in pg_hba.conf.j2, Lesson 5.2). No passwords in the script.
  • pg_dumpall --globals-only: backs up the roles (aurora, aurora_reporting, with their encrypted passwords) and the global privileges. Without this, restoring on a new server would fail because the database owners wouldn't exist.
  • pg_dump --format=custom: a compressed format that pg_restore can restore in full or in part (a single table, for example).
  • .partial + mv: the file only gets its final name once it is complete. A half-finished backup (full disk, power cut) never looks valid.
  • map('quote') (Lesson 5.3): quotes each name for the shell. With Aurora's names it wouldn't be necessary, but a role must not trust its inputs.
  • Retention with find -mtime: deletes whatever is more than N days old. Notice that it only deletes in $DIR (-maxdepth 1) and only files with the script's extensions.
  • The metric is written to a temporary file in the same directory and then renamed: node_exporter never reads a half-written file. If the directory doesn't exist (an environment without monitoring), it simply isn't written.

3.3. Service, timer and tasks

roles/postgresql_backup/templates/backup.service.j2:

# {{ ansible_managed }}
[Unit]
Description=Backup of the PostgreSQL databases
After=postgresql.service

[Service]
Type=oneshot
ExecStart={{ postgresql_backup_script }}
Nice=10
IOSchedulingClass=idle

roles/postgresql_backup/templates/backup.timer.j2:

# {{ ansible_managed }}
[Unit]
Description=Schedule for the PostgreSQL backup

[Timer]
OnCalendar={{ postgresql_backup_on_calendar }}
RandomizedDelaySec=15min
Persistent=true

[Install]
WantedBy=timers.target
  • Type=oneshot: the service runs the script and exits; it isn't a daemon.
  • Nice and IOSchedulingClass=idle: the backup yields CPU and disk to PostgreSQL, which keeps serving the store.
  • Persistent=true: if the server was off at 02:30, the backup runs at boot. RandomizedDelaySec spreads out the start time if some day you have many database servers.
  • Why a timer on the server and not an AWX schedule? Because the backup must not depend on the platform (ADR-06): if awx1 goes down, the backups keep running.

roles/postgresql_backup/tasks/main.yml:

---
- name: Check the role parameters
  ansible.builtin.assert:
    that:
      - postgresql_backup_databases | length > 0
      - postgresql_backup_retention_days | int >= 1
    fail_msg: >-
      postgresql_backup_databases cannot be empty and postgresql_backup_retention_days
      must be 1 or more (current value: {{ postgresql_backup_retention_days }}).
    quiet: true
  tags: always

- name: PostgreSQL backups
  tags: [config, backup]
  block:
    - name: Create the backup directory
      ansible.builtin.file:
        path: "{{ postgresql_backup_dir }}"
        state: directory
        owner: postgres
        group: postgres
        mode: "0700"

    - name: Publish the backup script
      ansible.builtin.template:
        src: postgresql-backup.sh.j2
        dest: "{{ postgresql_backup_script }}"
        owner: root
        group: root
        mode: "0755"

    - name: Publish the backup service and timer
      ansible.builtin.template:
        src: "{{ item.src }}"
        dest: "/etc/systemd/system/{{ item.dest }}"
        owner: root
        group: root
        mode: "0644"
      loop:
        - src: backup.service.j2
          dest: "{{ postgresql_backup_unit }}.service"
        - src: backup.timer.j2
          dest: "{{ postgresql_backup_unit }}.timer"
      loop_control:
        label: "{{ item.dest }}"
      notify: Restart the backup timer

    - name: Enable the backup timer
      ansible.builtin.systemd_service:
        name: "{{ postgresql_backup_unit }}.timer"
        enabled: true
        state: started
        daemon_reload: true

roles/postgresql_backup/handlers/main.yml:

---
- name: Restart the backup timer
  ansible.builtin.systemd_service:
    name: "{{ postgresql_backup_unit }}.timer"
    state: restarted
    daemon_reload: true
  • The new functional tag backup is added to config (the convention from Lesson 5.6): --tags backup applies only the backups.
  • daemon_reload: true in the enabling task: the first time, systemd doesn't know about the unit until it re-reads its configuration.
  • The handler restarts the timer when the units change, so that a new time in postgresql_backup_on_calendar takes effect right away.

3.4. Wiring the role into Aurora

playbooks/group_vars/dbservers.yml (common wiring, the rule from Lesson 9.1), at the end:

# Backups (postgresql_backup role, final project).
# postgresql_backup_dir repeats the role's default value because
# playbooks/test-restore.yml also reads it, and a role's defaults are not visible outside it.
postgresql_backup_dir: /var/backups/postgresql
postgresql_backup_databases: "{{ postgresql_databases | map(attribute='name') | list }}"
postgresql_backup_port: "{{ postgresql_port }}"
postgresql_backup_metrics_dir: "{{ node_exporter_textfile_dir }}"

Retention is an environment setting: in inventories/lab/group_vars/dbservers.yml, postgresql_backup_retention_days: 3; in staging, 1; in production, 14. (You will define node_exporter_textfile_dir in phase 3; until then, add it now to playbooks/group_vars/all/monitoring.yml with the value /var/lib/node_exporter.)

In playbooks/dbservers.yml, the list of roles becomes:

  roles:
    - postgresql
    - postgresql_backup

Apply it and launch a backup without waiting for the night:

ansible-playbook playbooks/site.yml --limit db1 --tags backup
ssh db1 sudo systemctl start postgresql-backup.service
ssh db1 sudo ls -l /var/backups/postgresql
ssh db1 systemctl list-timers postgresql-backup.timer

You will see globals-<date>.sql, aurora-<date>.dump and aurora_analytics-<date>.dump, and the timer's next run. If something fails, ssh db1 sudo journalctl -u postgresql-backup.service shows the script's output.

3.5. An untested backup is not a backup

playbooks/test-restore.yml:

---
# Restore test (final project): restores the latest backup of the store database
# into a temporary database and compares it with the original.
#   ansible-playbook playbooks/test-restore.yml
- name: Test restoring the latest Aurora Store backup
  hosts: dbservers
  become: true
  gather_facts: false
  vars:
    aurora_restore_db: aurora_restore
    aurora_restore_max_hours: 26

  tasks:
    - name: Find the backups of the store database
      ansible.builtin.find:
        paths: "{{ postgresql_backup_dir }}"
        patterns: "{{ aurora_db_name }}-*.dump"
      register: aurora_backups

    - name: Check that there are backups
      ansible.builtin.assert:
        that: aurora_backups.matched > 0
        fail_msg: "There is no backup of {{ aurora_db_name }} in {{ postgresql_backup_dir }}"
        quiet: true

    - name: Choose the most recent backup
      ansible.builtin.set_fact:
        aurora_backup: "{{ aurora_backups.files | sort(attribute='mtime') | last }}"

    - name: Check that the backup is recent
      ansible.builtin.assert:
        that: (now().timestamp() - aurora_backup.mtime) < aurora_restore_max_hours * 3600
        fail_msg: "The most recent backup ({{ aurora_backup.path }}) is more than {{ aurora_restore_max_hours }} hours old"
        quiet: true

    - name: Restore and compare in a temporary database
      become_user: postgres
      block:
        - name: Create the temporary database
          community.postgresql.postgresql_db:
            name: "{{ aurora_restore_db }}"
            port: "{{ postgresql_port }}"
            state: present

        - name: Restore the backup into the temporary database
          ansible.builtin.command:
            argv:
              - pg_restore
              - "--port={{ postgresql_port }}"
              - "--dbname={{ aurora_restore_db }}"
              - --no-owner
              - --exit-on-error
              - "{{ aurora_backup.path }}"
          changed_when: true

        - name: Count the tables of the original and the restored database
          community.postgresql.postgresql_query:
            db: "{{ item }}"
            port: "{{ postgresql_port }}"
            query: >-
              SELECT count(*) AS tables FROM information_schema.tables
              WHERE table_schema = 'public'
          loop:
            - "{{ aurora_db_name }}"
            - "{{ aurora_restore_db }}"
          register: aurora_restore_count

        - name: Check that the restore is complete
          ansible.builtin.assert:
            that: >-
              aurora_restore_count.results[0].query_result[0].tables ==
              aurora_restore_count.results[1].query_result[0].tables
            success_msg: "Backup {{ aurora_backup.path | basename }} restored successfully"

      always:
        - name: Delete the temporary database
          community.postgresql.postgresql_db:
            name: "{{ aurora_restore_db }}"
            port: "{{ postgresql_port }}"
            state: absent
  • become: true on the play and become_user: postgres on the block: the database operations are performed as postgres, which authenticates without a password through the local socket. Since become is inherited from the play, ansible-lint doesn't complain about partial-become (Lesson 9.4).
  • sort(attribute='mtime') | last: find returns the files with their modification time (seconds since 1970); the last one after sorting is the most recent.
  • now().timestamp(): the current time in the same format, to compute the age of the backup.
  • --no-owner: restores without trying to assign owners (the temporary database belongs to postgres). --exit-on-error: fails at the first error, instead of carrying on and leaving an incomplete restore.
  • The table count is a minimal check. Aurora's database has no tables yet (the website is static), so you will be comparing 0 with 0; in a real store you would compare the row counts of key tables (orders, customers) with some tolerance.
  • always: the temporary database is deleted no matter what (Lesson 5.5).
ansible-playbook playbooks/test-restore.yml

Save the work: README.md (a "Backups" section: what is backed up, where, when, how to restore) and CHANGELOG.md; pull request and merge. In AWX, create the Aurora - Test restore template (playbook playbooks/test-restore.yml, inventory Aurora - Lab, the lab SSH and Vault credentials) with a weekly schedule (for example, Mondays at 07:00).

Milestone M2: a nightly backup created by the timer (check it the next day with ls) and a successful restore test in AWX.

  1. Phase 3: monitoring with Prometheus and Alertmanager

Branch monitoring. You will set up mon1, open node_exporter to Prometheus, add the catalog API health metric and create the aurora_monitoring role (ADR-02, ADR-03, ADR-04).

4.1. The mon1 server

In lab/Vagrantfile, add to MACHINES, before awx1:

  "mon1" => { ip: "192.168.56.51", memory: 2048, cpus: 2 },
cd lab && vagrant up mon1 && vagrant snapshot save mon1 clean && cd ..
ssh-keyscan -t ed25519 192.168.56.51 >> ssh/known_hosts.lab
(cd lab && vagrant ssh mon1 -c 'ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub')
ssh-keygen -lf ssh/known_hosts.lab | grep 192.168.56.51
  • Compare the two fingerprints before trusting the key (the procedure from Lesson 9.2).
  • In ~/.ssh/config, add mon1 to the common line (Host lb1 web1 web2 db1 api1 mon1 awx1 192.168.56.*) and its own Host mon1 / HostName 192.168.56.51 block.
  • With mon1, the lab adds up to about 14 GB of RAM. If your computer can't cope, shut down api1 while you work on the phases that don't use it.

In inventories/lab/hosts.yml, inside aurora, after apiservers:

        monitorservers:
          hosts:
            mon1:
              ansible_host: 192.168.56.51

In inventories/production/hosts.yml, prod-mon1 with ansible_host: 10.20.1.51; in inventories/staging/hosts.yml, the empty monitorservers: group (the convention from Lesson 9.1: the same groups in every environment). Environment data in inventories/lab/group_vars/monitorservers.yml:

---
# lab environment data for the monitoring servers (final project).
docker_insecure_registries:
  - registry.aurora-store.example:5000
aurora_monitoring_awx_url: http://192.168.56.30:30080
# Enabled in phase 4.
aurora_monitoring_eda_enabled: false

4.2. node_exporter, open only to Prometheus

playbooks/group_vars/all/monitoring.yml ends up like this:

---
# Metrics agent (geerlingguy.node_exporter role, Lesson 6.2; final project).
node_exporter_version: "1.13.1"
node_exporter_port: 9100
# If the environment has a monitoring server, the agent listens on the internal IP
# (only Prometheus can reach it, see monitoring.yml); otherwise, only locally.
node_exporter_host: "{{ aurora_internal_ip if groups['monitorservers'] | length > 0 else '127.0.0.1' }}"
# Textfile collector: metrics written by local scripts (backups, API health).
node_exporter_textfile_dir: /var/lib/node_exporter
node_exporter_enabled_collectors:
  - systemd
  - textfile:
      directory: "{{ node_exporter_textfile_dir }}"

# Prometheus internal IP (empty if the environment has no monitoring server).
aurora_prometheus_ip: >-
  {{ hostvars[groups['monitorservers'][0]]['aurora_internal_ip']
     if groups['monitorservers'] | length > 0 else '' }}
  • node_exporter_host uses an inline Jinja if: in lab and production (with mon1/prod-mon1), the internal IP; in staging, which has no monitoring, it stays on 127.0.0.1.
  • node_exporter_enabled_collectors: the collectors the role enables in addition to the default ones. The textfile collector reads the .prom files in the given directory; it is the one the backups and the API will use (ADR-03). Check in galaxy_roles/geerlingguy.node_exporter/defaults/main.yml the exact format your version of the role expects, and in its tasks/config.yml whether it creates the directory (2.2.0 does when the collector is enabled).

In playbooks/monitoring.yml, add to post_tasks, before the existing check:

    - name: Allow Prometheus to read the metrics agent
      community.general.ufw:
        rule: allow
        from_ip: "{{ aurora_prometheus_ip }}"
        to_port: "{{ node_exporter_port | string }}"
        proto: tcp
        comment: Aurora Store Prometheus
      when: aurora_prometheus_ip | length > 0
      tags: monitoring

The existing check ("Check that the agent publishes the server metrics") still works because it queries node_exporter_host, which is now the internal IP. Remember what ADR-04 noted: on db1, api1 and mon1, ufw is not active, so the rule is saved but doesn't filter.

4.3. The catalog API health metric

The API only listens on 127.0.0.1:8080 (Lesson 9.2). A timer on api1 will query it every 30 seconds and write aurora_catalog_up (1 or 0) for the textfile collector. This is the responsibility of the role that deploys the API, aurora_catalog, and it will be optional: in roles/aurora_catalog/defaults/main.yml:

# node_exporter textfile collector directory; empty = no health metric.
aurora_catalog_metrics_dir: ""

(Add it to meta/argument_specs.yml too, type: str.) Template roles/aurora_catalog/templates/aurora-catalog-health.sh.j2:

#!/bin/sh
# {{ ansible_managed }}
# Publishes aurora_catalog_up (1 = the API responds on /health) for node_exporter.
set -u
if curl -fsS --max-time 5 "http://127.0.0.1:{{ aurora_catalog_port }}/health" > /dev/null; then
  VALUE=1
else
  VALUE=0
fi
TMP="$(mktemp "{{ aurora_catalog_metrics_dir }}/.aurora_catalog.XXXXXX")"
{
  echo '# HELP aurora_catalog_up 1 if the catalog API responds on /health.'
  echo '# TYPE aurora_catalog_up gauge'
  echo "aurora_catalog_up $VALUE"
} > "$TMP"
chmod 0644 "$TMP"
mv "$TMP" "{{ aurora_catalog_metrics_dir }}/aurora_catalog.prom"

And the units aurora-catalog-health.service.j2 (just like the backup service, with Type=oneshot and ExecStart=/usr/local/sbin/aurora-catalog-health) and aurora-catalog-health.timer.j2:

# {{ ansible_managed }}
[Unit]
Description=Periodic check of the catalog API

[Timer]
OnBootSec=1min
OnUnitActiveSec=30s
AccuracySec=5s

[Install]
WantedBy=timers.target
  • set -u without -e: here a curl failure must not stop the script, because that is exactly what needs to be measured.
  • OnUnitActiveSec=30s: it runs 30 seconds after each previous run; AccuracySec prevents systemd from grouping runs within a one-minute margin (its default value).

At the end of roles/aurora_catalog/tasks/main.yml, a block with the same four tasks as in the backup role (script in /usr/local/sbin/aurora-catalog-health with mode: "0755", the two units with notify, enabling the timer with daemon_reload: true), with:

- name: API health metric
  when: aurora_catalog_metrics_dir | length > 0
  tags: [deploy, config, monitoring]
  block:
    # ... the four tasks ...

and a new roles/aurora_catalog/handlers/main.yml with "Restart the API health timer" (state: restarted, daemon_reload: true). The wiring, in playbooks/group_vars/apiservers.yml:

aurora_catalog_metrics_dir: "{{ node_exporter_textfile_dir }}"

4.4. The aurora_monitoring role

ansible-galaxy role init --init-path roles aurora_monitoring
cd roles/aurora_monitoring && rm -rf files tests vars && cd ../..

roles/aurora_monitoring/defaults/main.yml:

---
aurora_monitoring_dir: /opt/aurora-monitoring
aurora_monitoring_env: lab
# Images (example versions: pin the latest stable ones).
aurora_monitoring_prometheus_image: docker.io/prom/prometheus:v3.5.0
aurora_monitoring_alertmanager_image: docker.io/prom/alertmanager:v0.28.1
aurora_monitoring_retention: 15d
# Servers to watch: dictionary {inventory name: IP}.
aurora_monitoring_targets: {}
aurora_monitoring_node_exporter_port: 9100
# Old backup alert.
aurora_monitoring_backup_max_age_hours: 26
# Event-Driven Ansible (phase 4).
aurora_monitoring_eda_enabled: false
aurora_monitoring_de_image: ""
aurora_monitoring_urls: []
aurora_monitoring_url_check_delay: 30
aurora_monitoring_awx_url: ""
aurora_monitoring_awx_token: ""
aurora_monitoring_awx_organization: Aurora Store
aurora_monitoring_jt_remediate_web: Aurora - Remediate web
aurora_monitoring_jt_remediate_catalog: Aurora - Remediate catalog

roles/aurora_monitoring/meta/main.yml carries the usual authorship data and dependencies: [{role: docker}] (like aurora_catalog, Lesson 8.1). Create its meta/argument_specs.yml with these options; the important ones are aurora_monitoring_targets (type: dict) and aurora_monitoring_awx_token (type: str, with no_log: true in the specification).

The Prometheus configuration

roles/aurora_monitoring/templates/prometheus.yml.j2:

# {{ ansible_managed }}
global:
  scrape_interval: 15s
  evaluation_interval: 15s
  external_labels:
    environment: {{ aurora_monitoring_env }}

rule_files:
  - /etc/prometheus/rules.yml

alerting:
  alertmanagers:
    - static_configs:
        - targets: ["alertmanager:9093"]

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]

  - job_name: node
    static_configs:
{% for name, address in aurora_monitoring_targets.items() | sort %}
      - targets: ["{{ address }}:{{ aurora_monitoring_node_exporter_port }}"]
        labels:
          instance: {{ name }}
{% endfor %}
  • scrape_interval: 15s: every 15 seconds Prometheus requests /metrics from each agent (a scrape). evaluation_interval: how often it evaluates the alerting rules.
  • alertmanager:9093: the service name in Docker Compose; containers in the same project find each other by name.
  • labels: instance: {{ name }}: by default Prometheus sets instance="192.168.56.41:9100". By setting it in the target configuration, the label becomes the inventory name (api1), which is what remediate-catalog.yml expects (Lesson 10.5). This is the contract between monitoring and Ansible.
  • .items() | sort: iterates over the dictionary in alphabetical order. Without sort, the order could vary and the template would change for no reason (a false changed on every run).

The alerting rules

roles/aurora_monitoring/templates/rules.yml.j2:

# {{ ansible_managed }}
groups:
  - name: aurora
    rules:
{% raw %}
      - alert: AuroraServerDown
        expr: up{job="node"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "The metrics agent on {{ $labels.instance }} is not responding"

      - alert: AuroraCatalogDown
        expr: aurora_catalog_up == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "The catalog API on {{ $labels.instance }} is not responding"

      - alert: AuroraDiskAlmostFull
        expr: >-
          node_filesystem_avail_bytes{mountpoint="/"}
          / node_filesystem_size_bytes{mountpoint="/"} < 0.15
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Less than 15% of disk space left on {{ $labels.instance }}"
{% endraw %}

      - alert: AuroraBackupTooOld
        expr: >-
          time() - aurora_postgresql_backup_last_success_timestamp_seconds
          > {{ aurora_monitoring_backup_max_age_hours * 3600 }}
        for: 30m
        labels:
          severity: warning
        annotations:
          summary: "{% raw %}The last successful backup on {{ $labels.instance }}{% endraw %} is more than {{ aurora_monitoring_backup_max_age_hours }} hours old"

Here a problem you saw in Lesson 5.2 shows up: Prometheus uses the same {{ }} syntax as Jinja in its annotations ({{ $labels.instance }}). If Ansible saw it, it would try to resolve it and fail. {% raw %}...{% endraw %} tells Jinja to copy that text as is. Look at the last rule: it mixes raw text (for Prometheus) and an Ansible variable (aurora_monitoring_backup_max_age_hours), which is why the raw block is closed and opened within the same line.

The rules:

Alert Expression Meaning
AuroraServerDown up == 0 for 2 min Prometheus can't read the agent (server off, network, agent stopped)
AuroraCatalogDown aurora_catalog_up == 0 for 1 min The API doesn't respond on /health (EDA remediates it)
AuroraDiskAlmostFull Less than 15% free on / for 10 min A warning to act before something breaks
AuroraBackupTooOld The last successful backup is more than 26 h old RPO at risk (NFR-A4)

for: is how long the condition must hold before the alert goes from pending to firing. It avoids alerts caused by a one-second glitch.

Alertmanager

roles/aurora_monitoring/templates/alertmanager.yml.j2:

# {{ ansible_managed }}
route:
  receiver: {{ 'eda' if aurora_monitoring_eda_enabled else 'nobody' }}
  group_by: [alertname, instance]
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h

receivers:
  - name: nobody
{% if aurora_monitoring_eda_enabled %}
  - name: eda
    webhook_configs:
      - url: http://eda:5050/
        send_resolved: true
{% endif %}
  • route: who the alerts are sent to. With EDA disabled (this phase), to the nobody receiver (you see them in the UI, but they don't go anywhere); in phase 4, to eda.
  • group_by: groups alerts with the same name and instance into one notification. group_wait: waits 30 s to group the ones that arrive together. repeat_interval: if it is still active, it is resent every 4 h.
  • http://eda:5050/: the eda service in the same Compose project, over the internal network. Port 5050 is not published on mon1: only Alertmanager can reach it (P05, ADR-05).

Docker Compose

roles/aurora_monitoring/templates/compose.yaml.j2:

# {{ ansible_managed }}
name: aurora-monitoring

services:
  prometheus:
    image: "{{ aurora_monitoring_prometheus_image }}"
    command:
      - --config.file=/etc/prometheus/prometheus.yml
      - --storage.tsdb.path=/prometheus
      - --storage.tsdb.retention.time={{ aurora_monitoring_retention }}
      - --web.enable-lifecycle
    ports:
      - "127.0.0.1:9090:9090"
    volumes:
      - ./prometheus:/etc/prometheus:ro
      - prometheus-data:/prometheus
    restart: unless-stopped

  alertmanager:
    image: "{{ aurora_monitoring_alertmanager_image }}"
    command:
      - --config.file=/etc/alertmanager/alertmanager.yml
      - --storage.path=/alertmanager
    ports:
      - "127.0.0.1:9093:9093"
    volumes:
      - ./alertmanager:/etc/alertmanager:ro
      - alertmanager-data:/alertmanager
    restart: unless-stopped
{% if aurora_monitoring_eda_enabled %}

  eda:
    image: "{{ aurora_monitoring_de_image }}"
    command: ["ansible-rulebook", "--rulebook", "/rulebooks/aurora.yml", "--verbose"]
    env_file:
      - ./eda.env
    volumes:
      - ./rulebooks:/rulebooks:ro
    restart: unless-stopped
{% endif %}

volumes:
  prometheus-data:
  alertmanager-data:
  • Ports on 127.0.0.1: the Prometheus and Alertmanager UIs are only reachable from mon1 (and from your laptop through an SSH tunnel, section 4.6). They have no authentication of their own: publishing them would be a risk (NFR-S3).
  • Directories are mounted, not files (./prometheus:/etc/prometheus:ro): the template module replaces files atomically (with a new file), and a single-file mount would keep seeing the old one. It's the same thing you did with data/ in Lesson 8.1.
  • --web.enable-lifecycle: allows reloading the configuration with a POST /-/reload request, which the handlers will use.
  • Named volumes for the data: they survive the recreation of the containers.

Tasks and handlers

roles/aurora_monitoring/tasks/main.yml:

---
- name: Check the role parameters
  ansible.builtin.assert:
    that: >-
      not aurora_monitoring_eda_enabled or (
        aurora_monitoring_de_image | length > 0 and
        aurora_monitoring_awx_url | length > 0 and
        aurora_monitoring_awx_token | length > 0)
    fail_msg: "With EDA enabled, the decision environment image, the AWX URL and the token are required"
    quiet: true
  tags: always

- name: Aurora Store monitoring
  tags: [config, monitoring]
  block:
    - name: Create the monitoring directories
      ansible.builtin.file:
        path: "{{ aurora_monitoring_dir }}/{{ item }}"
        state: directory
        owner: root
        group: root
        mode: "0755"
      loop: ["", prometheus, alertmanager, rulebooks]

    - name: Publish the Prometheus configuration
      ansible.builtin.template:
        src: prometheus.yml.j2
        dest: "{{ aurora_monitoring_dir }}/prometheus/prometheus.yml"
        mode: "0644"
      notify: Reload Prometheus

    - name: Publish the alerting rules
      ansible.builtin.template:
        src: rules.yml.j2
        dest: "{{ aurora_monitoring_dir }}/prometheus/rules.yml"
        mode: "0644"
        validate: >-
          docker run --rm --user 0 --entrypoint promtool -v %s:/tmp/rules.yml:ro
          {{ aurora_monitoring_prometheus_image }} check rules /tmp/rules.yml
      notify: Reload Prometheus

    - name: Publish the Alertmanager configuration
      ansible.builtin.template:
        src: alertmanager.yml.j2
        dest: "{{ aurora_monitoring_dir }}/alertmanager/alertmanager.yml"
        mode: "0644"
        validate: >-
          docker run --rm --user 0 --entrypoint amtool -v %s:/tmp/alertmanager.yml:ro
          {{ aurora_monitoring_alertmanager_image }} check-config /tmp/alertmanager.yml
      notify: Reload Alertmanager

    - name: Publish the Event-Driven Ansible rulebook
      ansible.builtin.template:
        src: rulebook.yml.j2
        dest: "{{ aurora_monitoring_dir }}/rulebooks/aurora.yml"
        mode: "0644"
      when: aurora_monitoring_eda_enabled
      notify: Restart EDA

    - name: Publish the EDA credentials for AWX
      ansible.builtin.template:
        src: eda.env.j2
        dest: "{{ aurora_monitoring_dir }}/eda.env"
        mode: "0600"
      when: aurora_monitoring_eda_enabled
      diff: false
      notify: Restart EDA

    - name: Publish the Docker Compose definition
      ansible.builtin.template:
        src: compose.yaml.j2
        dest: "{{ aurora_monitoring_dir }}/compose.yaml"
        mode: "0644"

    - name: Deploy the monitoring with Docker Compose
      community.docker.docker_compose_v2:
        project_src: "{{ aurora_monitoring_dir }}"
        state: present
        pull: missing
        remove_orphans: true
        wait: true
        wait_timeout: 120

roles/aurora_monitoring/handlers/main.yml:

---
- name: Reload Prometheus
  ansible.builtin.uri:
    url: http://127.0.0.1:9090/-/reload
    method: POST

- name: Reload Alertmanager
  ansible.builtin.uri:
    url: http://127.0.0.1:9093/-/reload
    method: POST

- name: Restart EDA
  community.docker.docker_compose_v2:
    project_src: "{{ aurora_monitoring_dir }}"
    services:
      - eda
    state: restarted
  • validate with promtool and amtool: the checking tools that ship inside the images themselves. Ansible writes the template to a temporary file (%s), mounts it in a throwaway container and only installs it if it is valid (Lesson 5.2). --user 0 because only root can read the temporary file. The main Prometheus configuration isn't validated this way because promtool check config would also look for rules.yml next to the temporary file; if it is wrong, the reload returns an error, the handler fails and Prometheus keeps the previous configuration.
  • Reload instead of restart: Prometheus and Alertmanager re-read their configuration without losing data or active alerts.
  • diff: false on eda.env: it contains the AWX token; it must not show up in --diff (Lesson 5.4).
  • remove_orphans: true: if you disable EDA, the eda container goes away.

4.5. The monitorservers.yml playbook

playbooks/group_vars/monitorservers.yml (common wiring):

---
# Wiring for the monitoring servers (final project).
aurora_monitoring_env: "{{ aurora_env }}"
aurora_monitoring_targets: >-
  {{ dict(groups['aurora'] | zip(groups['aurora'] | map('extract', hostvars, 'aurora_internal_ip'))) }}
aurora_monitoring_node_exporter_port: "{{ node_exporter_port }}"
aurora_monitoring_urls: >-
  {{ groups['webservers'] | map('extract', hostvars, 'aurora_internal_ip')
     | map('regex_replace', '^(.*)$', 'http://\\1/') | list }}
aurora_monitoring_de_image: registry.aurora-store.example:5000/aurora/aurora-de:1.0.0
aurora_monitoring_awx_token: "{{ vault_aurora_eda_awx_token | default('') }}"
  • aurora_monitoring_targets: the dict(... | zip(...)) technique from Lesson 5.3, now with aurora_internal_ip: {lb1: 192.168.56.10, web1: 192.168.56.11, ...}. It includes mon1 (it watches itself).
  • aurora_monitoring_urls: the website URLs for url_check, built from the inventory instead of written by hand as in watch-store.yml.
  • default('') on the token: in this phase it doesn't exist in the vault yet.

playbooks/monitorservers.yml:

---
# Monitoring servers: Prometheus, Alertmanager and Event-Driven Ansible (final project).
- name: Configure the Aurora Store monitoring servers
  hosts: monitorservers
  become: true
  gather_subset:
    - min

  pre_tasks:
    # The same task as in apiservers.yml: the lab image registry.
    - name: Resolve the lab internal names
      ansible.builtin.lineinfile:
        path: /etc/hosts
        line: "192.168.56.30 git.aurora-store.example registry.aurora-store.example"
      tags: always

  roles:
    - docker
    - aurora_monitoring

  post_tasks:
    - name: Wait for Prometheus to be ready
      ansible.builtin.uri:
        url: http://127.0.0.1:9090/-/ready
      register: aurora_prometheus_ready
      until: aurora_prometheus_ready.status == 200
      retries: 10
      delay: 3
      check_mode: false
      tags: always

    - name: Wait for Prometheus to scrape all the metrics agents
      ansible.builtin.uri:
        url: http://127.0.0.1:9090/api/v1/targets?state=active
      register: aurora_prometheus_targets
      until: >-
        aurora_prometheus_targets.json.data.activeTargets
        | selectattr('labels.job', 'equalto', 'node')
        | rejectattr('health', 'equalto', 'up')
        | list | length == 0
      retries: 10
      delay: 6
      check_mode: false
      tags: always
  • The Prometheus API (/api/v1/targets) returns in JSON each target with its health (up, down or unknown before the first scrape). The until condition filters the node job targets that are not up; when the list is empty, they all work.
  • retries/delay: after a new deployment, the targets start as unknown; it waits for up to a minute.

In playbooks/site.yml, add at the end - name: Monitoring and events / import_playbook: monitorservers.yml and update the comment header. It goes after monitoring.yml on purpose: Prometheus checks that the agents respond on their internal IP, and that is only true once monitoring.yml has changed them.

4.6. Verifying the phase

ansible-playbook playbooks/site.yml --check --diff      # review the expected changes
ansible-playbook playbooks/site.yml
curl -s --max-time 3 http://192.168.56.11:9100/metrics | head -1 || echo "Blocked (correct)"
ssh mon1 curl -s http://192.168.56.11:9100/metrics | head -1

From your laptop, port 9100 on web1 doesn't respond (ufw blocks it); from mon1, it does (criterion AC-06). To see the UIs, open an SSH tunnel:

ssh -N -L 9090:127.0.0.1:9090 -L 9093:127.0.0.1:9093 mon1

With the tunnel open, http://localhost:9090/targets shows the six servers UP with their inventory names, and http://localhost:9090/alerts the four rules. Try a real alert:

ssh api1 sudo docker stop aurora-catalog-catalog-1
# Wait ~1.5 minutes: AuroraCatalogDown goes from pending to firing (http://localhost:9093)
ssh api1 sudo docker start aurora-catalog-catalog-1

Save the work (README.md: a "Monitoring" section, with the SSH tunnel and the alerts; CHANGELOG.md; docs/adr/ if any decision changed), pull request and merge.

Milestone M3: all targets up in Prometheus and the AuroraCatalogDown alert visible in Alertmanager.

  1. Phase 4: from alerts to AWX with Event-Driven Ansible

Branch awx-events. In Lesson 10.5, ansible-rulebook ran in your terminal and executed playbooks with your keys. Now it will run on mon1, inside a container, and launch AWX templates (ADR-05).

5.1. The aurora-de decision environment

eda/decision-environment.yml:

---
# Aurora Store decision environment: ansible-rulebook and the ansible.eda collection.
# Build from the root of aurora-infra:
#   ansible-builder build -f eda/decision-environment.yml -c eda/context
version: 3

images:
  base_image:
    name: quay.io/centos/centos:stream9

dependencies:
  python_interpreter:
    package_system: python3.12
    python_path: /usr/bin/python3.12
  ansible_core:
    package_pip: ansible-core>=2.20,<2.21
  ansible_runner:
    package_pip: ansible-runner
  galaxy: ../rulebooks/requirements.yml
  python:
    - ansible-rulebook==1.1.7      # example: the same as in rulebooks/requirements.txt
    - aiohttp
  system:
    - java-17-openjdk-headless [platform:rpm]

additional_build_steps:
  append_final:
    - ENV JAVA_HOME=/usr/lib/jvm/jre-17-openjdk

options:
  package_manager_path: /usr/bin/dnf
  tags:
    - registry.aurora-store.example:5000/aurora/aurora-de:1.0.0

It's the same tool and the same format as the EE (Lesson 7.6), with different content: ansible-rulebook needs Java (its rules engine, Lesson 10.5) and the ansible.eda collection (event sources), which you already declared in rulebooks/requirements.yml. Add /eda/context/ to .gitignore. Build it, test it and publish it:

ansible-builder build -f eda/decision-environment.yml -c eda/context
podman run --rm registry.aurora-store.example:5000/aurora/aurora-de:1.0.0 ansible-rulebook --version
podman push registry.aurora-store.example:5000/aurora/aurora-de:1.0.0

So that the CI builds it from now on, copy .gitea/workflows/ee.yml as .gitea/workflows/de.yml, changing the paths that trigger it (eda/** and rulebooks/requirements.yml) and the definition file.

5.2. The remediation templates in AWX

First, an adjustment in playbooks/remediate-web.yml. The task that picks the host compares the event URL with ansible_host; the URLs that mon1 will watch use the internal IP (section 4.5), so the correct comparison is:

    - name: Skip the unaffected web servers
      ansible.builtin.meta: end_host
      when: (aurora_eda_url | urlsplit('hostname')) != aurora_internal_ip

In the lab both IPs are the same, but in an environment with a public and a private network they aren't. remediate-catalog.yml doesn't change: it already compares with the inventory name.

And a detail that means the playbooks need no further changes: they define aurora_eda_url (and aurora_eda_instance) in vars: from ansible_eda. When AWX launches them, they will receive that same variable as an extra variable, which has the highest precedence (Lesson 3.5) and overrides the value in vars:.

In AWX, as alex:

Object Type Configuration
Aurora - Notifications (webhook) Credential type See below
Aurora - Notifications lab Credential of that type The webhook URL of your Operations channel
Aurora - Remediate web Template Project aurora-infra, playbooks/remediate-web.yml, inventory Aurora - Lab, credentials Aurora - SSH lab, Aurora - Vault lab and Aurora - Notifications lab. Survey: aurora_eda_url (text, required, 8–200 characters)
Aurora - Remediate catalog Template playbooks/remediate-catalog.yml, same credentials. Survey: aurora_eda_instance (text, required)
eda User (Normal) Execute role only on the two previous templates; personal token with Write scope

The custom credential type (Lesson 7.5), for the summary callback webhook (ADR-12):

# Input configuration
fields:
  - id: webhook_url
    type: string
    label: Notification webhook URL
    secret: true
required:
  - webhook_url
# Injector configuration
env:
  AURORA_SUMMARY_WEBHOOK: "{{ webhook_url }}"
  • The aurora_store.infra.summary callback reads the URL from AURORA_SUMMARY_WEBHOOK (Lesson 10.3): with the credential attached, every job notifies the team without the URL being in the repository. Attach it to the existing templates too. Check in a job's output that the "AURORA STORE SUMMARY" block appears; if it doesn't, AWX isn't loading the callbacks_enabled from the project's ansible.cfg, and you can force it in Settings → Jobs → Extra Environment Variables with ANSIBLE_CALLBACKS_ENABLED.
  • Why a survey and not "Prompt on launch" for the variables? With Prompt on launch, whoever launches the template can pass any extra variable, including ones that change the playbook's behavior or the connection. With a survey and no Prompt on launch, AWX only accepts the survey variables and ignores the rest. It's least privilege applied to data (NFR-S2).

Store the eda user's token in the lab vault:

ansible-vault edit --vault-id lab@~/.ansible/vault/aurora-lab.pass playbooks/group_vars/lab/vault.yml
# Add:  vault_aurora_eda_awx_token: "<eda user token>"

5.3. The production rulebook

roles/aurora_monitoring/templates/rulebook.yml.j2:

---
# {{ ansible_managed }}
# Aurora Store rulebook (final project): the actions run in AWX.
# Version for learning locally, with run_playbook: rulebooks/watch-store.yml (Lesson 10.5).
- name: Watch the Aurora Store web servers
  hosts: all
  sources:
    - name: Check the web servers
      ansible.eda.url_check:
        urls:
{% for url in aurora_monitoring_urls %}
          - {{ url }}
{% endfor %}
        delay: {{ aurora_monitoring_url_check_delay }}
  rules:
    - name: Restart nginx on the web server that isn't responding
      condition: event.url_check.status == "down"
      throttle:
        once_within: 10 minutes
        group_by_attributes:
          - event.url_check.url
      action:
        run_job_template:
          name: "{{ aurora_monitoring_jt_remediate_web }}"
          organization: "{{ aurora_monitoring_awx_organization }}"
          job_args:
            extra_vars:
              aurora_eda_url: "{% raw %}{{ event.url_check.url }}{% endraw %}"

- name: Handle the monitoring alerts
  hosts: all
  sources:
    - name: Receive the Alertmanager notifications
      ansible.eda.alertmanager:
        host: 0.0.0.0
        port: 5050
  rules:
    - name: Restart the catalog API that is down
      condition: >-
        event.alert.status == "firing" and
        event.alert.labels.alertname == "AuroraCatalogDown"
      throttle:
        once_within: 15 minutes
        group_by_attributes:
          - event.alert.labels.instance
      action:
        run_job_template:
          name: "{{ aurora_monitoring_jt_remediate_catalog }}"
          organization: "{{ aurora_monitoring_awx_organization }}"
          job_args:
            extra_vars:
              aurora_eda_instance: "{% raw %}{{ event.alert.labels.instance }}{% endraw %}"

    - name: Show the remaining alerts
      condition: event.alert is defined
      action:
        print_event:
          pretty: true

Compare it with rulebooks/watch-store.yml (Lesson 10.5):

  • The URLs come from the inventory (a for loop); they aren't written by hand.
  • run_job_template instead of run_playbook. The variables in extra_vars are the ones in the surveys.
  • {% raw %}{{ event... }}{% endraw %}: the {{ }} expressions are for ansible-rulebook (which resolves them with the event data), not for the Ansible template. The same trick as in the Prometheus rules.
  • host: 0.0.0.0 inside the container: it listens on the Compose network, but the port isn't published on mon1 (section 4.4).
  • hosts: all and no inventory: run_job_template doesn't run anything locally, so ansible-rulebook doesn't need to know the servers; the AWX template provides the inventory.

roles/aurora_monitoring/templates/eda.env.j2:

# {{ ansible_managed }}
EDA_CONTROLLER_URL={{ aurora_monitoring_awx_url }}
EDA_CONTROLLER_TOKEN={{ aurora_monitoring_awx_token }}

ansible-rulebook reads the AWX connection from these environment variables (equivalent to --controller-url and --controller-token). The file has 0600 permissions and Compose passes it to the container with env_file.

5.4. Enabling and testing

In inventories/lab/group_vars/monitorservers.yml, aurora_monitoring_eda_enabled: true. Add to monitorservers.yml a check that EDA is running:

    - name: Check that Event-Driven Ansible is running
      community.docker.docker_container_info:
        name: aurora-monitoring-eda-1
      register: aurora_eda_container
      failed_when: not (aurora_eda_container.exists and aurora_eda_container.container.State.Running)
      when: aurora_monitoring_eda_enabled
      tags: always

Apply it and trigger the two incidents from Lesson 10.5:

ansible-playbook playbooks/site.yml --limit mon1
ssh mon1 sudo docker logs -f aurora-monitoring-eda-1 &      # keep the logs in view

ssh web1 sudo systemctl stop nginx
# In under 1 minute: an "Aurora - Remediate web" job in AWX, launched by eda
ssh api1 sudo docker stop aurora-catalog-catalog-1
# In about 2 minutes: alert -> Alertmanager -> EDA -> "Aurora - Remediate catalog"

In AWX, Views → Jobs: both jobs appear with Launched By eda, the aurora-ee 2.0.0 EE, the survey with the URL or the instance and the result Successful. The webhook notifies the channel. That is NFR-T4: the automatic remediation leaves the same trace as any other deployment.

Save the work (README.md: updated "Event-Driven Ansible" section; docs/awx.md with the new objects; CHANGELOG.md).

Milestone M4: stopping the API produces a successful Aurora - Remediate catalog job in AWX.

  1. Phase 5: remote Terraform state and staging in AWX

Branch staging-awx. Two problems to solve: the Terraform state lives on your laptop (AWX wouldn't see it), and refresh_inventory is no use inside AWX (ADR-08).

6.1. The state bucket

In playbooks/vars/aws-staging.yml, add (a bucket name is unique across all of AWS: change the suffix):

# Remote Terraform state (final project).
aurora_tfstate_bucket: aurora-tfstate-example-7f3a

playbooks/terraform-state.yml:

---
# Creates the S3 bucket for the Terraform state (final project). Run it ONCE,
# with a profile that has permission to create buckets:
#   AWS_PROFILE=aurora-admin ansible-playbook playbooks/terraform-state.yml
- name: Prepare the Terraform state storage
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files:
    - vars/aws-staging.yml

  tasks:
    - name: Create the Terraform state bucket
      amazon.aws.s3_bucket:
        name: "{{ aurora_tfstate_bucket }}"
        region: "{{ aurora_staging_region }}"
        state: present
        versioning: true
        encryption: AES256
        object_ownership: BucketOwnerEnforced
        public_access:
          block_public_acls: true
          ignore_public_acls: true
          block_public_policy: true
          restrict_public_buckets: true
        tags:
          Project: aurora
          ManagedBy: ansible
  • versioning: true: S3 keeps the previous versions of the state. If a run corrupts it, you can recover the previous one. It's the state's safety net.
  • encryption and public_access: the state contains sensitive data (IPs, identifiers and, depending on the resources, secrets); it must never be public.
  • A single owner (Lesson 8.5): Ansible creates the bucket; Terraform only uses it. If Terraform managed the bucket where it stores its own state, you'd have a circular problem.

6.2. The s3 backend

In terraform/staging/versions.tf, inside the existing terraform { ... } block:

  # Remote state in S3 with file-based locking (final project).
  # PARTIAL configuration: bucket, key and region come from Ansible (backend_config).
  backend "s3" {}

If you still have a local state from an earlier test (terraform/staging/terraform.tfstate), migrate its contents once, from the laptop:

cd terraform/staging
tofu init -migrate-state \
  -backend-config="bucket=aurora-tfstate-example-7f3a" \
  -backend-config="key=staging/terraform.tfstate" \
  -backend-config="region=eu-south-2" \
  -backend-config="encrypt=true" \
  -backend-config="use_lockfile=true"
cd ../..

If staging was destroyed (the normal situation at the end of each lesson), there's nothing to migrate: the first init from Ansible will create the state in S3.

Permissions: add to the policy of the aurora-ansible IAM user (Lesson 9.2) access only to its prefix in the bucket:

{
  "Sid": "TerraformStagingState",
  "Effect": "Allow",
  "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
  "Resource": "arn:aws:s3:::aurora-tfstate-example-7f3a/staging/*"
},
{
  "Sid": "ListTerraformStagingState",
  "Effect": "Allow",
  "Action": "s3:ListBucket",
  "Resource": "arn:aws:s3:::aurora-tfstate-example-7f3a",
  "Condition": {"StringLike": {"s3:prefix": ["staging/*"]}}
}

With use_lockfile, the lock is a staging/terraform.tfstate.tflock file next to the state: that's why DeleteObject is needed (to release the lock). And create a second IAM user, aurora-awx-read, only for the dynamic inventory, with a single allowed action: ec2:DescribeInstances (what amazon.aws.aws_ec2 queries, with the region set in aws_ec2.yml).

6.3. Splitting the provisioning

Copy the staging public key into the repository (public keys aren't secret, and this way AWX doesn't need your ~/.ssh):

cp ~/.ssh/aurora_staging_ed25519.pub ssh/

playbooks/staging-infra.yml is the first play of the old staging-provision.yml (Lesson 10.2) with three changes:

---
# staging infrastructure with OpenTofu/Terraform (final project, ADR-08).
# On the laptop it is used through staging-provision.yml; in AWX, as a template of its own
# ("Aurora - Staging infrastructure" and "Aurora - Destroy staging").
- name: Provision the Aurora Store staging environment with Terraform
  hosts: localhost
  connection: local
  gather_facts: false
  vars_files:
    - vars/aws-staging.yml
  vars:
    aurora_staging_state: present

  tasks:
    - name: Check that the staging inventory is being used
      ansible.builtin.assert:
        that: aurora_env == 'staging'
        fail_msg: "This playbook must be run with the staging inventory (-i inventories/staging)"

    - name: Require confirmation to destroy
      ansible.builtin.assert:
        that: confirm | default('') == aurora_staging_name
        fail_msg: "To destroy the environment, add -e confirm={{ aurora_staging_name }}"
      when: aurora_staging_state == 'absent'

    - name: Apply the environment's Terraform project
      community.general.terraform:
        project_path: "{{ aurora_staging_tf_project }}"
        binary_path: "{{ aurora_staging_tf_binary }}"
        state: "{{ aurora_staging_state }}"
        force_init: true
        backend_config:
          bucket: "{{ aurora_tfstate_bucket }}"
          key: staging/terraform.tfstate
          region: "{{ aurora_staging_region }}"
          encrypt: "true"
          use_lockfile: "true"
        variables:
          region: "{{ aurora_staging_region }}"
          az: "{{ aurora_staging_az }}"
          vpc_cidr: "{{ aurora_staging_vpc_cidr }}"
          subnet_cidr: "{{ aurora_staging_subnet_cidr }}"
          admin_cidr: "{{ aurora_staging_admin_cidr }}"
          instance_type: "{{ aurora_staging_instance_type }}"
          web_count: "{{ aurora_staging_web_count }}"
          db_count: "{{ aurora_staging_db_count }}"
          ssh_public_key_file: "{{ playbook_dir }}/../ssh/aurora_staging_ed25519.pub"
      register: aurora_staging_tf

    - name: Delete the known host keys of the destroyed environment
      ansible.builtin.file:
        path: ~/.ssh/known_hosts_aurora_staging
        state: absent
      when: aurora_staging_state == 'absent'

    - name: Stop here if the environment has been destroyed
      ansible.builtin.meta: end_playbook
      when: aurora_staging_state == 'absent'

    - name: Query AWS again to discover the new servers
      ansible.builtin.meta: refresh_inventory

The three changes:

  • The guard uses aurora_env instead of 'staging' in groups. The implicit localhost receives the variables of the inventory's all group (in staging, aurora_env: staging), and the check works the same on the laptop and in AWX, where a freshly created inventory may not yet have the staging group if there are no instances.
  • backend_config: the values of the partial backend configuration, which the module passes to tofu init as -backend-config. This way the bucket name lives in a single place (aws-staging.yml).
  • ssh_public_key_file points to the key in the repository (before, ~/.ssh, which doesn't exist inside the EE).

refresh_inventory stays: on the laptop it's still useful; in AWX it does nothing useful (the job uses the AWX inventory), which is why the workflow syncs the inventory in a separate node.

playbooks/staging-configure.yml (it gets back the name it had in Lesson 8.5, with different content):

---
# staging configuration (final project, ADR-08): waits for the servers to be
# ready and applies site.yml. In AWX, after syncing the "Aurora - Staging" inventory.
- name: Wait for the staging servers to be ready
  hosts: staging
  gather_facts: false
  become: true

  tasks:
    - name: Forget the cached facts of previous instances
      ansible.builtin.meta: clear_facts

    - name: Wait for the servers to accept SSH connections
      ansible.builtin.wait_for_connection:
        timeout: 300

    - name: Wait for cloud-init to finish booting
      ansible.builtin.command:
        cmd: cloud-init status --wait
      changed_when: false

- name: Apply the full Aurora Store configuration
  ansible.builtin.import_playbook: site.yml

And playbooks/staging-provision.yml is reduced to two useful entries, so you can keep using it from the laptop exactly as before:

---
# Provisions and configures staging from the laptop (same usage as in Lesson 10.2):
#   ansible-playbook -i inventories/staging playbooks/staging-provision.yml
#   ansible-playbook -i inventories/staging playbooks/staging-provision.yml \
#     -e aurora_staging_state=absent -e confirm=aurora-staging
- name: Infrastructure
  ansible.builtin.import_playbook: staging-infra.yml

- name: Configuration
  ansible.builtin.import_playbook: staging-configure.yml

When destroying, the meta: end_playbook in staging-infra.yml stops the whole run, including the playbooks imported afterwards: there's no attempt to configure an environment that no longer exists. Test the full cycle from the laptop (create, check changed=0 on a second run, destroy) before moving on to AWX.

6.4. staging and production in AWX

Object Type Configuration
Aurora - AWS staging Amazon Web Services credential Keys of aurora-awx-read (read-only)
Aurora - AWS staging (provision) Amazon Web Services credential Keys of aurora-ansible
Aurora - SSH staging Machine credential User ubuntu, private key aurora_staging_ed25519, sudo escalation
Aurora - Vault staging Vault credential Vault Identifier staging, password from aurora-staging.pass
Aurora - SSH production Machine credential User automation, key awx-production (Lesson 9.2)
Aurora - Vault production Vault credential Vault Identifier production
Aurora - Staging Inventory Source Sourced from a Project: aurora-infra, inventories/staging, credential Aurora - AWS staging, Overwrite, Overwrite variables, Update on launch
Aurora - Production Inventory Source from the project: inventories/production (ADR-01: not used in the lab nodes)
Aurora - Staging infrastructure Template playbooks/staging-infra.yml, inventory Aurora - Staging, credential Aurora - AWS staging (provision)
Aurora - Configure staging Template playbooks/staging-configure.yml, inventory Aurora - Staging, staging SSH, staging Vault and Notifications credentials
Aurora - Destroy staging Template Like the infrastructure one, with Variables aurora_staging_state: absent and confirm: aurora-staging; daily schedule at 21:00 (ADR-07)
  • Two AWS credentials: the inventory is synced many times and more people can launch it; if its credential leaked, it would only be good for reading the list of instances (AC-12). The one that creates and destroys resources is only used by two templates.
  • admin_cidr: the staging security group only allows SSH from that network (Lesson 8.4). AWX jobs go out to the Internet through your home or office connection, just like the laptop; if your public IP changes, update aurora_staging_admin_cidr.
  • Document all the objects in docs/awx.md (ADR-13).

Test the cycle in AWX, by hand, in this order: launch Aurora - Staging infrastructure; sync the Aurora - Staging source (Inventories → Aurora - Staging → Sources → Sync) and check that the three hosts appear in their groups; launch Aurora - Configure staging; launch Aurora - Destroy staging.

Milestone M5: staging created, configured and destroyed from AWX, without using the laptop.

  1. Phase 6: smoke tests and the promotion workflow

Branch promotion.

7.1. The smoke tests

Smoke tests are quick, read-only checks that the essentials work after a change. They don't replace Molecule (which tests a role in isolation) or --check (which compares configuration): they answer "does the store work right now in this environment?" (level 5 of the pyramid from Lesson 9.5).

playbooks/smoke-tests.yml:

---
# Aurora Store smoke tests (final project): quick, READ-ONLY checks
# that an environment works. They work for any environment:
#   ansible-playbook [-i inventories/staging] playbooks/smoke-tests.yml
# The environment's empty groups (loadbalancers in staging, for example) are skipped automatically.

- name: Smoke tests for the web servers
  hosts: webservers
  gather_facts: false
  tasks:
    - name: Request the home page from outside the server
      ansible.builtin.uri:
        url: "http://{{ ansible_host }}:{{ nginx_port }}/"
        return_content: true
      register: aurora_smoke_home
      delegate_to: localhost
      check_mode: false

    - name: Check the home page
      ansible.builtin.assert:
        that:
          - "'Aurora Store' in aurora_smoke_home.content"
          - "('Version ' ~ aurora_app_version) in aurora_smoke_home.content"
          - aurora_smoke_home.server | default('') == 'nginx'
        fail_msg: >-
          {{ inventory_hostname }} does not serve version {{ aurora_app_version }} or shows
          the nginx version (Server header: {{ aurora_smoke_home.server | default('none') }})
        quiet: true

    - name: Request the status page
      ansible.builtin.uri:
        url: "http://{{ ansible_host }}:{{ nginx_port }}/status.html"
        return_content: true
      register: aurora_smoke_status
      failed_when: aurora_smoke_status.status != 200 or 'OK' not in aurora_smoke_status.content
      delegate_to: localhost
      check_mode: false

    - name: Check that the web server reaches the database
      ansible.builtin.wait_for:
        host: "{{ aurora_app_db_host }}"
        port: "{{ aurora_app_db_port }}"
        timeout: 5

- name: Smoke tests for the database
  hosts: dbservers
  gather_facts: false
  tasks:
    - name: Check that the store can authenticate to its database
      community.postgresql.postgresql_ping:
        login_host: 127.0.0.1
        login_user: "{{ aurora_db_user }}"
        login_password: "{{ aurora_db_password }}"
        db: "{{ aurora_db_name }}"
        port: "{{ postgresql_port }}"
      register: aurora_smoke_db
      failed_when: not aurora_smoke_db.is_available

- name: Smoke tests for the load balancers
  hosts: loadbalancers
  gather_facts: false
  tasks:
    - name: Request the store several times through the load balancer
      ansible.builtin.uri:
        url: "http://{{ ansible_host }}:{{ nginx_port }}/"
        return_content: true
      register: aurora_smoke_lb
      loop: "{{ range(6) | list }}"
      loop_control:
        label: "request {{ item + 1 }}"
      delegate_to: localhost
      check_mode: false

    - name: Check that the load balancer distributes across all the web servers
      ansible.builtin.assert:
        that: >-
          aurora_smoke_lb.results | map(attribute='content')
          | map('regex_search', 'Served by (\\S+)', '\\1') | map('first')
          | unique | length == groups['webservers'] | length
        fail_msg: "The load balancer does not send requests to all the web servers"
        quiet: true

- name: Smoke tests for the catalog API
  hosts: apiservers
  gather_facts: false
  tasks:
    - name: Query the API health
      ansible.builtin.uri:
        url: "http://127.0.0.1:{{ aurora_catalog_port }}/health"
      register: aurora_smoke_api
      check_mode: false

    - name: Check the API version and its access to Redis
      ansible.builtin.assert:
        that:
          - aurora_smoke_api.json.version == aurora_catalog_version
          - aurora_smoke_api.json.redis
        quiet: true

- name: Smoke tests for the monitoring
  hosts: monitorservers
  gather_facts: false
  tasks:
    - name: Query the active alerts
      ansible.builtin.uri:
        url: http://127.0.0.1:9090/api/v1/alerts
      register: aurora_smoke_alerts
      check_mode: false

    - name: Check that there are no active critical alerts
      ansible.builtin.assert:
        that: >-
          aurora_smoke_alerts.json.data.alerts
          | selectattr('state', 'equalto', 'firing')
          | selectattr('labels.severity', 'equalto', 'critical')
          | list | length == 0
        fail_msg: "There are active critical alerts in Prometheus"
        quiet: true

How it's designed:

  • Read-only: there is no become in any play (the database is checked with the store's credentials, as in dbservers.yml) and check_mode: false on the queries so the playbook gives the same result with --check.
  • From outside and from inside: the website is requested with delegate_to: localhost, as a client would (from AWX, the client is the EE container); the database is checked from the web server itself with wait_for (is there a network path, with firewalls open, all the way to 5432?).
  • ('Version ' ~ aurora_app_version): Jinja's ~ operator concatenates text. It checks that the version the inventory states is being served, which is what the promotion has just deployed.
  • Load balancer distribution: six requests; from each response, the server name ("Served by web1") is extracted with regex_search and a capture group (it returns a list, hence map('first')); unique | length counts the distinct servers. With 2:1 weights, six requests are enough to see both.
  • Empty groups: in staging there's no load balancer, API or monitoring; those plays end with "skipping: no hosts matched", without an error.
  • No critical alerts: a deployment that "works" but triggers an alert isn't finished.
ansible-playbook playbooks/smoke-tests.yml

7.2. The workflow templates

  • Aurora - Smoke tests (new template): playbooks/smoke-tests.yml, with Prompt on launch on Inventory and Credentials (default values: Aurora - Lab, the lab SSH and Vault, Notifications). Schedule Hourly smoke tests against the lab (AC-14).
  • Aurora - Deploy web (existing, Lesson 7.3): enable Prompt on launch on Inventory and Credentials, so the workflow decides which environment it deploys to.

7.3. The promotion workflow

Redesign Aurora - Release web version (same name: the CI launches it by name, Lesson 8.3):

flowchart LR
    S["Sync project<br/>aurora-infra"] -->|Success| I["Staging<br/>infrastructure"]
    I -->|Success| SI["Sync inventory<br/>Aurora - Staging"]
    SI -->|Success| C["Configure staging"]
    C -->|Success| HS["Smoke tests<br/>(staging)"]
    HS -->|Success| AP{"Approve promotion<br/>to production"}
    AP -->|Approved| D["Deploy web<br/>(production, serial 1)"]
    D -->|Success| HP["Smoke tests<br/>(production)"]
Node Type Node inventory and credentials
Sync project Project Sync —
Staging infrastructure Template Aurora - Staging infrastructure The template's own
Sync inventory Inventory Source Sync: Aurora - Staging source —
Configure staging Template Aurora - Configure staging The template's own
Smoke tests (staging) Template Aurora - Smoke tests Aurora - Staging; staging SSH, staging Vault
Approve promotion to production Approval, 4 h timeout —
Deploy web (production) Template Aurora - Deploy web Aurora - Lab; lab SSH, Vault lab (ADR-01)
Smoke tests (production) Template Aurora - Smoke tests The same as the deployment

Three details that often go wrong:

  • Remove the inventory from the workflow itself (the Inventory field of the workflow template, which in Lesson 7.5 pointed to Aurora - Lab). An inventory at workflow level replaces the inventory of every node that accepts one: your staging smoke tests would run against the lab.
  • The inventory sync node is what solves ADR-08: between infrastructure and configuration, AWX runs the aws_ec2 plugin again and stores the new hosts.
  • No On Failure links: if something fails, the workflow ends in error and sends a notification. If the deployment to production fails, webservers.yml leaves the affected server out of the load balancer (Lesson 5.7) and the rollback runbook says what to do.

The permissions from Lesson 7.5 stay as they were: Operations approves, Development launches, gitea-ci launches without approving. The workflow's aurora_app_version survey stays for emergencies (Lesson 8.3) and its value reaches every node.

7.4. The release CI

In .gitea/workflows/web-deploy.yml, the check that the tag matches the inventory now goes through the three environments (ADR-11). Replace the comparison with inventories/lab with:

for env in lab staging production; do
  file="inventories/$env/group_vars/webservers.yml"
  current="$(grep -E '^aurora_app_version:' "$file" | cut -d'"' -f2)"
  if [ "$current" != "$VERSION" ]; then
    echo "::error::$file has aurora_app_version \"$current\" and the tag is $VERSION"
    exit 1
  fi
done
  • cut -d'"' -f2 extracts whatever is between the first pair of quotes ("1.5.0" → 1.5.0): that's why Aurora always writes the version in quotes (Lesson 5.5).
  • ::error:: is the Gitea/GitHub Actions format for flagging the error in the UI.

Merge the promotion branch once the CI is green.

7.5. Releasing version 1.5.0 end to end

Follow the deployment runbook in section 9 (write it first: you'll be testing the procedure at the same time). In short:

git switch main && git pull && git switch -c web-1.5.0
sed -i 's/^aurora_app_version: .*/aurora_app_version: "1.5.0"/' \
  inventories/{lab,staging,production}/group_vars/webservers.yml
git diff --stat                     # exactly three files, one line each
# CHANGELOG.md: "Web 1.5.0"
git commit -am "Website version 1.5.0" && git push -u origin web-1.5.0
# PR -> green CI -> review by marc -> merge
git switch main && git pull
git tag -a web-1.5.0 -m "Web 1.5.0" && git push origin web-1.5.0

While the workflow progresses, leave a loop running against the load balancer in another terminal:

while true; do
  curl -s --max-time 2 http://192.168.56.10/ | grep -o 'Version [0-9.]* - Served by web[0-9]' || echo "ERROR $(date +%T)"
  sleep 0.5
done

When the workflow reaches the approval, log in to AWX as marc, review the output of the staging smoke tests and approve. In the loop you'll see web1 and then web2 move to 1.5.0 without a single ERROR (AC-13). Afterwards, the nightly schedule will destroy staging; if you're done for the day, launch it now.

Milestone M6: website 1.5.0 in production, promoted from staging by the web-1.5.0 tag.

  1. The project's tests

With the project finished, the test pyramid from Lesson 9.5 is complete:

Level What it checks Tool Where and when
1. Syntax That the playbooks can be loaded --syntax-check CI, every push
2. Style and good practices YAML, Ansible rules, encrypted secrets yamllint, ansible-lint, gitleaks, check-vault.sh pre-commit and CI
3. Isolated roles That each role converges, is idempotent and leaves what's expected Molecule (common; postgresql_backup in Exercise 1) CI, every push
4. Drift That the environment matches the code site.yml --check --diff AWX every night and the CI on main
5. Integration That the new environment really works staging-configure.yml on new instances Workflow, on every promotion
6. Smoke That the store works right now smoke-tests.yml Workflow (staging and production) and every hour
7. Recovery That the backups are usable test-restore.yml AWX every week
8. Remediation That the automatic response works Drills (stop nginx, stop the API) By hand, after changing the monitoring or EDA

Two tips to keep this pyramid useful:

  • Every real incident adds a test. If one day the store fails because of something no test detected, the fix isn't finished until a smoke test, an alerting rule or an assert would detect it next time.
  • Slow tests don't get run. If the smoke tests take ten minutes, someone will remove them from the workflow "just for today". Keep them under a minute.

  1. Deployment runbook

A runbook is a written, step-by-step procedure that anyone on the team can follow without knowing the internal details. Write docs/runbooks/deployment.md with this structure:

1. Before you start (pre-checks)

  • The version's pull request is merged and the main CI is green.
  • The last nightly check (Aurora - Check configuration) finished with no changes.
  • There are no active critical alerts (SSH tunnel to mon1, http://localhost:9093).
  • The latest backup is from the last 24 h (AuroraBackupTooOld is not active).
  • There is no other deployment in progress and no maintenance window.

2. Launch

  • Create and push the tag: git tag -a web-X.Y.Z -m "Web X.Y.Z" && git push origin web-X.Y.Z.
  • Check in Gitea (Actions) that web-deploy.yml finishes green, and in AWX that the Aurora - Release web version workflow has started.

3. Watch staging

  • If "Staging infrastructure" or "Configure staging" fails: it's a problem with the environment, not with the version; review the output, fix it with a pull request and launch the workflow again from AWX (Relaunch).
  • If the smoke tests fail: do not approve. The version doesn't go through.

4. Approve (Operations)

  • Read the output of "Smoke tests (staging)".
  • Approve in Views → Workflow Approvals only if everything is green. The approval is recorded under your user.

5. Watch production

  • Follow the "Deploy web" job: one server at a time, out of and back into the load balancer.
  • When it finishes, check "Smoke tests (production)" and, five minutes later, that there are no new alerts.

6. Close

  • Post in the Operations channel the deployed version and the link to the workflow.
  • If staging won't be used again today, launch Aurora - Destroy staging.

Emergency (AWX unavailable). From the laptop of someone in Operations, with the repository at the tag: git checkout web-X.Y.Z && ansible-playbook playbooks/webservers.yml --tags deploy. Post it in the channel and record it afterwards in docs/ (AWX traceability has been lost for that run).

  1. Rollback runbook

Write docs/runbooks/rollback.md. A well-prepared rollback is fast because what to do in each case was decided before the incident:

Situation Symptom Rollback
The new website version fails in production Production smoke tests red, customer complaints See A
A web server was left out of the load balancer Deployment failed halfway; the load balancer serves with a single web server See B
A configuration change breaks something Failure after merging a change to roles or inventory See C
Corrupted or deleted data in PostgreSQL Application errors, missing data See D
The new EE or ansible-core fails in AWX All jobs fail after changing the EE See E
The automatic remediation loops or makes something worse Many remediation jobs in a row See F

A. Go back to the previous website version.

  1. Launch Aurora - Release web version from AWX with the aurora_app_version survey = previous version (for example, 1.4.0). This is the intended emergency use of the survey (Lesson 8.3). It goes through staging and the approval: if it's very urgent, Operations can launch Aurora - Deploy web directly with the lab inventory and credentials and the aurora_app_version variable.
  2. Afterwards, bring the repository back in line: a pull request with a git revert of the version commit (the three lines go back to the previous version). No new tag: the previous version already has its own.
  3. The nightly check will confirm that there is no drift.

B. A server was left out of the load balancer. This is the designed behavior (Lesson 5.7): webservers.yml stops without putting it back. Fix the cause (see the job output) and relaunch Aurora - Deploy web: the server is deployed again and put back. If it has to be put back without deploying, launch the template with Limit webN and the always tags.

C. Configuration change. git revert of the commit with a pull request → merge → Aurora - Configure infrastructure (or only the affected group with Limit). Ansible is declarative: applying the previous code returns the servers to their previous state, except for what the change created and the previous code doesn't mention (an installed package, a new file): that is removed by hand or with state: absent in the revert itself.

D. Restore PostgreSQL (requires Operations approval; target RTO 4 h):

  1. Stop deployments and notify: the store may serve incorrect data during the restore.
  2. Choose the backup: ssh db1 sudo ls -lt /var/backups/postgresql (the latest one before the damage).
  3. Restore into a new database and check it before replacing anything:
ssh db1
sudo -u postgres createdb aurora_recovered
sudo -u postgres pg_restore --dbname=aurora_recovered --exit-on-error /var/backups/postgresql/aurora-YYYYMMDD-HHMMSS.dump
# Check the data in aurora_recovered (business queries)
  1. Swap: rename the damaged and the recovered databases (ALTER DATABASE aurora RENAME TO aurora_damaged; ALTER DATABASE aurora_recovered RENAME TO aurora;, with no open connections), make sure of the owner (ALTER DATABASE aurora OWNER TO aurora;) and launch Aurora - Check configuration against db1: there must be no changes.
  2. If the whole server was lost: recreate db1 (Vagrant or cloud), apply site.yml --limit db1, restore globals-*.sql first with psql and then each database.
  3. Write down the total time: that is your real RTO.

E. Go back to the previous EE. In AWX, Aurora Store organization → default EE = aurora-ee 1.4.0 (that's why it is kept for a few days after phase 1). In the repository, git revert of the phase 1 pull request. Immutable tags (Lesson 7.6) guarantee that 1.4.0 is exactly the image that worked.

F. Stop the automatic remediation. ssh mon1 sudo docker compose -f /opt/aurora-monitoring/compose.yaml stop eda. Alerts keep reaching Alertmanager; nothing is remediated until it has been investigated and started again (start eda) or site.yml --limit mon1 is applied. If the loop comes from a template, you can also temporarily remove the Execute permission from the eda user.

Rehearse rollback A at least once with the lab (from 1.5.0 to 1.4.0 and back to 1.5.0) and write down the time in docs/acceptance.md (AC-16). A runbook that has never been rehearsed is a hypothesis.

  1. Final self-assessment checklist

Copy this checklist into docs/acceptance.md and check off each item with the date and the evidence (command, link to the AWX job or to the CI run). The AC-xx references are the acceptance criteria from Lesson 11.1.

Foundation and quality

  • [ ] AC-01 · The main CI passes lint, syntax and Molecule with ansible-core 2.20 (ansible --version in the job output).
  • [ ] AC-02 · ansible-playbook playbooks/site.yml --check --diff against the lab: changed=0 on every host.
  • [ ] AC-03 · All AWX templates show aurora-ee 2.0.0 in their jobs.
  • [ ] AC-09 · pre-commit run --all-files green; no new plaintext secret (git grep -n vault_aurora_eda_awx_token only appears encrypted or as a reference).

Data

  • [ ] AC-04 · ssh db1 sudo ls -lt /var/backups/postgresql shows backups from the last 24 h; Aurora - Test restore successful.
  • [ ] AC-07 · The four alerts appear in http://localhost:9090/alerts. Old-backup simulation: on db1, replace the value in /var/lib/node_exporter/postgresql_backup.prom with the timestamp from two days ago (date -d '2 days ago' +%s; changing the file's date with touch isn't enough, because the metric carries its own value) and check that AuroraBackupTooOld goes to firing after 30 minutes; then sudo systemctl start postgresql-backup.service and the alert resolves.

Monitoring and events

  • [ ] AC-05 · http://localhost:9090/targets (tunnel): all servers UP with their inventory names.
  • [ ] AC-06 · curl --max-time 3 http://192.168.56.11:9100/metrics fails from the laptop and works from mon1.
  • [ ] AC-08 · systemctl stop nginx on web1 and docker stop of the API: two Successful remediation jobs in AWX, launched by eda, in under 5 minutes each.
  • [ ] AC-15 · The notification channel receives the summary of every job; git grep -niE 'https?://[^ ]*hook' finds no webhook URL in the repository.

Environments and promotion

  • [ ] AC-10 · aws s3 ls s3://<bucket>/staging/ shows terraform.tfstate. While Aurora - Staging infrastructure is applying changes in AWX, a tofu plan from the laptop (with the same backend configuration) fails with "Error acquiring the state lock". (Don't test it by launching the template twice: AWX doesn't run a template without Concurrent Jobs in parallel; it simply queues the second one.)
  • [ ] AC-11 · staging created, configured and destroyed from AWX.
  • [ ] AC-12 · With the aurora-awx-read keys, aws ec2 run-instances ... returns UnauthorizedOperation.
  • [ ] AC-13 · Website 1.5.0 released with web-1.5.0, approved by marc, with no ERROR in the curl loop.
  • [ ] AC-14 · The Hourly smoke tests schedule has successful runs.
  • [ ] AC-18 · aws ec2 describe-instances --filters Name=tag:Environment,Values=staging Name=instance-state-name,Values=running returns nothing at the end.

Documentation and operations

  • [ ] AC-16 · docs/runbooks/deployment.md and rollback.md written; rollback A rehearsed (time recorded).
  • [ ] AC-17 · docs/adr/ with the 13 ADRs, docs/awx.md complete, README.md and CHANGELOG.md up to date.

When everything is checked, close the project:

git switch -c project-closure
git add docs/acceptance.md CHANGELOG.md README.md
git commit -m "Final project: acceptance completed"
git push -u origin project-closure
# PR -> merge

Milestone M7: project accepted.

  1. Extension ideas

The project deliberately leaves written-down debt (Lesson 11.1, section 8). These are the natural extensions, ordered by the value they bring:

Extension What it solves Hints
A copy of the backups outside db1 (P18) Losing db1 doesn't mean losing the data Upload each backup to an S3 bucket with amazon.aws.s3_object from a scheduled playbook, or restic from the script; encryption and retention at the destination
AWX as code (P16) Rebuild AWX from the repository (full NFR-R5) The awx.awx collection: credential, inventory, job_template, workflow_job_template, schedule, role modules; an awx/configure.yml playbook launched with alex's token
Automate awx1 (P13) Recover the platform after a disaster Roles for k3s, AWX Operator (kubernetes.core.k8s with the CR from Lesson 7.2), Gitea and the registry in containers
Registry with TLS and authentication (P14) Images that can't be tampered with in transit; a registry that isn't open A certificate from an internal CA, htpasswd in registry:2, a registry credential in AWX, docker login in the docker role
Isolated CI runner (P15) The CI doesn't share a machine or privileges with AWX act_runner in container mode or in its own VM, registered per repository
High availability Remove the single points of failure A second load balancer with keepalived; a streaming PostgreSQL replica and failover with approval
Grafana Investigate with dashboards Another service in the aurora_monitoring Compose project, with the data source provisioned from a file
Notifying people from Alertmanager Not depending only on EDA and the callback Exercise 2 of this lesson
Watching the watcher Knowing whether mon1 is down An external check (for example, an AWX schedule that queries Prometheus /-/healthy) or a heartbeat service
HTTPS on the store A mandatory requirement for a real store Certificates with ACME (community.crypto.acme_certificate) and scheduled renewal; security headers (nginx 1.2.0, Lesson 9.2)
CI for the collection Publish aurora_store.infra with guarantees A CI job with ansible-test sanity and units --docker in its repository; publish aurora_catalog_info
The catalog API on Kubernetes within the promotion A single flow for everything that gets released A kubernetes.yml node in the workflow, with an EE that includes helm and a Kubernetes credential

Common Mistakes and Tips

  • Upgrading ansible-core and other things at the same time. If in phase 1 you also change roles or inventory and something fails, you won't know what caused it. One variable at a time.
  • ansible-builder fails installing dependencies with Python 3.12. If the build can't find pip for python3.12, add python3.12-pip [platform:rpm] to system. If it fails compiling jpy (in the decision environment), add java-17-openjdk-devel and ENV JAVA_HOME=... in prepend_builder too.
  • Templates containing another tool's {{ }}. Prometheus, Alertmanager and ansible-rulebook use the same syntax as Jinja. Without {% raw %}, Ansible will try to resolve $labels or event and fail with "is undefined".
  • The alert doesn't reach EDA. Check, in order: the rule in Prometheus (Alerts: is it firing?), Alertmanager (which receiver?), the logs of aurora-monitoring-eda-1 (did the event arrive? which rule matched?), AWX (a permissions error for the eda user? a survey with a different variable name?).
  • The remediation job finishes without doing anything. That's correct if the prior check saw the service healthy (end_host). If not, compare the survey value with what the playbook expects: instance must be the inventory name, and the URL must contain aurora_internal_ip.
  • The metric goes stale and nobody notices. If the API health timer stops, aurora_catalog_up keeps its last value. node_exporter publishes node_textfile_mtime_seconds with the timestamp of each file: a rule time() - node_textfile_mtime_seconds > 300 detects it (a good first extension to the rules).
  • The workflow inventory overrides the nodes' inventories. Leave the workflow's Inventory field empty; otherwise, every node uses the same one.
  • staging is left running. A workflow that fails at the smoke tests leaves staging created. The nightly schedule destroys it, but check the AWS console at the end of each session (AC-18).
  • A Terraform lock that isn't released. If a job is canceled in the middle of an apply, the .tflock file may be left in S3. Before deleting it (tofu force-unlock <ID> from the laptop), check that there really is no other run in progress.
  • Tip: keep a living decision log. If during implementation you change something in the design (for example, a different image version or a different name), update the ADR or create a new one that supersedes it. The design and the code must tell the same story.

Exercises

Exercise 1: Molecule for postgresql_backup

Create a Molecule scenario roles/postgresql_backup/molecule/default/ (following the same pattern as the one for common, Lesson 9.5, with Ubuntu 24.04 only) that installs PostgreSQL with the postgresql role, applies postgresql_backup and verifies that: the timer is enabled, a run of the service produces a valid backup of the test database and the metric is written.

Exercise 2: notifying people too

Modify alertmanager.yml.j2 so that all alerts also reach a webhook on the Operations channel (URL in the vault, variable aurora_monitoring_notify_url), critical alerts still go to EDA, and the AuroraCatalogDown alert is not notified if AuroraServerDown is active at the same time for the same instance (the whole server is down: restarting the container makes no sense).

Exercise 3: data disaster drill

In the lab, "accidentally" drop the aurora_analytics database and recover it by following runbook D. Time it and check at the end that site.yml --check --diff shows no changes.

Solutions

Exercise 1. roles/postgresql_backup/molecule/default/molecule.yml is the one for common with a single platform (backup-ubuntu2404, ubuntu:24.04, the same Dockerfile.j2, prepare.yml and ansible: section). converge.yml:

---
- name: Converge
  hosts: all
  become: true
  gather_facts: true
  vars:
    postgresql_databases:
      - name: test
        owner: postgres
    postgresql_backup_databases: [test]
    postgresql_backup_retention_days: 2
    postgresql_backup_metrics_dir: /var/lib/node_exporter
  pre_tasks:
    - name: Create the metrics directory (node_exporter would do it)
      ansible.builtin.file:
        path: /var/lib/node_exporter
        state: directory
        mode: "0755"
  roles:
    - postgresql
    - postgresql_backup

verify.yml:

---
- name: Verify
  hosts: all
  become: true
  gather_facts: false
  tasks:
    - name: Check that the timer is enabled
      ansible.builtin.command: systemctl is-enabled postgresql-backup.timer
      changed_when: false

    - name: Run a backup
      ansible.builtin.systemd_service:
        name: postgresql-backup.service
        state: started

    - name: Find the backup of the test database
      ansible.builtin.find:
        paths: /var/backups/postgresql
        patterns: "test-*.dump"
      register: backup_test_copies

    - name: Check that the backup is a valid pg_restore archive
      ansible.builtin.command:
        argv: [pg_restore, --list, "{{ (backup_test_copies.files | first).path }}"]
      changed_when: false

    - name: Read the metric
      ansible.builtin.slurp:
        src: /var/lib/node_exporter/postgresql_backup.prom
      register: backup_test_metric

    - name: Check the metric
      ansible.builtin.assert:
        that: "'aurora_postgresql_backup_last_success_timestamp_seconds' in (backup_test_metric.content | b64decode)"

Notes: the service is Type=oneshot, so state: started waits for it to finish (if the script fails, the task fails with the systemd error). pg_restore --list reads the archive's table of contents without restoring anything: it's the cheapest check that the backup isn't corrupt. If the find task finds nothing, first will fail with an unclear error; you can add an assert on matched > 0 beforehand. The scenario will run in the CI on its own thanks to the loop in the tests job (Lesson 9.5).

Exercise 2. In alertmanager.yml.j2:

# {{ ansible_managed }}
route:
  receiver: people
  group_by: [alertname, instance]
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h
  routes:
{% if aurora_monitoring_eda_enabled %}
    - receiver: eda
      matchers:
        - severity = "critical"
      continue: true
{% endif %}
    - receiver: people

inhibit_rules:
  - source_matchers:
      - alertname = "AuroraServerDown"
    target_matchers:
      - alertname = "AuroraCatalogDown"
    equal: [instance]

receivers:
  - name: people
    webhook_configs:
      - url: "{{ aurora_monitoring_notify_url }}"
        send_resolved: true
{% if aurora_monitoring_eda_enabled %}
  - name: eda
    webhook_configs:
      - url: http://eda:5050/
        send_resolved: true
{% endif %}
  • routes are child routes evaluated in order. The first sends critical alerts to EDA and, thanks to continue: true, keeps evaluating: the second (with no conditions) also sends them to people. Without continue, the first matching route keeps the alert.
  • inhibit_rules: while an AuroraServerDown alert is active, AuroraCatalogDown alerts with the same instance are silenced. That way EDA doesn't try to restart a container on a server that isn't responding.
  • Add aurora_monitoring_notify_url to defaults (empty), to argument_specs (with no_log: true) and to the wiring ("{{ vault_aurora_notify_url }}"), and set diff: false on the Alertmanager task, because the configuration now contains a secret. The validate with amtool will catch any format error.

Exercise 3.

ssh db1 sudo -u postgres dropdb aurora_analytics              # the "accident" (lab only)
date +%T                                                      # start
ssh db1 sudo ls -lt /var/backups/postgresql | grep aurora_analytics | head -1
ssh db1 sudo -u postgres pg_restore --create --dbname=postgres --exit-on-error \
  /var/backups/postgresql/aurora_analytics-YYYYMMDD-HHMMSS.dump
date +%T                                                      # end
ansible-playbook playbooks/site.yml --check --diff --limit db1
  • --create --dbname=postgres: pg_restore connects to the postgres database, creates aurora_analytics with the name and owner (aurora_reporting) stored in the backup and restores into it. It works because the aurora_reporting role still exists; if the server had been lost, you would first have to restore globals-*.sql (runbook D, step 5).
  • site.yml --check --diff must finish with no changes: the database exists again with its owner, which is what postgresql_databases declares. If you had restored without --create into a database created by hand with a different owner, --check would show it to you as drift: another reason to always check after a recovery.
  • Write down the time in docs/acceptance.md. With a small database it will be minutes; what takes longest in real life is deciding (which backup, what is lost, whom to notify), and that's why the runbook settles it in advance.

Conclusion

With this lesson you finish the final project and the course. Aurora Store now has a complete production platform: supported tools (ansible-core 2.20 and aurora-ee 2.0.0), daily backups that are monitored and tested, monitoring with Prometheus and Alertmanager whose alerts reach Event-Driven Ansible and become AWX jobs, a staging environment on AWS that creates and destroys itself with its shared Terraform state, and a workflow that takes each website version from a Git tag to production through smoke tests and a human approval, with runbooks for deploying and for rolling back.

Look at how far you've come. You started in Lesson 1.5 with a three-line inventory.ini and an ansible all -m ping. You organized the inventory and the configuration (Module 2), turned loose commands into playbooks (Module 3) and playbooks into reusable roles (Module 4). You learned the techniques that separate a script from professional automation: handlers, templates, filters, Vault, error handling, tags and zero-downtime rolling deployments (Module 5). You shared and reused content with Galaxy and your own collection (Module 6), moved execution onto a platform with AWX (Module 7) and connected Ansible with containers, Kubernetes, CI/CD, the cloud and Terraform (Module 8). You organized the repository by environment, hardened it, made it fast and put it under continuous testing (Module 9), and you extended Ansible with your own modules and plugins, drove it from Python and made it react to events (Module 10). In this last module you have brought it all together, from design to acceptance.

The skills you take with you:

  • Automating the configuration of Linux servers in a declarative, idempotent and reusable way, with well-organized inventories, playbooks, roles and collections.
  • Managing secrets and security: per-environment Vault, least privilege, hardening and the supply chain.
  • Deploying with zero downtime and rolling back safely, with rolling deployments, checks and written procedures.
  • Operating at team scale with AWX: protected credentials, RBAC, workflows with approval, schedules and reproducible execution environments.
  • Integrating Ansible into DevOps: CI/CD, containers, Kubernetes, cloud and infrastructure as code with Terraform.
  • Ensuring quality with ansible-lint, Molecule, smoke tests and a complete test pyramid.
  • Extending and connecting Ansible: modules, plugins, ansible-runner and Event-Driven Ansible.
  • Designing an automation platform: measurable requirements, written decisions, phased plans and acceptance criteria.

To keep learning:

  • Red Hat certifications. The EX294 exam (Red Hat Certified Engineer, RHCE) assesses automating Red Hat Enterprise Linux systems with Ansible: inventories, playbooks, roles, Vault, collections and templates, in a timed hands-on exam. The EX374 (Red Hat Certified Specialist in Developing Automation with Ansible Automation Platform) focuses on developing with the platform: execution environments, ansible-navigator, collections and automation controller. Both are hands-on exams: practice on RHEL or compatible machines (this course's lab uses Ubuntu, so brush up on dnf, firewalld and SELinux) and review each exam's published objectives before you sit it, because they are updated along with the platform versions.
  • The community. The official Ansible forum (forum.ansible.com) is the meeting point for questions, announcements and working groups; the community collections accept contributions on GitHub, and fixing some documentation or a small bug is the best way to start. The community newsletters and events (AnsibleFest within Red Hat Summit, local meetups) will keep you up to date.
  • The official documentation. docs.ansible.com brings together the user guide, the collection index with the documentation for every module, the porting guides for each version (always read them before upgrading, as in phase 1) and the documentation for ansible-lint, Molecule, ansible-builder, ansible-navigator, AWX and Event-Driven Ansible. ansible-doc is still your first port of call from the terminal.
  • And, above all, practice. Pick up the extension ideas from this lesson, automate something real from your work and apply the same method: design, write down the decisions, build in phases and verify every step.

You've gone from running a ping to running a platform that deploys, monitors and repairs itself, leaving a trace of every step. That is the difference between using Ansible and truly automating. Congratulations on making it this far.

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