Ansible Hour 6: Application Deployment Architecture in Practice

Turn myapp from “runs on one machine” into “a three-tier architecture with rolling releases, rollback, and zero downtime”: nginx load balancer → 2 gunicorn application nodes → PostgreSQL
ansible-core 2.21Ansible community package 14.xcommunity.postgresql 4.2community.docker 5.4kubernetes.core 6.6Verified against official docs · 2026-11
Overall learning objectives
  • By lb / app / db designing the layered inventory (inventory): environment directories inventories/staging,inventories/production; group_vars layered structure and variable precedence, with one site.yml playbook orchestrating all tiers.
  • Use Jinja2 templates to dynamically generate the nginx upstream / HAProxy backend from the inventory, using validate to check the config before it is written, and explain the difference between reload and restart for in-flight connections.
  • Deploy myapp natively with systemd: a separate venv,a versioned release directory with a current symlink, systemd unit template,EnvironmentFile,/healthz and /readyz health endpoints.
  • Use community.postgresql to manage users, databases, tables and pg_hba.conf; use cron + pg_dump for scheduled backups, and complete one restore drill.
  • Master all the rolling-update knobs: serial (number / percentage / list),max_fail_percentage (must be “exceeded” to abort),any_errors_fatal,order,throttle.
  • Achieve zero-downtime releases: delegate_to remove/re-add nodes at the load balancer,run_once run it only once per batch,wait_for state=drained wait for connections to drain,uri health checks,block/rescue and automatic rollback.
  • Know when to hand the same orchestration to containers and Kubernetes: community.docker.docker_container / docker_compose_v2,kubernetes.core.k8s / helm, and the appropriate boundaries of Ansible within them.
  • Conduct one architecture review: failure mode analysis (FMEA), review scoring, and incident drills.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (4 systemd + sshd containers)
0Before classPreparation: multi-tier sample app projectBuild a managed-node image with systemd, start lb1/app1/app2/db1, generate the project skeletonEnvironment self-check checklistansible all -m ping All green
100–07Multi-tier application architecture and inventory designlb/app/db groups, environment directories, group_vars layering, variable precedence, site.yml,import_playbookVariable resolver: click a host to see which layer each variable comes fromCreate a staging inventory and use ansible-inventory --graph to verify
207–14Load balancer tier: nginx/HAProxyupstream template, generating backends from groups['app'] ,validate handler reload, HAProxy admin socketupstream generator + reload/restart connection comparisonDeploy the nginx LB, deliberately break the config, and watch validate block it
314–22Application tier: systemd services and configurationvenv/dependencies, release directory, unit template, EnvironmentFile,daemon_reload, /healthzThe 9 real steps of one release on a managed nodeDeploy myapp v1 to app1/app2
422–30Data tier: PostgreSQL and backupspostgresql_user/db/table/privs/pg_hba, become_user postgres, backup cron, restore drillpg_hba first-match simulator + backup/restore pipelineCreate database and user, back up, restore after dropping a table
530–38Rolling updates: serial and failure thresholdserial’s three syntaxes, batch calculation, max_fail_percentage, any_errors_fatal, order, throttleCore animation: serial rolling timeline + threshold abortUse a serial list for a canary; inject a fault and watch the abort
638–46Zero downtime: delegate_to and health checksRemove → drain → deploy → health check → re-add; run_once once per batch; pre/post_tasks; block/rescue rollbackError-rate comparison of “with vs. without removal” under load-test trafficv1→v2 zero-downtime release, 0 errors under load test
746–53Deploying to containers and Kubernetesdocker_container, docker_compose_v2, k8s (apply/wait), helm; the boundary between Ansible and GitOpsWhere modules run: Docker API / kube-apiserverRun myapp in local Docker; deploy a Deployment to a kind cluster
853–60Comprehensive architecture reviewfailure mode analysis, review scorecard, incident drills, interactive troubleshooting treeReview scorecard + incident drill simulationRun an FMEA on this lesson’s architecture
—After classCheat sheet · Capstone labZero-downtime rolling release and rollback for nginx + 2 app nodes + PostgreSQLFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / keywordsLab
Multi-environment, multi-tier inventory design✓······✓ansible-inventory --graph/--hostM1
Generate configuration from inventory✓✓✓✓·✓··groups,hostvars,templateM2/M3
Config validation and safe reload·✓✓✓·✓·✓validate, handlers,state: reloadedM2
systemd service deployment··✓··✓··systemd_service,pip,file state=linkM3
Database automation and backup/restore···✓···✓postgresql_*,cron,pg_dumpM4
Batched rolling updates and failure thresholds····✓✓·✓serial,max_fail_percentage,orderM5
Zero downtime and automatic rollback·✓✓·✓✓·✓delegate_to,run_once,uri,block/rescueM6 + capstone lab
Container / Kubernetes deployment······✓·docker_container,k8s,helmM7
Architecture review and incident drills···✓·✓·✓FMEA, RunbookM8

Topics not covered in this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
Molecule testing, ansible-lint rules, performance tuning (forks, pipelining, current status of Mitogen)Belongs to the troubleshooting and optimization topicsHour 7
AWX / AAP job templates, approvals, Event-Driven Ansible auto-triggered releasesThe previous lesson covered the platform; this lesson focuses on the release logic of the playbook itselfHour 5
PostgreSQL streaming replication, Patroni high availability, PITR (WAL archiving)Database HA needs its own course; this lesson only covers a single primary + logical backups + restore drillsPostgreSQL official High Availability chapter
TLS certificate automation (ACME), WAF, cloud load balancers (Azure LB / AWS ALB)This lesson simulates a three-tier architecture in local containersthe third and fourth 1-hour sessions (cloud platforms);K8s course Hour 3 (Gateway API)
Kubernetes’ own release strategies (maxSurge, PDB, Argo Rollouts)m7 only covers “driving K8s with Ansible”K8s course, Hour 2

How to use this courseware

10 pages per module
Theory · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Audio · Video. We recommend reading “Theory” and “Animation” first, then doing the “Lab”. The m5 animation is the core of this lesson, so be sure to work through its parameters by hand.
Learning progress
A quiz score of ≥ 70% or clicking “Mark module complete” counts toward progress. It is saved in this browser (cleared on refresh if local storage is disabled).
Chinese audio
The “Audio” page uses the browser’s built-in Web Speech API (en-US) to read the narration aloud. Without a Chinese voice pack, the narration script can still be read or passed to a TTS tool.
Version notes This lesson is based on ansible-core 2.21 (2026-05 GA, EOL 2027-11) and Ansible community package 14.x as the baseline. Control node Python 3.12–3.14, managed node Python 3.9–3.14 (Ubuntu 24.04 ships with 3.12). Collection versions follow the 2026-11 docs.ansible.com pages: community.postgresql 4.2.0, community.docker 5.4.0 (Compose only remains the docker_compose_v2 series), kubernetes.core 6.6.0 (the helm module has been adapted to Helm 4,atomic gets converted to --rollback-on-failure), community.general 13.5.1 (haproxy module). Template engine changes since core 2.19 (data tagging, and conditional expressions that must evaluate to booleans) affect when syntax. All examples in this lesson follow the new rules.

Module 0 · Preparation: multi-tier sample project (complete before class)

Four Ubuntu 24.04 containers that run systemd “like a VM”: lb1, app1, app2, db1; the control node reuses the pipx environment from earlier lessons
Before class ≈ 12 minDocker Engine 29 · Ubuntu 24.04
Prerequisites
  • CompletedHour 5(automation operations); the control node has already pipx install --include-deps ansible installed Ansible community package 14.x (including ansible-core 2.21).
  • Workstation: Ubuntu 24.04 LTS (Azure VM or local machine), Docker Engine 29 (installed in the Docker lesson), at least 4 GiB of free memory.
  • The node1–node3 containers used in earlier lessons are lightweight nodes with “sshd only, no systemd”; this lesson needs real systemd (nginx, gunicorn, and PostgreSQL all run as systemd services), so we build a new set of nodes that run /sbin/init nodes.

Link to the previous lesson

ReuseNotes
SSH key ~/.ssh/ansible_labThe ed25519 key generated in lesson 1; if it has been deleted, step 1 below will regenerate it
Docker networking approachNodes reach each other by container name (Docker’s built-in DNS); the control node connects via SSH through port mappings
myappReuse the Flask + gunicorn app from the Docker lesson; in this lesson, the Redis counter is replaced with PostgreSQL a table hits, and add /readyz
VaultThe database password is handled with the method from lesson 2: ansible-vault encrypt_string saved in

Step 1: Build a managed-node image with systemd + sshd

mkdir -p ~/ansible-lab/part6/node-image && cd ~/ansible-lab/part6/node-image
test -f ~/.ssh/ansible_lab || ssh-keygen -t ed25519 -N '' -f ~/.ssh/ansible_lab -C ansible-lab
cp ~/.ssh/ansible_lab.pub ./id_ed25519.pub

cat > Dockerfile <<'EOF'
FROM ubuntu:24.04
ENV container=docker DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
      systemd systemd-sysv dbus openssh-server sudo python3 python3-apt \
      ca-certificates curl acl iproute2 cron less \
 && apt-get clean && rm -rf /var/lib/apt/lists/*
RUN useradd -m -s /bin/bash ansible \
 && echo 'ansible ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/ansible \
 && chmod 440 /etc/sudoers.d/ansible \
 && install -d -m 700 -o ansible -g ansible /home/ansible/.ssh
COPY --chown=ansible:ansible id_ed25519.pub /home/ansible/.ssh/authorized_keys
RUN chmod 600 /home/ansible/.ssh/authorized_keys \
 && systemctl enable ssh.service cron.service \
 && systemctl mask systemd-logind.service getty.target
STOPSIGNAL SIGRTMIN+3
CMD ["/sbin/init"]
EOF
docker build -t ansible-node-systemd:24.04 .

Why install acl: m4 needs become_user: postgres (switching from the ansible user to another non-root user), and Ansible needs setfacl so that postgres can read the temporary module files it uploads; otherwise you get “Failed to set permissions on the temporary files…”. STOPSIGNAL SIGRTMIN+3 is the systemd convention’s “graceful shutdown” signal, letting docker stop shut down services properly.

Step 2: Start 4 nodes

docker network create ansnet 2>/dev/null || true
run_node(){  # $1=name  $2=SSH port  rest=extra arguments
  docker run -d --name "$1" --hostname "$1" --network ansnet \
    --privileged --cgroupns=private --tmpfs /run --tmpfs /run/lock \
    -p "127.0.0.1:$2:22" "${@:3}" ansible-node-systemd:24.04
}
run_node lb1  2221 -p 8080:80        # load balancer, exposed externally on 8080
run_node app1 2222
run_node app2 2223
run_node db1  2224
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
docker exec app1 systemctl is-system-running --wait
NAMES   STATUS          PORTS
db1     Up 8 seconds    127.0.0.1:2224->22/tcp
app2    Up 9 seconds    127.0.0.1:2223->22/tcp
app1    Up 10 seconds   127.0.0.1:2222->22/tcp
lb1     Up 11 seconds   0.0.0.0:8080->80/tcp, 127.0.0.1:2221->22/tcp
running
Security note--privileged Lets systemd inside the container manage its own cgroups, but also gives the container nearly the host’s root capabilities—use only on disposable lab machines. If you see degraded, use docker exec app1 systemctl --failed to list failed units (in containers, these are usually hardware-related units and can be ignored). Alternatives: Use multipass (multipass launch 24.04 -n app1 -c 1 -m 1G) or 4 Standard_B1s small Azure VMs (about US$0.01/hour each; delete after class az group delete -n rg-ansible-lab --yes --no-wait). In the inventory, you only need to replace ansible_host/ansible_port with the VM addresses.

Step 3: Generate the project skeleton

cd ~/ansible-lab/part6
mkdir -p inventories/{staging,production}/{group_vars,host_vars} \
         roles/{common,nginx_lb,myapp,postgresql}/{tasks,templates,handlers,defaults,files} \
         files/myapp collections

cat > ansible.cfg <<'EOF'
[defaults]
inventory = inventories/staging/hosts.yml
roles_path = roles
private_key_file = ~/.ssh/ansible_lab
remote_user = ansible
# lab only: disable host key checking
host_key_checking = False
# the default callback shows results in YAML format, which is easier to read
callback_result_format = yaml
forks = 10
interpreter_python = auto_silent

[ssh_connection]
pipelining = True
EOF

ansible-galaxy collection list | grep -E 'community\.(postgresql|general|docker)|kubernetes\.core'
community.docker             5.4.0
community.general            13.5.1
community.postgresql         4.2.0
kubernetes.core              6.6.0

Community package 14.x already bundles these collections. If you only installed ansible-core, run ansible-galaxy collection install community.postgresql community.general community.docker kubernetes.core, and pin the version to collections/requirements.yml (see m1).

Step 4: myapp source code (PostgreSQL version)

import os, socket
from flask import Flask, jsonify
import psycopg

app = Flask(__name__)
VERSION = os.environ.get("APP_VERSION", "dev")
DSN = os.environ.get("DATABASE_URL", "")
BROKEN = os.environ.get("APP_BROKEN", "0") == "1"     # used to demonstrate a “bad version”

def db():
    return psycopg.connect(DSN, connect_timeout=2)

@app.get("/")
def index():
    with db() as conn:                                  # automatically commits on exiting the with block
        n = conn.execute("INSERT INTO hits(host, version) VALUES (%s, %s) RETURNING id",
                         (socket.gethostname(), VERSION)).fetchone()[0]
    return jsonify(host=socket.gethostname(), version=VERSION, hits=n)

@app.get("/healthz")                                    # liveness: checks only the process itself
def healthz():
    if BROKEN:
        return jsonify(status="broken", version=VERSION), 500
    return jsonify(status="ok", version=VERSION)

@app.get("/readyz")                                     # readiness: dependencies (the database) are available
def readyz():
    try:
        with db() as conn:
            conn.execute("SELECT 1")
        return jsonify(status="ready", version=VERSION)
    except Exception as e:
        return jsonify(status="db-unavailable", error=str(e)), 503
flask>=3.1,<4
gunicorn>=23,<24
psycopg[binary]>=3.2,<4

In production, use pip-compile --generate-hashes to generate a hash-pinned lock file, so the two nodes don’t install different dependency versions (m3 production case).

Warm-up: answer from memory (30 seconds)

When does a handler run by default?

At the end of each play’s tasks section (and of its pre_tasks, roles, and post_tasks sections), it runs once; to run it immediately, use meta: flush_handlers. This foreshadows why, in m6, the health check must come after the flush.

What is Ansible’s default execution strategy?

strategy: linear: each task runs on all hosts (limited by forks) before moving on to the next task. serial instead splits hosts into batches, running each batch through the entire play before moving to the next batch. This is the star of m5.

Environment self-check checklist

Module 1 · Multi-tier application architecture and inventory design

00:00 – 07:00 · The inventory answers “which machines exist, what role each plays, and which environment they belong to”; group_vars answers “which parameters this tier or environment uses”
7 minansible-core 2.21★★★★★
Learning objectives
  • Design groups along two dimensions, “functional tier (lb/app/db) × environment (staging/production)”, and separate environments using separate inventory directories for isolation, rather than mixing them in one file.
  • Name the 8 most commonly used layers of variable precedence and determine where a variable ultimately comes from; use ansible-inventory --host and debug: var= to verify.
  • Write the site.yml, and understand import_playbook (static) execution order and --tags/--limit combinations.
Prerequisites: Lesson 1’s inventory and ad-hoc commands; lesson 2’s roles and Vault. Importance:★★★★★ (once the inventory structure is settled, every later playbook depends on it)

What: what a multi-tier application looks like to Ansible

To Ansible, “architecture” is groups and variables (vars) combined. The myapp in this lesson has three tiers:

TierGroup nameHostsServiceExternal port
Load balancer tierlblb1nginx (can be replaced with HAProxy)80 (host port 8080)
Application tierappapp1, app2myapp (gunicorn, systemd service)8000 (internal network only)
Data tierdbdb1PostgreSQL 16 (Ubuntu 24.04 repository version)5432 (accessible only to app)

In addition to the functional groups, add two kinds of “cross-cutting” groups: Business group myapp (all hosts of this application), and environment groups staging / production. A host can belong to several groups at once, and variables are merged by precedence.

Why: why the inventory deserves careful design

  • Template data sources: the nginx upstream backend list, PostgreSQL pg_hba allowed sources, and the application’s DATABASE_URL should all be derived from groups['app'],groups['db'] . Adding an app3 means changing only the inventory, not the templates.
  • Environment isolation: staging and production are split into two directories (-i inventories/production), so a single command cannot hit both environments; the production directory can also have stricter file permissions and its own Vault password.
  • Release granularity:--limit app,--limit 'app:&production' this kind of pattern depends on group design.

How: directory layout and variable precedence

part6/
├── ansible.cfg
├── collections/requirements.yml      # pinned collection versions
├── inventories/
│   ├── staging/
│   │   ├── hosts.yml                 # hosts and groups
│   │   ├── group_vars/
│   │   │   ├── all/main.yml          # environment level: env_name, myapp_version, domain…
│   │   │   ├── all/vault.yml         # environment-level secrets (encrypted with ansible-vault)
│   │   │   ├── lb.yml                # load balancer tier parameters
│   │   │   ├── app.yml               # application tier parameters
│   │   │   └── db.yml                # data tier parameters
│   │   └── host_vars/app2.yml        # per-host exception
│   └── production/                   # identical structure, different values
├── roles/{common,nginx_lb,myapp,postgresql}/
├── site.yml                          # orchestrates all tiers
├── db.yml  app.yml  lb.yml           # one playbook per tier
├── rolling_update.yml                # m5/m6 zero-downtime release
└── rollback.yml

Note: a group variable can be either a single file group_vars/all.yml, or a directory group_vars/all/ (all YAML files in the directory load in filename order). The team should agree on one form only, to avoid defining the same variable in two places. Use the directory form when secrets need separate encryption: all/main.yml + all/vault.yml, as created in the lab.

Variable precedence (from lowest to highest; excerpt of the most commonly used of the official 22 layers)

#SourceUse in this lesson
1role defaults (roles/x/defaults/main.yml)“safe defaults”, such as gunicorn_workers: 2
2inventory group_vars/allEnvironment level: env_name,myapp_version
3next to the playbook directory group_vars/allrarely used; the team should agree to use only the inventory side
4inventory group_vars/<group> (child groups override parent groups; at the same level, groups are applied in alphabetical order, with later ones overriding)Hierarchical parameters: app.yml,db.yml
5inventory host_vars/<host>Exception: app2 has less memory, so fewer workers
6play vars / vars_filesLocal constants in the release playbook
7role vars, block/task varsInternal constants that “should not be overridden”
8set_fact / registerComputed at runtime: previous version number
highestextra vars (-e)specified at release time -e myapp_version=v2

When sibling groups conflict, it can be set in group variables ansible_group_priority (it can only be set in the inventory; the higher value is merged later and wins).

When: when to split and when to merge

  • Environment differences are only values (replica count, domain, sizing) → the same roles, different inventory directories.
  • Environment differences are structural (production has 2 LBs + keepalived, staging has only 1) → still the same roles, expressed through group membership counts, with templates using loops to avoid when: env == 'prod' proliferating branches.
  • Hosts come from the cloud→ use a dynamic inventory plugin (from lessons 3 and 4’s azure_rm/aws_ec2), via keyed_groups/groups mapping cloud tags to lb/app/db groups, keeping the group_vars structure unchanged.

Comparison with similar approaches

Ansible inventory + group_varsTerraform workspace / directoriesHelm values per environment
Describesexisting machines and their rolescloud resources to be createdK8s object template parameters
Environment isolationseparate inventory directoriesseparate state (directories recommended over workspaces)values-prod.yaml
Topology datagroups/hostvars directly available in templatesoutput → passed to the Ansible dynamic inventoryService DNS; usually not needed
Common misconceptions① “host_vars beats extra vars”—wrong; -e extra vars are always the highest, so don’t pass values in -e them that should be decided by the inventory (they override every host’s per-host configuration). ② “Group_vars file names can be arbitrary”—the file name (or directory name) must exactly match the group name,apps.yml will not be picked up by the app group, and no error is reported. ③ “Using [prod]/[staging] to tell environments apart is enough”—one hosts: app run will hit both environments at once.

Architecture diagram: three-tier myapp and the Ansible control node

Users / load testcurl :8080 lb1 · group lbnginx upstream myappGenerated from groups['app']:80 app1 · group appmyapp.service (gunicorn):8000 /healthz /readyz app2 · group appmyapp.service (gunicorn):8000 /healthz /readyz db1 · group dbPostgreSQL 16pg_hba allows the app group:5432 + backup cron Control node (ansible-core 2.21)SSH → 127.0.0.1:2221–2224 Docker network ansnet: nodes reach each other by container name (lb1/app1/app2/db1)
Figure 1-1 Three-tier myapp: each tier is one inventory group; all cross-tier connections are derived from groups/hostvars

Data flow: where variables come from and how they merge

role defaults group_vars/all group_vars/app host_vars/app2 -e extra vars VariableManagerMerged by precedence (later overrides earlier)hostvars['app2'] Jinja2 rendering (on the control node) nginx.conf.j2: {% for h in groups['app'] %} myapp.env.j2: DATABASE_URL=…@{{ groups['db'][0] }} pg_hba: address = hostvars[h].ansible_default_ipv4 → rendered result sent to the managed node over SSH (the template module renders on the control node)
Figure 1-2 Variables are merged on the control node; templates are also rendered there, and the managed node only receives the final file

Interactive: Variable Precedence Resolver

Select a host and toggle whether to pass -e, and observe each variable’s final value and the layer it came from. This is exactly what Ansible’s VariableManager.get_vars() does for each host: it merges dictionaries in precedence order, with later merges overriding. The terminal below shows real commands and output you can use to verify this.

Click a host to start.
$ ansible-inventory --host app2

Core commands and parameters

CommandPurposeKey parameters / notes
ansible-inventory --graphShow groups and hosts as a tree-i inventories/production,--vars also show variables
ansible-inventory --host app2Show a host’s merged inventory variablesexcludes role defaults / play vars (view those at runtime)
ansible-inventory --list -yExport the full inventory (YAML)Troubleshoot dynamic inventory plugin results
ansible app -m ansible.builtin.debug -a var=myapp_versionView variables at runtimeShows the merged result of extra vars and group_vars
ansible-playbook site.yml --list-hosts --list-tasksDoes not execute; only lists the hosts and tasks that would be matchedRequired before release
ansible-playbook site.yml --limit 'app:&staging'Limit hosts (intersection &, exclude !)Quote to avoid shell parsing
ansible-galaxy collection install -r collections/requirements.ymlInstall pinned-version collections per the requirements file-p ./collections install into the project
all:
  vars:
    ansible_host: 127.0.0.1          # lab: all nodes are reached via port mappings
  children:
    lb:
      hosts:
        lb1:  { ansible_port: 2221 }
    app:
      hosts:
        app1: { ansible_port: 2222 }
        app2: { ansible_port: 2223 }
    db:
      hosts:
        db1:  { ansible_port: 2224 }
    myapp:                            # business dimension
      children: { lb: {}, app: {}, db: {} }
    staging:                          # environment dimension
      children: { myapp: {} }
ansible-inventory --graph
@all:
  |--@ungrouped:
  |--@lb:
  |  |--lb1
  |--@app:
  |  |--app1
  |  |--app2
  |--@db:
  |  |--db1
  |--@myapp:
  |  |--@lb:
  ...
  |--@staging:
  |  |--@myapp:
  ...

How to verify: Every functional group appears under staging . Common error: In a YAML inventory, hosts: written as a list (- app1): this reports “Invalid "hosts" entry … expected a dictionary”. Production use: Include --graph output in the PR description, so reviewers can see at a glance which hosts the change affects.

collections:
  - name: community.postgresql
    version: ">=4.2.0,<5.0.0"
  - name: community.general
    version: ">=13.0.0,<14.0.0"
  - name: community.docker
    version: ">=5.4.0,<6.0.0"
  - name: kubernetes.core
    version: ">=6.6.0,<7.0.0"

site.yml: orchestration in dependency order

---
# order: base first → database ready → application ready → finally point the LB at the application
- import_playbook: common.yml
- import_playbook: db.yml
- import_playbook: app.yml
- import_playbook: lb.yml
---
- name: application tier
  hosts: app
  become: true
  roles:
    - role: myapp
      tags: [app]

import_playbook is static import: expanded at parse time,--list-tasks all tasks are visible,--tags app and precise filtering is possible. import_playbook It can only appear at the top level; it cannot go inside a play, and you cannot use a loop with it.

Lab 1: Create staging/production inventories and verify variable sources (about 6 min)

Write the staging inventory (content in the “Commands” page’s hosts.yml), then create the layered variables:
cd ~/ansible-lab/part6
mkdir -p inventories/staging/group_vars/all
cat > inventories/staging/group_vars/all/main.yml <<'EOF'
env_name: staging
myapp_version: v1
myapp_port: 8000
myapp_db_name: myapp
myapp_db_user: myapp
myapp_db_host: "{{ groups['db'][0] }}"     # derived from the inventory, not hard-coded
EOF
cat > inventories/staging/group_vars/app.yml <<'EOF'
gunicorn_workers: 3
gunicorn_timeout: 30
EOF
cat > inventories/staging/group_vars/lb.yml <<'EOF'
nginx_worker_connections: 1024
lb_public_port: 80
EOF
cat > inventories/staging/group_vars/db.yml <<'EOF'
postgresql_version: 16
postgresql_backup_dir: /var/backups/postgresql
postgresql_backup_keep_days: 7
EOF
cat > inventories/staging/host_vars/app2.yml <<'EOF'
gunicorn_workers: 2          # app2 has a smaller spec (example: host-level exception)
EOF
Store the database password in Vault (password file for lab use only):
echo 'lab-vault-pass' > ~/.ansible_lab_vault && chmod 600 ~/.ansible_lab_vault
ansible-vault encrypt_string --vault-password-file ~/.ansible_lab_vault \
  'S3cure-Lab-Pass' --name vault_myapp_db_password \
  > inventories/staging/group_vars/all/vault.yml
echo 'myapp_db_password: "{{ vault_myapp_db_password }}"' >> inventories/staging/group_vars/all/main.yml
echo 'vault_password_file = ~/.ansible_lab_vault' >> ansible.cfg   # appending after [ssh_connection] will NOT work! See the note below

⚠ vault_password_file belongs to [defaults] section. The command above >> appends it to the end of the file, in the [ssh_connection] section, which means it will not take effect—this is a deliberate pitfall: manually move this line to [defaults] under the correct section before continuing. vault_ A prefix plus a plaintext variable that references it is the officially recommended “greppable secret” pattern.

Connectivity and inventory verification:
ansible all -m ansible.builtin.ping -o
ansible-inventory --host app2 | python3 -m json.tool | head -20
ansible app -m ansible.builtin.debug -a "msg={{ gunicorn_workers }} {{ myapp_db_host }}"
lb1 | SUCCESS => {"changed": false,"ping": "pong"}
app1 | SUCCESS => {"changed": false,"ping": "pong"}
app2 | SUCCESS => {"changed": false,"ping": "pong"}
db1 | SUCCESS => {"changed": false,"ping": "pong"}
...
app1 | SUCCESS => { "msg": "3 db1" }
app2 | SUCCESS => { "msg": "2 db1" }

The ping module’s discovered_interpreter_python should be /usr/bin/python3. myapp_db_password Showing plaintext indicates Vault decryption works; if you see “Attempting to decrypt but no vault secrets found”, the previous step’s vault_password_file is still in the wrong section.

Copy out the production inventory (only change the values; the structure stays the same):
cp -r inventories/staging/. inventories/production/
sed -i 's/env_name: staging/env_name: production/' inventories/production/group_vars/all/main.yml
sed -i 's/^    staging:/    production:/' inventories/production/hosts.yml
ansible-inventory -i inventories/production --graph | tail -3
  |--@production:
  |  |--@myapp:
  |  |  |--@lb:

In the lab, both environments point to the same set of containers, just to practice the structure; a real production inventory should point to different hosts and use a different Vault password (--vault-id prod@prompt).

Write placeholders for site.yml and each tier’s playbook, and use --list-hosts to check:
for l in common:myapp db:db app:app lb:lb; do n=${l%%:*}; g=${l##*:}
cat > $n.yml <<EOF
---
- name: $n tier
  hosts: $g
  become: true
  tasks:
    - ansible.builtin.debug: { msg: "TODO: $n on {{ inventory_hostname }}" }
EOF
done
printf -- '---\n- import_playbook: common.yml\n- import_playbook: db.yml\n- import_playbook: app.yml\n- import_playbook: lb.yml\n' > site.yml
ansible-playbook site.yml --list-hosts
playbook: site.yml
  play #1 (myapp): common tier	TAGS: []
    pattern: ['myapp']
    hosts (4):
      app1
      ...
  play #4 (lb): lb tier	TAGS: []
    pattern: ['lb']
    hosts (1):
      lb1
Cleanup: this lab’s files are the foundation for later modules,do not delete them.

Case 1: a single -e override made the two environments’ configs identical

Problem: The on-call engineer ran, to temporarily increase workers, ansible-playbook app.yml -e gunicorn_workers=8, which also overrode the 2 set in host_vars for the small-spec machine to 8, so the small machine ran out of memory (OOM). Fix: Rule: -e Use it only for variables with “this release” semantics (version numbers, switches); capacity parameters may only be changed in group_vars/host_vars via a PR. Configuration: Use in CI grep -E '\-e (gunicorn|nginx)_' to block job templates. Limitation: AWX job templates’ “Prompt on launch” also supplies extra vars, so the same constraints are needed.

Case 2: migrating from a static inventory to an Azure dynamic inventory without changing the playbook

Problem: Application nodes are now auto-scaled by VMSS, so the static hosts.yml is no longer accurate. Fix: Use the azure.azcollection.azure_rm inventory plugin, grouping by VM tag tier=app to generate groups: keyed_groups: [{prefix: "", separator: "", key: "tags.tier"}]; the group_vars directory is kept as is. Configuration: Place under inventories/production azure_rm.yml and group_vars. Limitation: Group names come from tag values; a misspelled tag makes hosts “disappear” without any error. Add ansible-inventory --graph | grep -c an assertion on the host count in CI.

Case 3: variable conflict between sibling groups

Problem: A host belongs to both app and monitoring groups, and both group_vars define log_level, and the result depends on alphabetical order (monitoring comes later and wins). Fix: Prefix the variables (myapp_log_level), or set it in the inventory for the app group ansible_group_priority: 10. Limitation:ansible_group_priority It can only be set in inventory files or plugins; setting it in group_vars files has no effect.

Common errors and fixes

[WARNING]: Could not match supplied host pattern, ignoring: app

Cause: The wrong inventory was used (ansible.cfg not taking effect, or -i is mistyped), or the group name is misspelled.

ansible --version | grep "config file"
ansible-inventory --graph

Fix: Confirm you run from the project directory (ansible.cfg is searched in ANSIBLE_CONFIG → current directory → ~/.ansible.cfg → /etc/ansible/ansible.cfg ; it is ignored if the current directory is globally writable).

'myapp_db_host' is undefined / AnsibleUndefinedVariable

Cause: group_vars file name does not match the group name (e.g. apps.yml), or the file is in the playbook directory rather than the inventory directory, yet -i points to another directory.

ansible-inventory --host app1 | grep myapp_
ls inventories/staging/group_vars/

Fix: make the file name equal the group name; all put group variables in group_vars/all.yml or group_vars/all/*.yml —pick one.

ERROR! Attempting to decrypt but no vault secrets found

Cause: group_vars contains Vault-encrypted content, but no password was provided.

Fix:--vault-password-file,--ask-vault-pass, or in the [defaults] section, set vault_password_file (note the section name; see step 2 of the lab).

ERROR! 'import_playbook' is not a valid attribute for a Play

Cause: Indenting import_playbook into a play (or placing it in the same list item as hosts: ).

Fix:import_playbook It must be a top-level list item: - import_playbook: db.yml.

Conditional result (…) was derived from value of type 'str' … / Conditional is marked as unsafe

Cause: Starting with ansible-core 2.19, the template engine is stricter: when the result must be a boolean, for example when: env_name (strings) are no longer implicitly treated as truthy values.

Fix: Write an explicit comparison: when: env_name == 'production',when: some_list | length > 0. See the core 2.19 porting guide.

Command-line questions
1. Without executing any tasks, list which hosts site.yml would match in the production environment.
ansible-playbook -i inventories/production site.yml --list-hosts
2. Check the gunicorn_workers value for app2 at runtime (including extra vars).
ansible app2 -m ansible.builtin.debug -a var=gunicorn_workers -e gunicorn_workers=5
# output 5: extra vars override the 2 from host_vars
Scenario analysis
The team wants to add an app3 to production and wants the nginx, pg_hba, and monitoring configs to update automatically. Which files need to change? If templates must change, explain what is wrong with the design.

Just add app3 to the inventories/production/hosts.yml of the app group (adding host_vars if needed), then run site.yml (or run db.yml to refresh pg_hba, app.yml to deploy app3, and lb.yml to refresh the upstream, in that order). If the template must change, it hard-codes hostnames or IPs; change it to loop over groups['app'] and take addresses from hostvars hostvars instead.

Verified instructional videos

▶
Ansible 101 - Episode 2 - Ad-hoc tasks and Inventory — Jeff Geerling
2020 live series · English · Basics of inventories and groups; useful as a review for this module (recorded earlier, so for new ansible-core 2.21 behavior, follow this lesson)
▶
Ansible 101 - Episode 12 - Real-world Ansible Playbooks — Jeff Geerling
2020 · English · Directory organization and multi-playbook orchestration in real projects

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided, which can be passed to a video tool.

Shot 1 · 0–20s
Visual: the three boxes lb, app, and db light up in turn, each with a group-name label.
Narration: To Ansible, architecture is groups. The load balancer, application, and database are each one group.
Shot 2 · 20–45s
Visual: two folders, staging and production, side by side with identical structure; only the numbers differ.
Narration: Environments are isolated in separate directories, so one command cannot hit both environments.
Shot 3 · 45–70s
Visual: five layers of transparent film stacked: role defaults, all, app, host_vars, extra vars; the value on the top layer shows through.
Narration: Variables are merged by precedence; the higher the layer, the higher its priority. Extra vars always win.
Shot 4 · 70–90s
Visual: app3 is added to the inventory, and a new server line automatically appears in the nginx config.
Narration: Good inventory design means scaling out changes only the inventory, not the templates.
or score ≥ 70% on the quiz

Module 2 · Load balancer tier: nginx / HAProxy

07:00 – 14:00 · Backend lists generated from the inventory, config validated before it is written, and config changes applied with reload rather than restart
7 minnginx (Ubuntu 24.04 repository) · HAProxy 2.8community.general.haproxy★★★★☆
Learning objectives
  • Write an upstream / backend template that iterates over groups['app'] the group, and support marking specified hosts as down (preparing for m6’s removal).
  • Use template ’s validate parameter, which runs before the file is replaced, to run nginx -t -c %s / haproxy -c -f %s, so bad config is never written to disk.
  • Explain the difference between reload (SIGHUP, handover between old and new workers) and restart (stop then start, listening port briefly closed), and use a handler to implement “reload only on change”.
  • Understand the HAProxy runtime API (admin socket) and the community.general.haproxy module’s enabled / disabled / drain states.
Prerequisites: the inventory from m1; the handlers from lesson 1. Importance:★★★★☆

What: what the LB tier must manage in automation

  • Backend members: which application nodes receive traffic (from groups['app']), and whether they are currently removed (down / MAINT).
  • Health checks: open-source nginx only has passive checks (max_fails + fail_timeout: after several real request failures, the node is temporarily skipped); HAProxy has active checks (option httpchk, periodically requesting /readyz). nginx’s active health checks (health_check) and runtime API belong to the commercial NGINX Plus.
  • Retry policy: proxy_next_upstream error timeout http_502 http_503 lets a request move to the next backend when one backend fails; this is the second safeguard for “users feel nothing during a release”.

Why: why the template + validate + reload trio

The LB is the single entry point for all site traffic. A typo (a missing semicolon) that takes effect via restart means nginx won’t start,and the whole site goes down. Each piece of the trio solves a different problem: the template keeps the backend list in sync with the inventory; validate → bad config stays off disk; reload → existing connections survive when new config takes effect.

How: the real mechanics of validate and reload

StepWhere it happensDetails
1. Render the templateControl nodeJinja2 reads groups/hostvars produces text
2. TransferSSH → temp directory on lb1First upload to ~/.ansible/tmp/…/source, not overwrite the target directly
3. Validatelb1Run validate command; %s is replaced with the temp file path; non-zero return code → task fails, target file unchanged
4. Atomic replacementlb1After validation passes, rename atomically replaces the target; backup: true a timestamped backup of the old file is kept when
5. Notify handlerThe control node records the change;the handler is notified only when changed the file changes, and runs at the end of the section reload nginx
6. reloadlb1systemctl reload nginx → master receives SIGHUP → parses the new config → starts new workers → tells old workers to exit gracefully (after finishing their current requests)
Two pitfalls with validate① %s is a temporary file, so relative include paths are resolved from the temp file’s directory resolution (nginx uses the directory of the file given by -c as the config prefix), so templates must use absolute paths for includes: include /etc/nginx/mime.types;. ② It can only validate a “complete” config file. conf.d/ A fragment on its own inside nginx -t -c will fail (missing events/http block), so this lesson has Ansible manage the entire nginx.conf; if you must manage fragments, add a nginx -t task after the template, together with backup rollback.

When: nginx or HAProxy

nginx (open source)HAProxy
Active health checksNone (only in Plus)Yes: option httpchk + http-check send/expect
Remove nodes at runtimechange config and add down + reloadadmin socket: disable server myapp/app1, no file changes needed
Ansible moduletemplate + systemd_servicetemplate + community.general.haproxy
reloadSIGHUP, handover between old and new workersseamless reload in master-worker mode (the Ubuntu unit uses -Ws)
Best forneeding static files, reverse proxy, and caching togetherpure L4/L7 load balancing; needing fine-grained health checks and connection draining
Common misconceptions① “systemctl reload “Validation failure takes nginx down”—no: when the new config fails to parse, the master keeps the old config and only logs the error to error.log; however, the Ubuntu reload command itself may return 0,so you must validate before reloading with. ② “Adding max_fails gives you health checks”—that is passive: the first failed request still hits the bad node; only with proxy_next_upstream can it be transparent to users. ③ “Handlers run immediately”—by default, they run only at the end of the current section.

Architecture diagram: execution path of template + validate + handler

Control nodenginx.conf.j2for h in groups['app']→ render text SSH lb1 temp file~/.ansible/tmp/…/sourcevalidate:nginx -t -c %s rc=0 rc≠0 Task fails/etc/nginx/nginx.conf unchanged Atomic replacerename → nginx.confbackup: nginx.conf.123.@… notify handlerAt end of sectionstate: reloaded nginx master (SIGHUP)parse new config → fork new workers (new upstream)Old workers: stop accepting, exit after finishing in-flight requestsListening socket always held by master → no interruption
Figure 2-1 validate runs before the atomic replacement; the handler reloads only when the file actually changes

Comparison: connections during reload vs. restart

reload Old worker: handles in-flight requests until completion New worker: receives all new connections (listening socket stays open) restart Old process: receives stop signal Port closed: connections refused New process: if the config is broken, it won’t start at all t0: config changeTime →
Figure 2-2 During reload, the master holds the listening port throughout; restart creates a window of refused connections, and a config error causes a full outage

Interactive: upstream generator + reload / restart comparison

Check the “app hosts in the inventory” and “removed (down)” hosts; the rendered template result updates live on the left. Check “Inject syntax error” to simulate someone breaking the template. Then click “Apply (reload)” or “Apply (restart)” and observe whether validate blocks it and whether in-flight requests are interrupted.

Inventory groups['app']
nginx_down_hosts

        
In-flight requests (one connection per cell)
Change the options on the left, then click Apply.
$ ansible-playbook lb.yml --diff

Core modules and parameters

Module / commandPurposeKey parameters
ansible.builtin.templateRender Jinja2 and atomically replacevalidate (including %s),backup,mode,lstrip_blocks
ansible.builtin.systemd_serviceManage systemd services (old name systemd still works)state: started/reloaded/restarted,enabled,daemon_reload
ansible.builtin.aptInstall packagesupdate_cache,cache_valid_time
community.general.haproxyEnable/disable/drain backends via the admin socketstate: enabled/disabled/drain,host,backend,socket (default /var/run/haproxy.sock),wait,drain,weight
ansible-playbook lb.yml --check --diffDry-run and show the configuration difftemplate can also show a diff in check mode

roles/nginx_lb

nginx_worker_connections: 1024
lb_public_port: 80
myapp_port: 8000
nginx_down_hosts: []        # passed in by rolling_update.yml for the current batch’s nodes during the m6 release
# {{ ansible_managed }}
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;     # absolute path: during validate, the temp file directory is used as the prefix

events { worker_connections {{ nginx_worker_connections }}; }

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    log_format upstreamlog '$remote_addr "$request" $status up=$upstream_addr rt=$upstream_response_time';
    error_log /var/log/nginx/error.log;

    upstream myapp {
{% for h in groups['app'] %}
        server {{ hostvars[h].myapp_listen_host | default(h) }}:{{ myapp_port }} max_fails=2 fail_timeout=5s{{ ' down' if h in nginx_down_hosts else '' }};   # {{ h }}
{% endfor %}
        keepalive 16;
    }

    server {
        listen {{ lb_public_port }} default_server;
        access_log /var/log/nginx/myapp.log upstreamlog;
        location = /lb-health { return 200 "ok\n"; }
        location / {
            proxy_pass http://myapp;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_connect_timeout 2s;
            proxy_next_upstream error timeout http_502 http_503;
        }
    }
}
- name: install nginx
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: remove the distribution default site (otherwise it conflicts with default_server)
  ansible.builtin.file:
    path: /etc/nginx/sites-enabled/default
    state: absent
  notify: reload nginx

- name: render nginx.conf (validated with nginx -t before writing to disk)
  ansible.builtin.template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
    owner: root
    group: root
    mode: "0644"
    backup: true
    validate: nginx -t -c %s
  notify: reload nginx

- name: nginx running and enabled at boot
  ansible.builtin.systemd_service:
    name: nginx
    state: started
    enabled: true
- name: reload nginx
  ansible.builtin.systemd_service:
    name: nginx
    state: reloaded

How to verify:curl -s localhost:8080/lb-health returns ok; docker exec lb1 nginx -T | grep -A4 "upstream myapp" shows two server entries. Common errors: validate reports “host not found in upstream "app1:8000"”—nginx resolves upstream hostnames while parsing the config, so lb1 must be able to resolve app1 (same Docker network, or /etc/hosts). Production use: Run in CI against the rendered template output nginx -t (containerized nginx) as a PR check.

HAProxy version (optional replacement)

global
    log /dev/log local0
    stats socket /run/haproxy/admin.sock mode 660 level admin   # runtime API, requires admin level
    master-worker

defaults
    mode http
    timeout connect 2s
    timeout client 30s
    timeout server 30s
    option redispatch
    retries 2

frontend fe_http
    bind *:{{ lb_public_port }}
    default_backend myapp

backend myapp
    balance roundrobin
    option httpchk
    http-check send meth GET uri /readyz
    http-check expect status 200
{% for h in groups['app'] %}
    server {{ h }} {{ hostvars[h].myapp_listen_host | default(h) }}:{{ myapp_port }} check inter 2s fall 2 rise 2
{% endfor %}
- name: render haproxy.cfg (validated with haproxy -c)
  ansible.builtin.template:
    src: haproxy.cfg.j2
    dest: /etc/haproxy/haproxy.cfg
    validate: haproxy -c -f %s
  notify: reload haproxy

- name: remove app1 at runtime (no file change)
  community.general.haproxy:
    state: disabled
    host: app1
    backend: myapp
    socket: /run/haproxy/admin.sock     # must be set explicitly; the module default is /var/run/haproxy.sock
    drain: true                          # wait for existing sessions to finish first
    wait: true
  delegate_to: lb1
# talk to the runtime API directly (to verify the module’s effect; install socat first with apt-get install -y socat in the image)
docker exec lb1 sh -c 'echo "show servers state myapp" | socat stdio /run/haproxy/admin.sock'

Lab 2: Deploy an nginx LB and let validate block a bad config (about 6 min)

Write the role: write the roles/nginx_lb — defaults, templates, tasks, and handlers — from the “Commands” page to their paths, then change lb.yml to:
---
- name: load balancer tier
  hosts: lb
  become: true
  roles:
    - role: nginx_lb
      tags: [lb]
First deployment (app nodes are not serving yet at this point; this only verifies the LB itself):
ansible-playbook lb.yml --diff
curl -s localhost:8080/lb-health
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/
TASK [nginx_lb : render nginx.conf (validated with nginx -t before writing to disk)] ****
--- before: /etc/nginx/nginx.conf
+++ after: /home/…/nginx.conf.j2
@@ … @@
+    upstream myapp {
+        server app1:8000 max_fails=2 fail_timeout=5s;   # app1
+        server app2:8000 max_fails=2 fail_timeout=5s;   # app2
changed: [lb1]
RUNNING HANDLER [nginx_lb : reload nginx] ****
changed: [lb1]
PLAY RECAP ****
lb1 : ok=5  changed=4  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
ok
502

502 is expected: nothing is serving on backend port 8000 yet (it becomes 200 after the m3 deployment).

Idempotence: run it again; it should show changed=0, and the handler does not run.
ansible-playbook lb.yml | tail -2
PLAY RECAP ****
lb1 : ok=4  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
Deliberately break the template, and observe validate blocking it:
sed -i 's/keepalive 16;/keepalive 16/' roles/nginx_lb/templates/nginx.conf.j2
ansible-playbook lb.yml
docker exec lb1 nginx -t     # the live config is still intact
sed -i 's/keepalive 16$/keepalive 16;/' roles/nginx_lb/templates/nginx.conf.j2
TASK [nginx_lb : render nginx.conf (validated with nginx -t before writing to disk)] ****
fatal: [lb1]: FAILED! => {"changed": false, "checksum": "…", "exit_status": 1,
  "msg": "failed to validate", "stderr": "nginx: [emerg] unexpected \"}\" in /home/ansible/.ansible/tmp/ansible-tmp-…/source:23\nnginx: configuration file /home/ansible/.ansible/tmp/…/source test failed\n", …}
...
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Try the down flag (the basis for m6):
ansible-playbook lb.yml -e '{"nginx_down_hosts": ["app2"]}' --diff | grep -E '^\+|^-' | grep server
ansible-playbook lb.yml --diff | grep -E '^\+|^-' | grep server
-        server app2:8000 max_fails=2 fail_timeout=5s;   # app2
+        server app2:8000 max_fails=2 fail_timeout=5s down;   # app2
-        server app2:8000 max_fails=2 fail_timeout=5s down;   # app2
+        server app2:8000 max_fails=2 fail_timeout=5s;   # app2

List-type extra vars must use JSON syntax -e '{"k": [...]}'; -e nginx_down_hosts=app2 otherwise you get a string, whereas 'app1' in 'app2' a substring check on such a string may give wrong results.

Cleanup: keep nginx; later modules continue to use it.

Case 1: a restart turned a small change into a site-wide outage

Problem: One team’s role used state: restarted as a handler. When changing the gzip config, the template gained an invalid directive; after the restart, nginx could not start, and the site was down for 6 minutes. Fix: Change the handler to reloaded; add validate to the template; in CI, run nginx -t on the rendered result. Configuration: see the tasks in this module. Limitation: Changes to worker_processes, loading new dynamic modules, and a few other changes still require a restart; schedule them separately and run them one host at a time.

Case 2: lossless node removal in HAProxy

Problem: Long-lived connection (WebSocket) services were cut off abruptly during releases. Fix: Use community.general.haproxy ’s state: drain (weight set to 0, serving only existing sessions) + wait: true, then wait_for: state=drained wait for application-side connections to drop to zero before deploying. Limitation: Connections may never end, so you must set a timeout and accept forced disconnects; the admin socket must be level admin, and the Ansible user needs read/write permission on the socket (join the haproxy group or use become).

Case 3: DNS changes cause nginx to point to an old IP

Problem: After application nodes are replaced in the cloud, their IPs change, but nginx keeps sending requests to the old IPs. Cause: Open-source nginx resolves hostnames in upstream only at startup or reload. Fix: After scaling out or replacing nodes, have Ansible re-render and reload (inventory-driven), or use resolver + variable-form proxy_pass (which loses upstream load balancing). Newer open-source nginx versions add the resolve parameter to upstream server; check the official documentation for your installed version to confirm it is available.

Common errors and fixes

failed to validate: nginx: [emerg] open() "/home/ansible/.ansible/tmp/…/mime.types" failed (2: No such file or directory)

Cause: The template uses a relative path include mime.types;, which validate resolves relative to the temp file’s directory.

Fix: Use absolute paths for all includes /etc/nginx/mime.types.

nginx: [emerg] host not found in upstream "app1:8000"

Cause: lb1 cannot resolve the backend hostnames (not on the same Docker network, or internal DNS is not configured in the cloud).

ansible lb -m ansible.builtin.command -a "getent hosts app1"

Fix: Set in the inventory for the app hosts myapp_listen_host (internal IP), and have the template prefer it; or use hostvars[h].ansible_default_ipv4.address (this requires gathering facts for the app group first).

The task includes an option with an undefined variable. 'dict object' has no attribute 'ansible_default_ipv4'

Cause: The lb play references app hosts’ facts, but this run did not gather facts for the app hosts (for example --limit lb).

Fix: Add a play at the start of site.yml hosts: all, gather_facts: true that gathers facts; or enable fact caching (fact_caching = jsonfile); or switch to inventory variables.

community.general.haproxy: [Errno 13] Permission denied / No such file or directory: '/var/run/haproxy.sock'

Cause: The module’s default socket path differs from Ubuntu’s default /run/haproxy/admin.sock , or the task lacks become.

Fix: Explicitly set socket: /run/haproxy/admin.sock, and become: true; confirm stats socket … level admin.

502 Bad Gateway (all requests)

Cause: All upstream servers are unavailable or marked down.

docker exec lb1 tail -5 /var/log/nginx/error.log
docker exec lb1 nginx -T | grep -A5 "upstream myapp"

Fix: Check whether the application is listening on 0.0.0.0:8000 (not 127.0.0.1); confirm no leftover down marks remain after an interrupted release (rerun lb.yml).

Command-line questions
1. Without changing production, preview the config diff that marking app1 as down would produce.
ansible-playbook lb.yml --check --diff -e '{"nginx_down_hosts": ["app1"]}'
2. Use an ad-hoc command to safely reload nginx on the lb group (validate first).
ansible lb -b -m ansible.builtin.command -a "nginx -t" && \
ansible lb -b -m ansible.builtin.systemd_service -a "name=nginx state=reloaded"
Scenario analysis
A colleague says: “We split the nginx config into a conf.d/myapp.conf fragment managed by Ansible, with the rest provided by the image, but validate always fails.” Explain why and give two options.

A fragment is not a complete config,so nginx -t -c fragment is bound to fail for lacking the events/http context. Option 1: have Ansible manage the complete nginx.conf (this lesson’s approach). Option 2: don’t set validate on the template, but set backup: true and register it; then run nginx -t, and on failure use copy remote_src to restore the backup and fail (can be placed in block/rescue); only notify reload when validation passes.

Verified instructional videos

▶
Ansible 101 - Episode 4 - Your first real-world playbook — Jeff Geerling
2020 · English · Deploying a web service with a playbook and using handlers
▶
Ansible 101 - Episode 5 - Playbook handlers, environment vars, and variables — Jeff Geerling
2020 · English · Handlers and variables, directly relevant to writing a reload handler

No verified video on “nginx/HAProxy upstream template + validate” was found; a storyboard script is provided below.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: the app1 and app2 lines from the inventory flow like water into the template and produce two server lines.
Narration: don’t hand-write the backend list; let the template loop over the app group to generate it.
Shot 2 · 20–45s
Visual: a config file with a red typo is stopped at the “nginx dash t” checkpoint; the live file stays green.
Narration: validate runs before the file is replaced; bad config never gets written to disk.
Shot 3 · 45–80s
Visual: on the left, reload—the old worker leaves after serving its last request and the new worker takes over; on the right, restart—a red “connection refused” gap appears in the middle.
Narration: use reload for config changes; the listening port stays open and in-flight requests are not cut off.
or score ≥ 70% on the quiz

Module 3 · Application tier: systemd services and configuration

14:00 – 22:00 · One release directory per version (with its own venv); the current symlink points to the “version currently running”; systemd manages the process lifecycle
8 minansible.builtin.pip · systemd_servicegunicorn 23★★★★★
Learning objectives
  • Use ansible.builtin.pip ’s virtualenv parameter to create a separate venv for each release, and understand why you should not install dependencies into the system Python (PEP 668 “externally-managed-environment” on Ubuntu 24.04).
  • Write the systemd unit template: User,WorkingDirectory,EnvironmentFile,Type=notify,Restart=on-failure, basic sandbox options, and, when the unit changes, daemon_reload.
  • Separate “configuration/secrets” (/etc/myapp/myapp.env, mode 0640) and “version-specific environment” (release.env, rolls back with the release).
  • Implement /healthz (liveness) and /readyz (readiness) endpoints, and at the end of the deployment task use uri + until for the local health check.
Prerequisites: myapp and gunicorn from the Docker lesson; basic Linux systemd knowledge. Importance:★★★★★

What: the release directory pattern

/opt/myapp/
├── releases/
│   ├── v1/                  # app.py  requirements.txt  release.env  venv/
│   └── v2/                  # each version is fully self-contained, including dependencies
└── current -> releases/v2   # systemd only recognizes this path
/etc/myapp/myapp.env         # configuration and secrets such as DATABASE_URL (root:myapp 0640)
/etc/systemd/system/myapp.service

This is a deployment structure that has been popular since the Capistrano era: Deploy = prepare a new directory + atomically switch the symlink + restart; Rollback = point the link back to the previous directory + restart, with no need to re-download or re-run pip install; it completes within seconds.

Why: why not “overwrite in place”

  • Atomicity: Overwriting in place git pull/ overwriting files, a process may load half-new, half-old code; a symlink switch is one rename atomic operation.
  • Dependency consistency: Each release carries its own venv, so dependencies roll back along with the code (rolling back code after upgrading dependencies in place often fails, because the dependencies have already changed).
  • Observability:readlink /opt/myapp/current is the “current version”; the m6 rollback logic relies on it.

How: how systemd and gunicorn work together

DirectivePurposeValue in this lesson and why
Type=notifyThe process uses sd_notify(READY=1) to tell systemd it is “ready”gunicorn supports systemd notification,systemctl start so systemd waits until the master is ready before returning
WorkingDirectoryWorking directory of the process/opt/myapp/current: At startup, resolves the symlink; after switching the link, a restart is required
EnvironmentFileLoad environment variables from a file (multiple lines allowed)Loaded first: /etc/myapp/myapp.env, then loaded: current/release.env
KillMode=mixed + TimeoutStopSecOn stop, SIGTERM goes to the main process first; after a timeout, SIGKILL is sent to the whole cgroupgunicorn exits gracefully on SIGTERM (default graceful_timeout 30 seconds)
Restart=on-failureAutomatically restart on abnormal exitUsed with RestartSec=2, to avoid restarting too quickly
NoNewPrivileges/ProtectSystem=strict/PrivateTmpSandboxThe application has read-only access to system directories (if you hit 226/NAMESPACE in the container lab, see troubleshooting)

Semantics of health endpoints

EndpointWhat it checksWho uses itOn failure
/healthzThe process responds (dependencies not checked)Local check in the deploy script; liveness judgment by systemd or monitoringRoll back this node / restart the process
/readyzDependencies available (SELECT 1)HAProxy active checks; checks before re-adding to the LB during a releaseStop routing traffic, but do not restart (during a database outage, restarting all apps only amplifies the failure)

When: when to use native systemd deployment vs. containers

Native deployment suits: existing VM assets, compliance requirements for host-level auditing, and services that need direct hardware access or large local disks. Container deployment (m7) suits: multiple languages and versions side by side, and the need for image-level immutability and fast scaling. The release logic (batching, removal, health checks, rollback) is exactly the same for both; that is why this lesson covers the native approach first.

Comparison with similar approaches

release directory + systemdIn-place git pullContainer image
Rollback speedSeconds (switch link)Requires re-fetch / reinstallSeconds (switch image tag, if the image is already local)
Dependency isolationOne venv per releaseShared, prone to driftInside the image
Disk usageN copies of venv (need cleanup)One copyImage layers shared
Common misconceptions① “Changing the unit file and restarting is enough”—you must first daemon-reload (in the module, daemon_reload: true), otherwise systemd keeps using the old definition in memory and prints “changed on disk. Run 'systemctl daemon-reload'”. ② “A restart in a handler is enough”—handlers run only at the end of the section; if your health check is written later in the same section, the check will hit the old process. This lesson’s role explicitly restarts immediately on change, then runs the health check. ③ “EnvironmentFile supports shell syntax”—it does not support export, variable expansion, or command substitution, and its rules for spaces and quotes in values also differ from the shell.

Architecture diagram: deployment artifacts on one app node

app1 (Ubuntu 24.04, systemd) /opt/myapp releases/v1app.py · venv · release.env(v1) releases/v2app.py · venv · release.env(v2) current → releases/v2 /etc/myapp/myapp.envDATABASE_URL=postgresql://…@db1root:myapp 0640 (contains password) myapp.serviceUser=myapp · Type=notifyExecStart=current/venv/bin/gunicorn gunicorn masterworker × gunicorn_workers0.0.0.0:8000/healthz /readyz / journaldjournalctl -u myappaccess log written to stdout
Figure 3-1 The current symlink determines which version runs; configuration/secrets and the version environment are stored separately

Flowchart: order of one deployment on a managed node

apt/userDependencies and accounts copy source codereleases/v2 pip venvinstall dependencies templateenv + unit file linkswitch current daemon-reload+ restart uri /healthzuntil 200 find + fileclean up old releases The first 4 steps do not affect the running process (preparation phase); steps 5–6 are the switchover window; if step 7 fails → m6’s rescue points the link back to the old version
Figure 3-2 Prepare first, switch later: compress the window that “affects live traffic” to the few seconds of the restart

Step-by-step animation: the 9 real steps of deploying myapp on app1

Each step shows the module Ansible actually runs, what happens on the managed node, and the /opt/myapp directory and myapp.service state. Check “bad version” to see what a failed health check looks like (this is exactly the trigger for the m6 rollback).

Managed node filesystem
systemd / processes

Core modules and parameters

ModulePurposeKey parameters
ansible.builtin.pipInstall dependencies in a venvrequirements,virtualenv,virtualenv_command: python3 -m venv
ansible.builtin.copyCopy the source directorysrc: myapp/ (trailing slash = copy the directory’s contents)
ansible.builtin.fileSymbolic linkstate: link,src (target),dest (link),force
ansible.builtin.systemd_serviceServicedaemon_reload,state,enabled
ansible.builtin.uriHTTP checkurl,status_code,return_content; used with register/until/retries/delay
ansible.builtin.wait_forWait for a port / file / connection drainport,host,state: started/stopped/drained,timeout
myapp_user: myapp
myapp_base: /opt/myapp
myapp_release_dir: "{{ myapp_base }}/releases/{{ myapp_version }}"
myapp_port: 8000
myapp_bind: 0.0.0.0
gunicorn_workers: 2
gunicorn_timeout: 30
myapp_keep_releases: 3
myapp_broken: false          # for demo: when true, /healthz returns 500
# {{ ansible_managed }}
[Unit]
Description=myapp {{ env_name }}
After=network-online.target
Wants=network-online.target

[Service]
Type=notify
NotifyAccess=main
User={{ myapp_user }}
Group={{ myapp_user }}
WorkingDirectory={{ myapp_base }}/current
EnvironmentFile=/etc/myapp/myapp.env
EnvironmentFile={{ myapp_base }}/current/release.env
ExecStart={{ myapp_base }}/current/venv/bin/gunicorn \
    --workers {{ gunicorn_workers }} --timeout {{ gunicorn_timeout }} \
    --bind {{ myapp_bind }}:{{ myapp_port }} --access-logfile - app:app
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=35
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target
# {{ ansible_managed }}
DATABASE_URL=postgresql://{{ myapp_db_user }}:{{ myapp_db_password | urlencode }}@{{ myapp_db_host }}:5432/{{ myapp_db_name }}
APP_VERSION={{ myapp_version }}
APP_BROKEN={{ '1' if myapp_broken | bool else '0' }}
- name: system dependencies
  ansible.builtin.apt:
    name: [python3-venv, python3-pip]
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: service account
  ansible.builtin.user:
    name: "{{ myapp_user }}"
    system: true
    shell: /usr/sbin/nologin
    home: "{{ myapp_base }}"
    create_home: false

- name: base directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: "{{ myapp_user }}"
    mode: "0755"
  loop: ["{{ myapp_base }}", "{{ myapp_base }}/releases", "{{ myapp_release_dir }}", /etc/myapp]

- name: copy source to the release directory
  ansible.builtin.copy:
    src: myapp/
    dest: "{{ myapp_release_dir }}/"
    mode: "0644"

- name: version environment file (rolls back with the release)
  ansible.builtin.template:
    src: release.env.j2
    dest: "{{ myapp_release_dir }}/release.env"
    mode: "0644"
  register: myapp_release_env

- name: venv and dependencies
  ansible.builtin.pip:
    requirements: "{{ myapp_release_dir }}/requirements.txt"
    virtualenv: "{{ myapp_release_dir }}/venv"
    virtualenv_command: python3 -m venv

- name: configuration and secrets
  ansible.builtin.template:
    src: myapp.env.j2
    dest: /etc/myapp/myapp.env
    owner: root
    group: "{{ myapp_user }}"
    mode: "0640"
  diff: false                      # avoid --diff printing the password to the log
  register: myapp_env

- name: systemd unit
  ansible.builtin.template:
    src: myapp.service.j2
    dest: /etc/systemd/system/myapp.service
    mode: "0644"
  register: myapp_unit

- name: switch current → this version
  ansible.builtin.file:
    src: "{{ myapp_release_dir }}"
    dest: "{{ myapp_base }}/current"
    state: link
    force: true
  register: myapp_link

- name: restart immediately on change (no handler, so the following health check targets the new process)
  ansible.builtin.systemd_service:
    name: myapp
    enabled: true
    daemon_reload: "{{ myapp_unit is changed }}"
    state: "{{ 'restarted' if (myapp_link is changed or myapp_env is changed or myapp_unit is changed or myapp_release_env is changed) else 'started' }}"

- name: local health check /healthz
  ansible.builtin.uri:
    url: "http://127.0.0.1:{{ myapp_port }}/healthz"
    return_content: true
  register: myapp_health
  until: myapp_health.status == 200
  retries: 10
  delay: 2

- name: list releases
  ansible.builtin.find:
    paths: "{{ myapp_base }}/releases"
    file_type: directory
  register: myapp_releases

- name: keep only the most recent {{ myapp_keep_releases }} releases (never delete the current version)
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: absent
  loop: "{{ (myapp_releases.files | rejectattr('path', 'equalto', myapp_release_dir) | sort(attribute='mtime') | list)[:-(myapp_keep_releases - 1)] }}"
  loop_control: { label: "{{ item.path }}" }
  when: myapp_releases.matched > myapp_keep_releases

How to verify:ansible app -b -a "readlink /opt/myapp/current"; ansible app -b -a "systemctl show myapp -p ActiveState,MainPID,ExecMainStartTimestamp". Common errors: pip reports “externally-managed-environment”—this means you did not use virtualenv the parameter, and installed directly into the system Python. Production use: Name release directories with the short Git commit hash or build number,myapp_version passed in by CI.

Lab 3: Deploy myapp v1 to app1/app2 (about 7 min)

Write the role: write the defaults, the three templates, and the tasks from the “Commands” page into roles/myapp/; app.yml was already changed in m1 to reference the myapp role (if it is still the placeholder version, modify app.yml as shown on the m1 “Commands” page).
Deploy:
ansible-playbook app.yml
TASK [myapp : venv and dependencies] ****
changed: [app1]
changed: [app2]
TASK [myapp : restart immediately on change (no handler, so the following health check targets the new process)] ****
changed: [app1]
changed: [app2]
TASK [myapp : local health check /healthz] ****
ok: [app1]
ok: [app2]
PLAY RECAP ****
app1 : ok=13  changed=10  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
app2 : ok=13  changed=10  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
Verify the three endpoints (the database is not created until m4, so at this point /readyz should be 503):
ansible app -b -m ansible.builtin.shell -a 'readlink /opt/myapp/current; curl -s localhost:8000/healthz; echo; curl -s -o /dev/null -w "readyz=%{http_code}\n" localhost:8000/readyz'
docker exec app1 systemctl status myapp --no-pager | head -6
app1 | CHANGED | rc=0 >>
/opt/myapp/releases/v1
{"status":"ok","version":"v1"}
readyz=503
...
● myapp.service - myapp staging
     Loaded: loaded (/etc/systemd/system/myapp.service; enabled; preset: enabled)
     Active: active (running) since …
   Main PID: 1234 (gunicorn)
Idempotence and “restart only on change”: run again and note whether MainPID changes.
ansible app -b -a "systemctl show myapp -p MainPID"
ansible-playbook app.yml | tail -3
ansible app -b -a "systemctl show myapp -p MainPID"

The two MainPID values match,changed=0: no change means no restart. If every run reports changed, a common cause is that the pip task reports a change each time (for example, requirements contains an unpinned VCS link).

Check whether secrets leak:
ansible app -b -a "stat -c '%U:%G %a' /etc/myapp/myapp.env"
ansible-playbook app.yml --diff --check | grep -i DATABASE_URL || echo "no password appears in the diff ✓"
Cleanup: keep these; after m4 creates the database, /readyz it will automatically become 200.

Case 1: two nodes installed different dependencies

Problem: requirements only specified flask>=3, app1 was deployed on Monday and app2 was scaled out on Wednesday; in between, PyPI published a new version, so the two hosts behaved differently. Fix: Use pip-compile --generate-hashes to produce a lock file; further, build a wheelhouse in CI (pip wheel -r requirements.txt -w wheels/), and Ansible only does pip install --no-index --find-links. Limitation: Wheels must match the Python version and architecture of the managed nodes.

Case 2: logs filled up the root partition

Problem: The old approach used nohup … & to start, writing logs to a file without rotation. Fix: Switch to systemd management; gunicorn logs go to stdout and are handed to journald; configure SystemMaxUse=; then use the log collection from lesson 5 to forward journald to a central platform. Limitation: Whether journald stores logs in memory or on disk by default depends on /var/log/journal whether it exists.

Case 3: rollback failed — the code went back, the config did not

Problem: The new version introduced a new environment variable. The rollback switched back only the code; the old code didn’t recognize the new config item but raised no error, causing functional failures. Fix: Put the “version-specific” environment into the release directory (this lesson’s release.env), and keep only version-independent connection strings and secrets in shared config; config changes follow the rule “new code works with old config, old code ignores new config”. Limitation: Database schema changes cannot be rolled back by switching links (see expand/contract in m6).

Common errors and fixes

error: externally-managed-environment … This environment is externally managed

Cause: Ubuntu 24.04’s system Python follows PEP 668, which prohibits pip from installing directly into the system environment.

Fix: Use the virtualenv parameter to install into a venv (this lesson’s approach); do not use --break-system-packages to bypass it.

myapp.service: Main process exited, code=exited, status=226/NAMESPACE

Cause: systemd sandbox options (ProtectSystem,PrivateTmp etc.) need to create a mount namespace, which is not allowed in some container environments.

docker exec app1 journalctl -u myapp -n 20 --no-pager

Fix: In the lab container, you can temporarily comment out the sandbox options (or confirm the container runs with --privileged ); on a real VM, keep these options.

Warning: The unit file, source configuration file or drop-ins of myapp.service changed on disk. Run 'systemctl daemon-reload'

Cause: The unit file was modified but daemon-reload was not run.

Fix:systemd_service Set daemon_reload: true on the task (this lesson sets it automatically when the unit changes).

FAILED - RETRYING: [app1]: local health check /healthz (10 retries left) … Status code was -1 and not [200]: Request failed: <urlopen error [Errno 111] Connection refused>

Cause: The process did not start or is not listening on 8000. status -1 This indicates a connection-level failure, not an HTTP error.

ansible app1 -b -a "journalctl -u myapp -n 30 --no-pager"
ansible app1 -b -a "ss -ltnp"

Fix: Common causes: gunicorn is missing from the venv (requirements error),EnvironmentFile a path does not exist (systemd refuses to start outright; you can prefix the path with - to mark it optional), or the port is already in use.

systemd: Failed to determine user credentials: No such process / status=217/USER

Cause:User=myapp The corresponding account does not exist (the task that creates it was skipped or its spelling is inconsistent).

Fix: Make sure the user task runs before the unit, and use the same variable myapp_user.

Command-line questions
1. Use an ad-hoc command to check the version currently running on all app nodes and the process start time.
ansible app -b -m ansible.builtin.shell -a 'readlink /opt/myapp/current; systemctl show myapp -p ExecMainStartTimestamp --value'
2. To re-render only the config files (without reinstalling dependencies): which tasks should get a tag, and how do you call it?
# add tags: [config] to the role’s two template tasks and the restart task
ansible-playbook app.yml --tags config
Scenario analysis
A Java team asks: we also want to use the release directory pattern, but JARs are large (300 MB), and keeping one per release would fill the disk. How should we design it?

Reduce retention to 2–3 releases (myapp_keep_releases); the JAR itself is an immutable artifact, so it can be placed in a shared artifacts/ directory named by version, with the release directory holding only symlinks and release.env; or use an artifact repository + get_url ’s checksum parameter to implement “skip if already present”. Rollback is still switching current.

Verified instructional videos

▶
Ansible 101 - Episode 6 - Ansible Vault and Roles — Jeff Geerling
2020 · English · Role structure and Vault, corresponding to this module’s role split and secrets handling

No verified video on “Ansible + systemd release directory deployment” was found; a storyboard script is provided below.

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: the releases folder holds two boxes side by side, v1 and v2; the current arrow points to v1.
Narration: one directory per version, with dependencies installed alongside; the current link points to the running version.
Shot 2 · 25–55s
Visual: the arrow clicks from v1 to v2, the systemd icon spins once, and gunicorn restarts.
Narration: a release is switching the link and then restarting; the switch is atomic, so you never get a half-new, half-old state.
Shot 3 · 55–90s
Visual: the health-check probe hits healthz and a green light comes on; with a bad version, a red light comes on and the arrow turns back to v1.
Narration: check the health endpoint right after deployment; if it fails, point the link back. Rollback completes in seconds.
or score ≥ 70% on the quiz

Module 4 · Data tier: PostgreSQL and backups

22:00 – 30:00 · Declaratively manage users, databases, tables, and access rules with community.postgresql; a backup doesn’t count until a restore succeeds
8 mincommunity.postgresql 4.2.0PostgreSQL 16 (Ubuntu 24.04)★★★★★
Learning objectives
  • Use postgresql_user,postgresql_db,postgresql_table,postgresql_privs,postgresql_pg_hba to create the database objects the application needs, and keep them idempotent.
  • Understand why these tasks must become_user: postgres (peer authentication), and why it depends on the acl package on the managed node.
  • Derive from the inventory pg_hba rules (only allowing the IPs of the app group), and master the pg_hba rule that is “top-down, first match wins”.
  • Use cron to deploy pg_dump -Fc scheduled backups + a retention policy, and complete one drill of “restore to a temporary database → verify row counts → formal restore”.
Prerequisites: SQL basics; the Vault variables from m1. Importance:★★★★★ (data is the only thing that cannot be “redeployed”)

What: the community.postgresql collection

This collection (4.2.0, verified 2026-11) provides 23 modules; this lesson uses:

ModuleManagesKey points
postgresql_userRoles (users)password (stored as hashes by default),role_attr_flags (e.g. CREATEDB,NOSUPERUSER); grants no longer use this module; use postgresql_privs
postgresql_dbdatabases; can also dump/restoreowner,encoding,template; state: dump/restore + target (these two states do not require psycopg)
postgresql_tableTablescolumns list,owner; only ensures “existence”; does not perform schema migration
postgresql_privsGRANT/REVOKEtype: table,objs: ALL_IN_SCHEMA,privs: SELECT
postgresql_pg_hbapg_hba.conf linescontype,databases,users,address (alias source),method; does not reload automatically; needs a handler
postgresql_query / postgresql_ping / postgresql_infoRun SQL / connectivity / instance infoWhen writing SQL, watch for idempotence (IF NOT EXISTS)

Note: postgresql_set In 4.x it is marked as deprecated; for changing server parameters, the recommended option is postgresql_alter_system; this lesson changes listen_addresses using lineinfile to change postgresql.conf, for easy comparison with the distribution’s configuration.

Why: why the database should also be handed to Ansible

  • Rebuildable: New and disaster-recovery environments need “the same users, the same privileges, the same access rules”; manual work inevitably drifts.
  • Access rules tied to topology: when app nodes are added or removed,pg_hba should follow inventory changes automatically (the design goal of m1).
  • Auditable backups: Cron entries, retention days, and script contents are all in Git, so they are clear at review time.

How: execution identity and connection method

The module runs on the managed node (db1), connecting to the local PostgreSQL with psycopg2/psycopg3. Ubuntu’s default is local all postgres peer: only the OS user postgres can log in as the database user postgres. So the task is written with become: true + become_user: postgres. When switching from the ansible user to another unprivileged user, the temporary module files Ansible uploads must be readable by postgres; it tries these in turn: setfacl (requires the acl package) and similar methods; if all fail, you get “Failed to set permissions on the temporary files…”. With pipelining enabled, the module is sent via stdin, which avoids this problem, but installing acl is still recommended.

pg_hba.conf: top-down, first match wins

FieldExampleMeaning
TYPElocal / host / hostsslUnix socket / TCP / TCP with TLS only
DATABASEmyappTarget database
USERmyappDatabase role
ADDRESS172.18.0.3/32Source; samenet means the same subnet
METHODscram-sha-256Default password hash since PostgreSQL 14; reject explicit reject

The first rule that matches TYPE+DATABASE+USER+ADDRESS determines the authentication method,and later rules are no longer checked. If the first match is reject or the password is wrong, it does not “fall back to a lower-priority rule”. When no rule matches, you get no pg_hba.conf entry for host …. After editing, reload takes effect; whereas listen_addresses requires restart.

When: logical backup vs. physical backup

pg_dump (logical, this lesson)pg_basebackup + WAL archiving (physical)Managed database
GranularitySingle database / tableWhole clusterWhole server
Recovery pointBackup timeAny point in time (PITR)Any point in time (within retention)
Best forSmall to medium databases; cross-version migrationLarge databases; RPO requirements in minutesAzure Database for PostgreSQL / Amazon RDS
Common misconceptions① “If cron runs a backup every day, it’s safe”—a backup without restore drills is no backup at all; pg_dump in some versions the return code can still be 0 on errors (the module docs also note this), so the script must use pg_restore --list to check that the file is readable. ② “postgresql_table can perform schema migration”—it only ensures a table exists; adding columns or changing types requires a migration tool (Alembic, Flyway) following m6’s expand/contract. ③ “Adding one line at the end of pg_hba is enough”—if there are broader rules earlier in the file reject or rules with a different method, your rule will never be matched.

Architecture diagram: objects and access paths on db1

app1172.18.0.3 app2172.18.0.4 lb1 (should not have access)172.18.0.2 TCP 5432 pg_hba.conf (first match) local all postgres peer host myapp myapp 172.18.0.3/32 scram host myapp myapp 172.18.0.4/32 scram host all all 127.0.0.1/32 scram lb1 no match →FATAL: no pg_hba.conf entry ← generated from groups['app'] PostgreSQL 16 · main clusterrole myapp (LOGIN, scram password)database myapp (owner myapp)table hits(id, host, version, ts)role report_ro (SELECT)listen_addresses = '*' cron (postgres user)pg_backup.sh → /var/backups/postgresqlmyapp-YYYYmmdd-HHMMSS.dump, kept for 7 days
Figure 4-1 Only IPs in the app group can connect to the myapp database; backups run from the postgres user’s cron

Flowchart: backup and restore drill

cron triggers*/5 or daily at 02:15 pg_dump -Fcwrite .tmp pg_restore --listverify readable → mv find -mtime +7-delete Drill: restore tomyapp_restore_test compare row counts→ drop the temporary database Also be sure to copy backups off db1 (object storage / another host); otherwise, if the host is damaged, the backups are lost too
Figure 4-2 Backup → verify → rotate → periodic restore drill; all four steps are required

Interactive simulator: pg_hba first match

Select a connection request and click “Match”. The simulator compares TYPE / DATABASE / USER / ADDRESS line by line from the top, using PostgreSQL’s real algorithm, and stops at the first match. Click ↑ to the left of a rule to reorder it and see that “order is meaning”.

First select a connection request.
$ psql "host=db1 dbname=myapp user=myapp"

Core modules and commands

Module / commandPurposeKey parameters
community.postgresql.postgresql_userCreate roles and set passwordsname,password,role_attr_flags,no_password_changes
community.postgresql.postgresql_dbDatabases / dump / restoreowner,state: present/dump/restore,target,target_opts
community.postgresql.postgresql_tableTablesdb,name,columns,owner
community.postgresql.postgresql_privsGrantsrole,type,objs,schema,privs
community.postgresql.postgresql_pg_hbaAccess rulesdest,contype,address,method,backup
ansible.builtin.cronScheduled tasksname (idempotency key),user,minute/hour,job
ansible.builtin.setup + delegate_factsGather facts for app hosts in the db playdelegate_to + delegate_facts: true
---
- name: data tier
  hosts: db
  become: true
  pre_tasks:
    - name: gather network facts for app nodes (pg_hba needs their IPs)
      ansible.builtin.setup:
        gather_subset: [network]
      delegate_to: "{{ item }}"
      delegate_facts: true          # facts are stored under hostvars[item], not db1
      loop: "{{ groups['app'] }}"
  roles:
    - role: postgresql
      tags: [db]
- name: install PostgreSQL, psycopg2, acl
  ansible.builtin.apt:
    name: [postgresql, postgresql-contrib, python3-psycopg2, acl]
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: listen on all addresses (requires restart)
  ansible.builtin.lineinfile:
    path: "/etc/postgresql/{{ postgresql_version }}/main/postgresql.conf"
    regexp: '^#?listen_addresses\s*='
    line: "listen_addresses = '*'"
  notify: restart postgresql

- name: service running
  ansible.builtin.systemd_service: { name: postgresql, state: started, enabled: true }

- name: run pending restart now (later tasks need the new config)
  ansible.builtin.meta: flush_handlers

- name: database objects
  become_user: postgres
  block:
    - name: application role
      community.postgresql.postgresql_user:
        name: "{{ myapp_db_user }}"
        password: "{{ myapp_db_password }}"
      no_log: true

    - name: application database
      community.postgresql.postgresql_db:
        name: "{{ myapp_db_name }}"
        owner: "{{ myapp_db_user }}"
        encoding: UTF-8
        template: template0

    - name: table hits
      community.postgresql.postgresql_table:
        db: "{{ myapp_db_name }}"
        name: hits
        owner: "{{ myapp_db_user }}"
        columns:
          - id bigserial primary key
          - host text not null
          - version text not null
          - ts timestamptz not null default now()

    - name: read-only reporting role
      community.postgresql.postgresql_user:
        name: report_ro
        role_attr_flags: NOLOGIN

    - name: grant read-only privileges
      community.postgresql.postgresql_privs:
        db: "{{ myapp_db_name }}"
        role: report_ro
        type: table
        schema: public
        objs: ALL_IN_SCHEMA
        privs: SELECT

- name: pg_hba: allow only the app group to access the myapp database
  community.postgresql.postgresql_pg_hba:
    dest: "/etc/postgresql/{{ postgresql_version }}/main/pg_hba.conf"
    contype: host
    databases: "{{ myapp_db_name }}"
    users: "{{ myapp_db_user }}"
    address: "{{ hostvars[item].ansible_default_ipv4.address }}/32"
    method: scram-sha-256
    backup: true
  loop: "{{ groups['app'] }}"
  notify: reload postgresql

- name: backup directory
  ansible.builtin.file:
    path: "{{ postgresql_backup_dir }}"
    state: directory
    owner: postgres
    group: postgres
    mode: "0750"

- name: backup script
  ansible.builtin.template:
    src: pg_backup.sh.j2
    dest: /usr/local/bin/pg_backup.sh
    mode: "0755"

- name: backup cron (demo every 5 minutes; production uses daily at 02:15)
  ansible.builtin.cron:
    name: myapp pg_dump
    user: postgres
    minute: "{{ postgresql_backup_minute | default('*/5') }}"
    hour: "{{ postgresql_backup_hour | default('*') }}"
    job: "/usr/local/bin/pg_backup.sh >> /var/log/postgresql/backup.log 2>&1"
- name: restart postgresql
  ansible.builtin.systemd_service: { name: postgresql, state: restarted }

- name: reload postgresql
  ansible.builtin.systemd_service: { name: postgresql, state: reloaded }
#!/usr/bin/env bash
# {{ ansible_managed }}
set -euo pipefail
DIR="{{ postgresql_backup_dir }}"
TS="$(date +%Y%m%d-%H%M%S)"
OUT="$DIR/{{ myapp_db_name }}-$TS.dump"
pg_dump -Fc -d "{{ myapp_db_name }}" -f "$OUT.tmp"
pg_restore --list "$OUT.tmp" > /dev/null          # verify the file is complete and readable
mv "$OUT.tmp" "$OUT"
find "$DIR" -name '{{ myapp_db_name }}-*.dump' -mtime +{{ postgresql_backup_keep_days }} -delete
echo "$(date -Is) backup ok: $OUT ($(stat -c %s "$OUT") bytes)"

How to verify:ansible db -b --become-user postgres -m community.postgresql.postgresql_ping -a db=myapp returns is_available: true; docker exec db1 crontab -u postgres -l shows entries with #Ansible: myapp pg_dump comments (the cron module uses this comment to identify the “same” task). Common errors: Setting block has been written on become_user but the play does not have become: true—become_user does not take effect on its own.

Lab 4: create database and user, scheduled backups, restore after dropping a table (about 8 min)

Write the role and db.yml (content on the “Commands” page), then run:
ansible-playbook db.yml
TASK [gather network facts for app nodes (pg_hba needs their IPs)] ****
ok: [db1 -> app1] => (item=app1)
ok: [db1 -> app2] => (item=app2)
...
TASK [postgresql : application role] ****
changed: [db1]
TASK [postgresql : pg_hba: allow only the app group to access the myapp database] ****
changed: [db1] => (item=app1)
changed: [db1] => (item=app2)
RUNNING HANDLER [postgresql : reload postgresql] ****
changed: [db1]
PLAY RECAP ****
db1 : ok=16  changed=12  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
The application tier is now ready (no need to redeploy the app: /readyz each request reconnects to the database):
for i in 1 2 3 4; do curl -s localhost:8080/; echo; done
ansible app -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/readyz" -o | cut -c1-80
{"host":"app1","hits":1,"version":"v1"}
{"host":"app2","hits":2,"version":"v1"}
{"host":"app1","hits":3,"version":"v1"}
{"host":"app2","hits":4,"version":"v1"}
app1 | SUCCESS => {"changed": false, … "status": 200 …
app2 | SUCCESS => {"changed": false, … "status": 200 …
Verify that pg_hba rejects lb1:
docker exec lb1 bash -c "apt-get install -y -qq postgresql-client >/dev/null; PGPASSWORD=S3cure-Lab-Pass psql -h db1 -U myapp -d myapp -c 'select 1'"
psql: error: connection to server at "db1" (172.18.0.5), port 5432 failed: FATAL:  no pg_hba.conf entry for host "172.18.0.2", user "myapp", database "myapp", SSL encryption
Trigger a backup manually and check:
ansible db -b --become-user postgres -a /usr/local/bin/pg_backup.sh
ansible db -b -m ansible.builtin.find -a "paths=/var/backups/postgresql patterns=*.dump" | grep '"path"'
db1 | CHANGED | rc=0 >>
2026-11-15T10:20:03+00:00 backup ok: /var/backups/postgresql/myapp-20261115-102003.dump (3912 bytes)
            "path": "/var/backups/postgresql/myapp-20261115-102003.dump",
Restore drill playbook: first restore into a temporary database and compare row counts, then drop the temporary database.
---
- name: restore drill (does not affect the production database)
  hosts: db
  become: true
  become_user: postgres
  vars:
    drill_db: "{{ myapp_db_name }}_restore_test"
  tasks:
    - name: find the latest backup
      ansible.builtin.find:
        paths: "{{ postgresql_backup_dir }}"
        patterns: "{{ myapp_db_name }}-*.dump"
      register: dumps
      failed_when: dumps.matched == 0

    - name: select the file
      ansible.builtin.set_fact:
        latest_dump: "{{ (dumps.files | sort(attribute='mtime') | last).path }}"

    - name: create a temporary database
      community.postgresql.postgresql_db: { name: "{{ drill_db }}", state: present }

    - name: restore into the temporary database (.dump uses pg_restore)
      community.postgresql.postgresql_db:
        name: "{{ drill_db }}"
        state: restore
        target: "{{ latest_dump }}"
        target_opts: "--no-owner"

    - name: compare row counts
      community.postgresql.postgresql_query:
        db: "{{ item }}"
        query: SELECT count(*) AS n FROM hits
      loop: ["{{ drill_db }}", "{{ myapp_db_name }}"]
      register: counts

    - name: report
      ansible.builtin.debug:
        msg: "Backup {{ latest_dump | basename }}: restored DB {{ counts.results[0].query_result[0].n }} rows / production DB {{ counts.results[1].query_result[0].n }} rows (production ≥ restored is normal)"

    - name: drop the temporary database
      community.postgresql.postgresql_db: { name: "{{ drill_db }}", state: absent }
ansible-playbook restore_drill.yml
TASK [report] ****
ok: [db1] => {
    "msg": "Backup myapp-20261115-102003.dump: restored DB 4 rows / production DB 4 rows (production ≥ restored is normal)"
}
Real disaster: restore after accidentally dropping a table (first stop application writes, then restore):
ansible db -b --become-user postgres -m community.postgresql.postgresql_query -a "db=myapp query='DROP TABLE hits'"
curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/          # 500: table does not exist
ansible app -b -m ansible.builtin.systemd_service -a "name=myapp state=stopped"
LATEST=$(ansible db -b -m ansible.builtin.shell -a 'ls -t /var/backups/postgresql/*.dump | head -1' | tail -1)
ansible db -b --become-user postgres -m community.postgresql.postgresql_db \
  -a "name=myapp state=restore target=$LATEST target_opts='--clean --if-exists'"
ansible app -b -m ansible.builtin.systemd_service -a "name=myapp state=started"
curl -s localhost:8080/
500
...
{"host":"app1","hits":5,"version":"v1"}

After restoring, hits continues from the backup time (data written after the backup is lost; that is the RPO). If, after the restore, / you get permission errors, it means the object owner changed during the restore: remove --no-owner or run once more ansible-playbook db.yml.

Cleanup: change cron to the production frequency: in group_vars/db.yml add postgresql_backup_minute: "15",postgresql_backup_hour: "2" then rerun db.yml (the cron module updates the same entry by name, so no duplicates are created).

Case 1: backups “succeeded” for a year; the empty files were only discovered during a restore

Problem: The backup script passed pg_dump output through a pipe to gzip,pg_dump authentication failed, but the pipeline returned gzip’s exit code 0; a year of backups were all 20 bytes. Fix: The script uses set -o pipefail; write to .tmp first, then pg_restore --list verifies and then renames; every week, restore_drill.yml (an AWX scheduled job) restores into a temporary database, compares row counts, and alerts on failure. Limitation: Row-count comparison only catches “obvious loss”; for critical tables, you can additionally compare checksums.

Case 2: after scaling out to app3, it could not connect to the database

Problem: The new node deployed successfully, but /readyz returns 503, and the log shows no pg_hba.conf entry. Cause: Only ran app.yml, so the db tier’s pg_hba was not refreshed. Fix: The scale-out runbook is fixed to site.yml --limit 'db:app3:lb', or simply run the full site.yml (idempotent). Limitation: Large environments can switch to samenet or a subnet CIDR to reduce the number of rules, but this widens the access scope and must be weighed with the security team.

Case 3: a password leaked into CI logs

Problem:postgresql_user When a task failed, the error message included the module parameters. Fix: Add no_log: true to all tasks that handle passwords; add diff: false to template tasks; store production passwords in Vault or an external secrets manager (AAP 2.6 supports credential plugins such as HashiCorp Vault and Azure Key Vault). Limitation:no_log It also hides useful error messages; when troubleshooting, temporarily use a method other than ANSIBLE_DEBUG (reproduce in an isolated environment).

Common errors and fixes

Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user (rc: 1, err: chmod: invalid mode: 'A+user:postgres:rx:allow')

Cause: When switching from ansible to the unprivileged user postgres, the managed node does not have setfacl, and the other fallback methods also fail.

Fix: Install the acl package (preinstalled in this lesson’s image, and also installed by the role); or enable pipelining = True; do not use allow_world_readable_tmpfiles (this makes the temporary files globally readable).

FATAL: Peer authentication failed for user "postgres"

Cause: The task connects as root or the ansible user, while in pg_hba, peer local all postgres peer requires the OS username to equal the database username.

Fix:become: true + become_user: postgres (the module documentation’s recommended approach).

Failed to import the required Python library (psycopg2 or psycopg) on db1's Python /usr/bin/python3

Cause: The module runs on the managed node and requires the managed node’s Python to be able to import psycopg2 (≥ 2.5.1) or psycopg3 (≥ 3.1.8).

Fix:apt install python3-psycopg2; if a custom ansible_python_interpreter (for example, a venv) is used, install the library into that interpreter.

FATAL: no pg_hba.conf entry for host "172.18.0.4", user "myapp", database "myapp", no encryption

Cause: No matching rule; or the rule was written but not reloaded; or the app node IP changed (container rebuilt).

ansible db -b -a "grep -v '^#' /etc/postgresql/16/main/pg_hba.conf"
ansible db -b --become-user postgres -m community.postgresql.postgresql_query -a "query='SELECT line_number,type,database,user_name,address,auth_method,error FROM pg_hba_file_rules'"

Fix: Rerun db.yml (this re-collects the app IPs and reloads). pg_hba_file_rules The view shows the file on disk’s parse result, so you can check the syntax before reloading.

could not connect to server: Connection refused Is the server running on host "db1" and accepting TCP/IP connections on port 5432?

Cause:listen_addresses It is still localhost, or after the change only a reload was done, with no restart.

Fix: Confirm the handler is a restart and runs before later tasks meta: flush_handlers; run ansible db -b -a "ss -ltn" — you should see 0.0.0.0:5432.

Command-line questions
1. Use an ad-hoc command to check how many rows are currently in the hits table of the myapp database.
ansible db -b --become-user postgres -m community.postgresql.postgresql_query \
  -a "db=myapp query='SELECT count(*) FROM hits'"
2. Use a module to dump the myapp database in custom format to /tmp.
ansible db -b --become-user postgres -m community.postgresql.postgresql_db \
  -a "name=myapp state=dump target=/tmp/myapp-manual.dump target_opts='-Fc'"
Scenario analysis
The business requires RPO ≤ 5 minutes and RTO ≤ 30 minutes, with a database size of 800 GB. Is this module’s cron + pg_dump approach still suitable? How would you design it, and which part does Ansible own?

Not suitable: logical backups of 800 GB take a long time, restores take even longer, and RPO can only reach the backup time. Use physical backups + continuous WAL archiving (such as pgBackRest or Barman) for PITR, or use point-in-time recovery of a managed database directly; add a streaming-replication standby to reduce RTO. Ansible is responsible for installing and configuring the backup tools, the archive destination and credentials, scheduled full/incremental jobs, and orchestrating monitoring and periodic restore drills; it should not itself run the long-running data copies.

Verified instructional videos

No verified video on “community.postgresql collection + backup and restore drills” was found. For review:

▶
Ansible 101 - Episode 4 - Your first real-world playbook — Jeff Geerling
2020 · English · The overall playbook approach to deploying a service

Official documentation

Video storyboard script (about 90 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: the Ansible icon puts on a “postgres” badge, enters the database room, and places three blocks in turn: user, database, table.
Narration: database tasks must run as the postgres user; this is required by peer authentication.
Shot 2 · 25–55s
Visual: three connection requests queue through a row of rule gates; the first matching gate lights up, and the gates after it turn gray.
Narration: pg_hba goes top-down, first match wins; order is meaning.
Shot 3 · 55–90s
Visual: the backup file is put into a safe, then taken out and restored into a temporary database; the counters show matching row counts on both sides, with a check mark.
Narration: a backup doesn’t count until a restore succeeds. Drill regularly, and make restores routine.
or score ≥ 70% on the quiz

Module 5 · Rolling updates: serial, max_fail_percentage, any_errors_fatal, order

30:00 – 38:00 · serial splits hosts into batches; each batch runs the full play before the next batch starts; the failure threshold decides “how bad things must get before stopping”
8 minansible-core 2.21 play keywordsCore animation of this lesson★★★★★
Learning objectives
  • Calculate, using Ansible’s actual algorithm, serial the batches for serial: numbers, percentages (rounded down, minimum 1), and lists (the last value is reused).
  • Accurately describe max_fail_percentage: calculated per the current batch, and the failure ratio must exceed the threshold (not equal it) before aborting; and the default behavior when no threshold is set (the play stops only when a whole batch fails).
  • Distinguish any_errors_fatal (if any host fails, the whole play stops after the current batch finishes that task) from max_fail_percentage: 0 —the subtle differences.
  • Use order to control host order,throttle to limit concurrency per task, and understand serial’s effect on handlers,run_once, and magic variables ansible_play_batch .
Prerequisites: The deployment role from m3. Importance:★★★★★

What: serial changes the “unit of execution”

By default (strategy: linear, without serial), Ansible runs each task across all hosts (limited by forks concurrency) before moving to the next task. During a release, all nodes restart almost simultaneously, which is effectively a downtime release. With serial set, Ansible first splits the play’s hosts into batches,and each batch runs the entire play independently (pre_tasks → roles → tasks → post_tasks → handlers); the next batch starts only after this batch fully finishes.

Batch calculation (consistent with the ansible-core source)

SyntaxMeaningBatches for 10 hosts
serial: 11 host per batch1,1,1,1,1,1,1,1,1,1
serial: 33 hosts per batch; the remainder forms the last batch3,3,3,1
serial: "30%"Calculated from the total number of play hosts: int(30/100 × 10), and if the result is 0, use 13,3,3,1
serial: "25%"int(2.5) = 2 (rounded down)2,2,2,2,2
serial: [1, "30%", "100%"]Use the values in the list in order; once used up,repeat the last one1,3,6 (canary → small batch → all remaining)
serial: [1, 2]Same as above1,2,2,2,2,1

Why: why rolling updates also need a failure threshold

serial only controls “how many machines change at once”, not “what to do when something goes wrong”. The default behavior: after a host fails, it is dropped from this run,while the remaining hosts and later batches keep going; the play only stops when the hosts of a batch all fail. This means serial: 2 that if each batch has only one bad host, the bad version will spread to half the machines.

How: the precise semantics of the three knobs

KeywordScopePrecise semantics (official docs + source behavior)
max_fail_percentagePlay; with serial, calculated per batch.After each task finishes, calculate “number of failed hosts in this batch / number of hosts in this batch”,if this exceeds the threshold, the remaining hosts in this batch are also marked failed and the play aborts. Official example: serial: 10 + max_fail_percentage: 30 → in a batch of 10 hosts, more than 3 hosts (i.e., the 4th host) must fail before aborting; serial: 4 to stop after 2 failures, set 49, not 50.
any_errors_fatal: trueplay / block / taskIf any host fails, Ansible first lets the current batch finish that failing task, then stops the whole play across all hosts; later tasks and the play no longer run.
orderplayHost ordering: inventory (default: the order returned by the inventory, not necessarily the order written in the file),reverse_inventory,sorted,reverse_sorted, and shuffle. Ordering happens before batches are split.
throttletask / blockLimits the number of hosts this task runs on at the same time; it can only reduce concurrency; with forks/serial, it must be smaller to have an effect. Suitable for calling rate-limited APIs.

Effect of serial on other mechanisms

  • handlers: handlers run at the end of each batch rather than at the end of the whole play.
  • run_once: the official docs state that when used with serial, a run_once task runs once in each batch. To run only once overall, you need when: inventory_hostname == ansible_play_hosts_all[0].
  • Magic variables: ansible_play_batch = hosts still alive in the current batch; ansible_play_hosts = hosts still alive in this play (not limited by batch); ansible_play_hosts_all = all target hosts of this play (including failed ones). m6 uses these to compute “which hosts to remove from the LB”.
  • rescue: hosts rescue that are rescued are not counted as failures (recorded as rescued in PLAY RECAP) unless the rescue section triggers a fail fail.

When: how to choose batches

ScenarioRecommendation
2–4 application nodesserial: 1 + max_fail_percentage: 0
Dozens of nodes; canary first,serial: [1, "10%", "25%"], then increase batch size after the first batch, using pause plus manual confirmation
Database cluster (primary/replica)serial: 1 + order Replicas first, then the primary (or split into two plays by group)
Stateless “change everything at once” configs (e.g., sysctl)Do not set serial, but set max_fail_percentage to prevent large-scale failures

Comparison with similar mechanisms

Ansible serialK8s Deployment RollingUpdateAzure VMSS rolling upgrade
Batchserial (number / percentage / list)maxSurge / maxUnavailablemaxBatchInstancePercent
Failure thresholdmax_fail_percentageprogressDeadlineSeconds (no automatic rollback)maxUnhealthyInstancePercent, etc.
Health judgmenturi/wait_for tasks you writereadinessProbeApplication health extension / LB probe
Traffic removaldelegate_to you write (m6)EndpointSlice automaticPlatform automatic
Common misconceptions① “max_fail_percentage: 50 “If 1 host fails in a 2-host batch, the play stops”—no: 1/2 = 50% does not exceed 50. ② “If no threshold is set, one bad host stops the play”—only a fully failed batch stops it (with serial: 1, each batch is exactly one host, so it looks like “one failure stops the play”; with serial: 2, it does not). ③ “The percentage is calculated from the remaining hosts”—batch size is calculated from the total number of hosts in the play. ④ “run_once with serial runs only once”—it runs once per batch.

Sequence diagram: serial: 2, 4 hosts, max_fail_percentage: 0

Batch 1: app1, app2 pre_tasks remove roles deploy tasks health check post_tasks re-add handlers Batch 2: app3, app4 pre_tasks remove roles deploy app4 failed ✗ 1/2 = 50% > 0% → abort, no further execution Time → Result app1, app2: new version, in the LB · app3: new version but still “removed” (post_tasks not executed) app4: failed (the old version if a rescue rollback exists) and removed · app3 also shows failed in PLAY RECAP (marked by the threshold logic) → This is the “LB state after abort” that m6 must handle: healthy removed nodes must be re-added manually or automatically
Figure 5-1 Each batch runs the full play independently; the threshold is checked after every task and aborts when exceeded

Batch calculation example: serial: [1, "30%", "100%"], 10 hosts

1 int(0.3×10)=3 int(1.0×10)=10 → only 6 hosts remain, so take 6 CanarySmall-batch validationEverything remaining (after the list runs out, the last value repeats) Percentages are always relative to the play’s total host count (10), not to the number of hosts remaining
Figure 5-2 List-style serial is Ansible’s native “canary → gradual ramp-up”

Core animation: serial rolling-update timeline + failure-threshold abort

Set the parameters, then click “Play”. Each batch goes through, in order: Remove from the LB (delegate_to lb1, run_once once per batch) → Deploy (switch current + restart) → Health check (uri /healthz, retried with until) → Re-add to LB. Click a host block to make the new version fail its health check on that node. The terminal below shows the real output format you will see in the ansible-playbook rolling_update.yml output.

serial: order:
max_fail_percentage:
Batch:
Nodes in the lb1 upstream currently receiving traffic
Old version · in LBRemoved / deployingNew version · in LBFailed✗ = injected fault
Suggested things to try, in order:① serial 2, threshold “not set”, inject a fault on app3: the release keeps going to the end (one bad host does not stop it). ② Threshold 0: abort right after the health check of batch 2. ③ Threshold 50, serial 2: 1/2 does not exceed 50%, so it continues. ④ Turn off rescue: the failed node stays on the bad version and is removed. ⑤ serial list + inject a fault on app1: the canary batch stops it, with the smallest impact.

Keywords and commands

Keyword / commandPurposeExample
serialBatch sizeserial: [1, "30%", "100%"]
max_fail_percentageMaximum failure ratio per batch (must be exceeded to abort)max_fail_percentage: 0
any_errors_fatalAny failure stops everythingPlace on the play or a key block
orderHost orderorder: sorted
throttlePer-task concurrency limitthrottle: 1
ansible.builtin.pauseManual confirmation / observation windowwhen: ansible_play_batch == [ansible_play_hosts_all[0]] (pause only after the canary batch)
ansible-playbook --list-hostsView which hosts would be matched (does not show batches)Combine with order Estimate order
ansible-playbook --start-at-task / --limit @retryResume from a point after an abort, or rerun only some hosts--limit app3,app4
---
- name: observe batches (no changes)
  hosts: app
  gather_facts: false
  serial: [1, "100%"]
  order: sorted
  max_fail_percentage: 0
  tasks:
    - name: who is in this batch
      ansible.builtin.debug:
        msg: "batch={{ ansible_play_batch }} play_hosts={{ ansible_play_hosts }} all={{ ansible_play_hosts_all }}"
      run_once: true                 # once per batch

    - name: simulated deploy
      ansible.builtin.command: sleep 1
      changed_when: false

    - name: demo of a handler running at the end of each batch
      ansible.builtin.debug: { msg: "notify" }
      changed_when: true
      notify: batch done
  handlers:
    - name: batch done
      ansible.builtin.debug: { msg: "handler runs at the end of batch {{ ansible_play_batch }}" }
ansible-playbook serial_demo.yml
PLAY [observe batches (no changes)] ****
TASK [who is in this batch] ****
ok: [app1] => {
    "msg": "batch=['app1'] play_hosts=['app1', 'app2'] all=['app1', 'app2']"
}
...
RUNNING HANDLER [batch done] ****
ok: [app1] => { "msg": "handler runs at the end of batch ['app1']" }

PLAY [observe batches (no changes)] ****
TASK [who is in this batch] ****
ok: [app2] => {
    "msg": "batch=['app2'] play_hosts=['app1', 'app2'] all=['app1', 'app2']"
}

How to verify: Each batch prints again PLAY [...] the PLAY header; this is the most direct way to tell whether serial is working. Common errors: Putting serial on a task (it is a play keyword; on a task you get “'serial' is not a valid attribute for a Task”). Production use: Split CI logs by PLAY header and measure the time per batch.

throttle: limit concurrency when calling external APIs

- name: record the release in the CMDB (API allows at most 2 calls per second)
  ansible.builtin.uri:
    url: "https://cmdb.example.internal/api/deployments"
    method: POST
    body_format: json
    body: { host: "{{ inventory_hostname }}", version: "{{ myapp_version }}" }
  throttle: 2
  delegate_to: localhost

Lab 5: Use a serial list for a canary, inject a fault, and watch the abort (about 7 min)

Run the batch-observation playbook (see the “Commands” page’s serial_demo.yml), and confirm you see two PLAY [...] headers.
Minimal rolling release (LB removal not yet included; added in m6):
---
- name: basic rolling release
  hosts: app
  become: true
  serial: 1
  max_fail_percentage: 0
  order: sorted
  roles:
    - myapp
ansible-playbook rolling_basic.yml -e myapp_version=v2
for i in $(seq 6); do curl -s localhost:8080/ | grep -o '"version":"v[0-9]"'; done | sort | uniq -c
      6 "version":"v2"
Inject a fault: make only app2’s new version “break”, and observe the difference between default behavior and the threshold:
# -e applies to all hosts; to break only one host, use host_vars
echo 'myapp_broken: true' >> inventories/staging/host_vars/app2.yml
ansible-playbook rolling_basic.yml -e myapp_version=v3
PLAY [basic rolling release] ****
...
TASK [myapp : local health check /healthz] ****
ok: [app1]
...
PLAY [basic rolling release] ****
...
TASK [myapp : local health check /healthz] ****
FAILED - RETRYING: [app2]: local health check /healthz (10 retries left).
...
fatal: [app2]: FAILED! => {"attempts": 10, "changed": false, … "status": 500, "msg": "Status code was 500 and not [200]: HTTP Error 500: INTERNAL SERVER ERROR" …}

NO MORE HOSTS LEFT ****
PLAY RECAP ****
app1 : ok=13  changed=4  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
app2 : ok=10  changed=4  unreachable=0  failed=1  skipped=0  rescued=0  ignored=0

At this point app2 is running the bad version, and is still in the LB: curl localhost:8080/ Try a few more times; because / itself still works (only /healthz is broken), users may not notice—but if what breaks is /, nginx’s proxy_next_upstream http_502 http_503 also cannot rescue a 500. This is exactly why m6 removes nodes first and rolls back on failure.

Compare serial: 2 + no threshold (put both hosts in the same batch, one bad):
cp rolling_basic.yml rolling_basic.bak
sed -i 's/serial: 1/serial: 2/; /max_fail_percentage/d' rolling_basic.yml
ansible-playbook rolling_basic.yml -e myapp_version=v4 | grep -E "^(fatal|PLAY RECAP|app)"
mv rolling_basic.bak rolling_basic.yml

With 2 hosts there is only 1 batch; app1 succeeds and app2 fails—the “entire batch fails” condition is not met, so if later batches exist, they will continue. In a 10-host environment, this means the bad version spreads to part of every batch. The last line restores the file to serial 1 + threshold 0.

Cleanup: remove the fault injection and restore to v2:
sed -i '/myapp_broken/d' inventories/staging/host_vars/app2.yml
ansible-playbook rolling_basic.yml -e myapp_version=v2

Case 1: bad version spreads to half the cluster

Problem: 40 nodes serial: 10, no threshold set. The new version failed to start on about a quarter of the nodes because of kernel parameter differences. Since each batch had only 2–3 bad hosts, the whole release “completed successfully”, leaving 10 machines on the bad version and capacity dropping sharply. Fix: All release playbooks must set max_fail_percentage: 0 (checked by a custom ansible-lint rule); the first batch is a serial: [1, …] canary. Limitation: With a threshold of 0, any occasional failure (for example, an apt mirror hiccup) aborts the release—this is intentional: better to stop than to spread.

Case 2: protecting the primary with order

Problem: The database primary and replicas were patched together,serial: 1 but the inventory order put the primary first; restarting the primary interrupted application writes. Fix: Split into two plays (first hosts: db_replicas, then hosts: db_primary), or name hosts so that order: reverse_sorted sorts replicas before the primary. Limitation: Ordering that depends on naming conventions is fragile; the explicit “groups + multiple plays” approach is recommended.

Case 3: manual confirmation after the canary

Problem: Monitoring metrics take several minutes to reveal problems with the new version. Fix: use a serial list;serial: [1, "50%", "100%"], and in post_tasks add ansible.builtin.pause: prompt="Check the dashboard, then press Enter to continue", with the condition when: ansible_play_batch | length == 1 and inventory_hostname == ansible_play_hosts_all[0]. Limitation: AWX/AAP: interactive pause is not available; replace it with pause: minutes=10 observation window + automated metric checks (uri querying Prometheus), or use an approval node in the workflow.

Common errors and fixes

ERROR! 'serial' is not a valid attribute for a Task

Cause:serial is a play keyword.

Fix: Move it to the same level as hosts: . To limit concurrency for just one task, use throttle.

The release “succeeded” overall, but some nodes run the bad version (PLAY RECAP shows failed=1, exit code 2)

Cause: Not set: max_fail_percentage, so failed hosts are removed and the remaining batches continue.

Fix: Set max_fail_percentage: 0 or any_errors_fatal: true; in CI, judge the release result by ansible-playbook ’s exit code (2 on failure), not by the last line of output.

max_fail_percentage: 50, serial: 2, 1 host went bad but the play did not abort

Cause: The threshold must be “exceeded”; 1/2 = 50% does not exceed it.

Fix: To “stop on one bad host”, set 49 (or simply 0).

The run_once database migration ran once per batch

Cause: When used with serial, run_once runs once per batch (documented official behavior).

Fix: Move the migration to a separate play before the release play (hosts: app[0] or hosts: db); or when: inventory_hostname == ansible_play_hosts_all[0]; the migration itself must also be idempotent.

serial: "30%" in a 2-host staging environment gives only 1 host per batch, which is different from what you might expect

Cause:int(0.3 × 2) = 0 → take the minimum of 1.

Fix: This is expected behavior; use a number when you need a fixed batch size. Use --list-hosts and this module’s animation to estimate batches.

Command-line questions
1. Write a play header: 10 hosts, 1 canary host first, then 3, then all remaining; abort on any failure; sort by hostname.
- hosts: app
  serial: [1, 3, "100%"]
  max_fail_percentage: 0
  order: sorted
2. The last release aborted on app3; after the fix, continue the release only for app3 and app4.
ansible-playbook rolling_update.yml -e myapp_version=v2 --limit app3,app4
Scenario analysis
20 hosts,serial: "25%" and max_fail_percentage: 20. If one host fails in batch 2, what happens? And if two fail?

Batch size int(0.25×20)=5. 1/5 = 20%, which does not exceed 20%, so the release continues (the failed host is removed). 2/5 = 40% > 20%: after that task finishes, the remaining hosts in the batch are marked failed, the play aborts, and later batches do not run.

Verified instructional videos

▶
Ansible 101 - Episode 12 - Real-world Ansible Playbooks — Jeff Geerling
2020 · English · How real playbooks are organized; for serial details, follow this lesson and the official docs

No verified video on “serial / max_fail_percentage” was found; a storyboard script is provided below.

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: ten servers in a row, split by dashed boxes into groups of 1, 3, and 6.
Narration: serial splits hosts into batches. The list form starts with one canary, then a small validation batch, and finally a full ramp-up.
Shot 2 · 20–50s
Visual: the first group of servers turns yellow (removed), then blue (deploying), then green (healthy), and returns to the traffic pool.
Narration: each batch runs the entire play to completion before the next batch begins.
Shot 3 · 50–80s
Visual: one server in the second group turns red; an equation appears on screen: one divided by three, greater than zero, and a red “ABORT” stamp comes down.
Narration: max_fail_percentage is calculated per batch; once the threshold is exceeded, the play aborts, and the bad version does not keep spreading.
Shot 4 · 80–100s
Visual: two comparison cards: “Fifty: one bad host does not stop it” and “Forty-nine: one bad host stops it.”
Narration: note that it aborts only when the threshold is exceeded; matching the threshold exactly does not count.
or score ≥ 70% on the quiz

Module 6 · Zero downtime: delegate_to, run_once, health checks and rollback

38:00 – 46:00 · Each batch: remove from LB → drain → deploy → health check → re-add to LB; on failure, roll back this node and abort
8 mindelegate_to · run_once · wait_for drained · uri★★★★★
Learning objectives
  • Use delegate_to on the load balancer host to run tasks “on behalf of app hosts”, and explain that it changes only the connection target, not the variable context (inventory_hostname and variables still belong to the original host).
  • Use run_once + ansible_play_batch to make each batch change the LB config only once, avoiding multiple hosts modifying the same file concurrently (a race condition).
  • Split the release into pre_tasks (removal, drain) / tasks (deploy, check) / post_tasks (re-add, verify), and understand what it means that post_tasks does not execute when the play aborts.
  • Design three layers of rollback: single-node automatic rollback (block/rescue), full rollback (roll forward to the old version using the same zero-downtime path), and expand/contract for the database.
Prerequisites: The nginx_down_hosts, the m3 release directory, and the m5 serial and threshold settings. Importance:★★★★★

What: the five actions of a zero-downtime release

#ActionWhere it runsAnsible implementation
1Remove this batch’s nodes from the LBlb1 (delegated)template nginx.conf (this batch marked down) + reload,delegate_to + run_once
2Drain in-flight connectionsapp nodeswait_for: port=8000 state=drained
3Deploy the new versionapp nodesinclude_role: myapp (m3)
4Health + readiness checksapp nodesuri /readyz,until version equals the target version
5Re-add to LB and verify through the LBlb1 (delegated)Re-render (only failed nodes kept as down) + reload; uri access through the LB

Why: why serial alone is not enough

m5’s rolling_basic.yml restarts only one host at a time, but during the few seconds of restart nginx still sends requests to it: after gunicorn closes its listener, new connections are refused (nginx logs an error,proxy_next_upstream and can retry on another server); meanwhile requests already forwarded but not yet completed are safe only if they finish within gunicorn’s graceful_timeout window; otherwise they are cut off when the process exits (returning 502, and non-idempotent requests cannot be safely retried); passive health checks max_fails may also temporarily eject the node because of these errors, amplifying the instability. Remove first, then drain, so you can restart only once “no new requests come in and old requests have all completed”.

How: delegate_to, run_once, and magic variables

MechanismActual behaviorUsage in this lesson
delegate_to: lb1The task runs using lb1’s connection parameters (hostvars['lb1'] ansible_host/port/user of lb1); but template rendering,when and conditionals still use the variables of the original host (e.g., app1)LB-side variables (nginx_worker_connections,lb_public_port) must be explicitly passed in using hostvars[item].xxx .
run_once: trueRuns only once on the first host of the current batch; the result is copied to the other hosts in the batch; when combined with serial,once per batchchanges the LB config once per batch; “once per batch” is exactly what we want here
delegate_facts: trueFacts gathered by a delegated task are stored under the delegated host’s namecollecting IPs for app in m4
ansible_play_batchHosts still alive in the current batchNodes to remove in this batch
ansible_play_hosts_all | difference(ansible_play_hosts)Hosts that have already failed in this playStay down when re-added to the LB
wait_for: state=drainedPoll the local host /proc/net/tcp*, until there are no active connections on the specified portConfirm nginx no longer holds connections to this node
Why not let each host delegate separately to change the LB? If serial: 2 and you do not add run_once, app1 and app2 will simultaneously delegate to lb1 to render the same file, and the two tasks are unaware of each other: one writes “app1 down”, the other writes “app2 down”; the final result depends on who writes last—a classic race condition. Use run_once + ansible_play_batch to write the whole batch once, or use throttle: 1 (serial but still writes once each, requiring the template to express “accumulated” state; not recommended).

Three-layer rollback strategy

LayerTriggerActionTime
Single-node automatic rollbackHealth check fails on this noderescue: point current back to myapp_previous → restart → confirm healthy → fail abort the release (node stays removed, awaiting manual confirmation)Seconds
Full rollbackMonitoring finds a problem after the release completesUse the same rolling_update.yml -e myapp_version=v1: the release directory still exists, pip/copy have no changes, so only the link is switched and the service restarted, with the same batch-by-batch removala few seconds per batch
Databaseschema changesexpand/contract: this release only makes backward-compatible changes (adding columns, adding tables, adding nullable fields); dropping old columns is deferred until after the next version is stable. This way, old code can also run on the new schema, so code rollback is always safeCross-version

When: when this pattern is not enough

  • Only 1 app node: removing it means downtime—use at least 2 nodes, or switch to “blue-green on two ports on the same machine” (start the new version on 8001, switch the upstream, then stop the old process).
  • Long-lived connections (WebSocket / gRPC streams): draining may never finish; you must set a timeout and a client reconnection strategy.
  • Sessions held in process memory: removal loses sessions—move sessions to Redis or a database, or use session persistence at the LB and extend the drain time.
Common misconceptions① “delegate_to ① “After inventory_hostname it is lb1”—no, it is still app1; to get lb1’s variables you must use hostvars['lb1']. ② “A handler can be used to reload the LB”—a handler notified by a delegated task runs by default on the original host (app1), and only at the end of the section; both timing and location are wrong, so this lesson uses an explicit reload task. ③ “If the play aborts, the LB restores itself”—post_tasks does not run, and removed nodes stay removed; the runbook must include a step to “check and restore LB state” (ansible-playbook lb.yml).

Sequence diagram: one batch (serial: 1, app1)

Control nodelb1 (nginx)app1 ① template nginx.conf (app1 down) + validate ② systemctl reload nginx (new workers no longer pick app1) ③ wait_for port=8000 state=drained (old workers finish requests and close keepalive) ④ include_role myapp: copy / pip / switch current / restart ⑤ uri http://127.0.0.1:8000/readyz until 200 and version == v2 On failure → rescue: point current back to v1 → restart→ confirm healthy → fail (app1 stays down, release aborts) ⑥ template (only failed nodes down) + reload ⑦ uri http://127.0.0.1/ (via LB) = 200 app1 receives traffic again → next batch
Figure 6-1 ①②⑥⑦ are delegated to lb1 and run once per batch (run_once); ③④⑤ run locally on app1

State diagram: state of one app node during a release

Serving v1 Removed · draining Deploy v2 Health check Serving v2 Rolled back to v1 · stays removed · aborted 200 Failed Traffic enters a node only in the “Serving” state; nodes in other states are not in the upstream
Figure 6-2 A failed node stays in “rolled back, kept removed” until manually confirmed and re-added

Interactive: error-rate comparison of “with vs. without removal” under load-test traffic

Simulates continuous load testing (each tick, 6 requests are round-robin distributed by lb1 to app1/app2). After choosing a release method, click “Start release”. In “direct restart” mode, requests being processed at the moment of restart are interrupted and new connections are refused; “zero downtime” mode follows the order in Figure 6-1. The terminal shows the Ansible task output for each step (note that [app1 -> lb1] indicates delegation).

lb1
upstream: app1, app2
app1
v1 · serving
app2
v1 · serving
Choose a release method to begin.

Full rolling_update.yml

---
- name: database expand migration (before release, runs once, backward-compatible)
  hosts: db
  become: true
  become_user: postgres
  gather_facts: false
  tasks:
    - name: add nullable column (old code is not affected)
      community.postgresql.postgresql_query:
        db: "{{ myapp_db_name }}"
        query: ALTER TABLE hits ADD COLUMN IF NOT EXISTS note text

- name: zero-downtime rolling release of myapp
  hosts: app
  become: true
  serial: "{{ rolling_serial | default(1) }}"
  max_fail_percentage: 0
  order: sorted
  vars:
    lb_hosts: "{{ groups['lb'] }}"
    lb_template: roles/nginx_lb/templates/nginx.conf.j2
    # hosts that already failed in this play: stay down when re-added to the LB
    failed_so_far: "{{ ansible_play_hosts_all | difference(ansible_play_hosts) }}"

  pre_tasks:
    - name: read the current version (rollback target)
      ansible.builtin.stat:
        path: /opt/myapp/current
      register: myapp_current

    - name: record the previous version
      ansible.builtin.set_fact:
        myapp_previous: "{{ (myapp_current.stat.lnk_target | default('')) | basename }}"

    - name: remove this batch’s nodes from the LB (once per batch)
      ansible.builtin.template:
        src: "{{ lb_template }}"
        dest: /etc/nginx/nginx.conf
        validate: nginx -t -c %s
      vars:
        nginx_down_hosts: "{{ ansible_play_batch + failed_so_far }}"
        nginx_worker_connections: "{{ hostvars[item].nginx_worker_connections }}"   # LB variables come from the lb host
        lb_public_port: "{{ hostvars[item].lb_public_port }}"
      delegate_to: "{{ item }}"
      loop: "{{ lb_hosts }}"
      run_once: true
      register: lb_drain

    - name: reload LB
      ansible.builtin.systemd_service:
        name: nginx
        state: reloaded
      delegate_to: "{{ item }}"
      loop: "{{ lb_drain.results | selectattr('changed') | map(attribute='item') | list }}"
      run_once: true

    - name: wait for connections to this node to drain
      ansible.builtin.wait_for:
        port: "{{ myapp_port }}"
        state: drained
        timeout: 60

  tasks:
    - name: deploy and verify (roll back this node on failure)
      block:
        - name: deploy new version
          ansible.builtin.include_role:
            name: myapp

        - name: readiness check (database available and correct version)
          ansible.builtin.uri:
            url: "http://127.0.0.1:{{ myapp_port }}/readyz"
            return_content: true
          register: myapp_ready
          until: myapp_ready.status == 200 and myapp_ready.json.version == myapp_version
          retries: 10
          delay: 2
      rescue:
        - name: rollback: point current back to the previous version
          ansible.builtin.file:
            src: "/opt/myapp/releases/{{ myapp_previous }}"
            dest: /opt/myapp/current
            state: link
            force: true
          when: myapp_previous | length > 0

        - name: restart the old version
          ansible.builtin.systemd_service:
            name: myapp
            state: restarted

        - name: confirm the old version is healthy
          ansible.builtin.uri:
            url: "http://127.0.0.1:{{ myapp_port }}/healthz"
          register: rb_health
          until: rb_health.status == 200
          retries: 10
          delay: 2

        - name: abort release
          ansible.builtin.fail:
            msg: "{{ inventory_hostname }}: {{ myapp_version }} failed checks, rolled back to {{ myapp_previous }}; node stays removed. After confirmation, run ansible-playbook lb.yml to re-add it."

  post_tasks:
    - name: re-add to LB (failed nodes stay down)
      ansible.builtin.template:
        src: "{{ lb_template }}"
        dest: /etc/nginx/nginx.conf
        validate: nginx -t -c %s
      vars:
        nginx_down_hosts: "{{ failed_so_far }}"
        nginx_worker_connections: "{{ hostvars[item].nginx_worker_connections }}"
        lb_public_port: "{{ hostvars[item].lb_public_port }}"
      delegate_to: "{{ item }}"
      loop: "{{ lb_hosts }}"
      run_once: true
      register: lb_restore

    - name: reload LB
      ansible.builtin.systemd_service:
        name: nginx
        state: reloaded
      delegate_to: "{{ item }}"
      loop: "{{ lb_restore.results | selectattr('changed') | map(attribute='item') | list }}"
      run_once: true

    - name: verify through the LB
      ansible.builtin.uri:
        url: "http://127.0.0.1:{{ hostvars[item].lb_public_port }}/"
      delegate_to: "{{ item }}"
      loop: "{{ lb_hosts }}"
      run_once: true
SyntaxWhy
delegate_to: "{{ item }}" + loop: lb_hostsSupports multiple LBs (each one must be removed)
hostvars[item].nginx_worker_connectionsDelegation does not change the variable context, so LB group variables must be explicitly retrieved
selectattr('changed') | map(attribute='item')Reloads only the LBs whose config actually changed, replacing a handler
failed_so_far placed in play varsVariables are evaluated lazily, each time they are used, so they reflect the hosts that have failed “at that moment”
The readiness check compares json.versionprevents a false success while the old process still responds (for example, if the restart did not take effect)
# release / full rollback / two hosts per batch
ansible-playbook rolling_update.yml -e myapp_version=v2
ansible-playbook rolling_update.yml -e myapp_version=v1
ansible-playbook rolling_update.yml -e myapp_version=v2 -e rolling_serial=2

# after an abort, check and restore LB state
docker exec lb1 grep -n "server app" /etc/nginx/nginx.conf
ansible-playbook lb.yml

Lab 6: zero-downtime release v1 → v2 with 0 load-test errors; automatic rollback of a bad version (about 8 min)

Prepare the load-test client (in a separate terminal, send requests continuously and record only the status codes):
cd ~/ansible-lab/part6
while true; do curl -s -o /dev/null -m 2 -w "%{http_code}\n" localhost:8080/; sleep 0.05; done > load.log &
echo $! > load.pid
Control group: release v3 with m5’s rolling_basic (no removal):
: > load.log
ansible-playbook rolling_basic.yml -e myapp_version=v3 > /dev/null
sort load.log | uniq -c
    412 200
      3 502

The number of errors depends on timing: gunicorn tries to finish in-flight requests after receiving SIGTERM, and for GET requests that hit a connection error, nginx’s proxy_next_upstream error retry will send them to another server, so the control group may also show 0. But this is only a “lucky combination”: nginx does not retry non-idempotent requests such as POST by default; requests hitting a node max_fails marked down, a single-node setup, or TimeoutStopSec timed out by SIGKILL will return 502. Zero downtime must be guaranteed by the process, not by luck.

Experimental group: release v2 with rolling_update.yml (write the full playbook from the “Commands” page):
: > load.log
ansible-playbook rolling_update.yml -e myapp_version=v2
sort load.log | uniq -c
curl -s localhost:8080/ ; echo
TASK [remove this batch’s nodes from the LB (once per batch)] ****
changed: [app1 -> lb1] => (item=lb1)
TASK [reload LB] ****
changed: [app1 -> lb1] => (item=lb1)
TASK [wait for connections to this node to drain] ****
ok: [app1]
...
TASK [re-add to LB (failed nodes stay down)] ****
changed: [app1 -> lb1] => (item=lb1)
...
PLAY RECAP ****
app1 : ok=24  changed=9  unreachable=0  failed=0  skipped=2  rescued=0  ignored=0
app2 : ok=24  changed=9  unreachable=0  failed=0  skipped=2  rescued=0  ignored=0
db1  : ok=1   changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
    530 200
{"host":"app2","hits":618,"version":"v2"}
Bad version: inject a fault into app2 and release v3, and observe the rescue rollback:
echo 'myapp_broken: true' >> inventories/staging/host_vars/app2.yml
: > load.log
ansible-playbook rolling_update.yml -e myapp_version=v3; echo "exit=$?"
sort load.log | uniq -c
ansible app -b -a "readlink /opt/myapp/current"
docker exec lb1 grep "server app" /etc/nginx/nginx.conf
TASK [myapp : local health check /healthz] ****
FAILED - RETRYING: [app2]: local health check /healthz (10 retries left).
...
fatal: [app2]: FAILED! => {"attempts": 10, … "status": 500 …}
TASK [rollback: point current back to the previous version] ****
changed: [app2]
TASK [restart the old version] ****
changed: [app2]
TASK [confirm the old version is healthy] ****
ok: [app2]
TASK [abort release] ****
fatal: [app2]: FAILED! => {"changed": false, "msg": "app2: v3 failed checks, rolled back to v2; node stays removed. After confirmation, run ansible-playbook lb.yml to re-add it."}
NO MORE HOSTS LEFT ****
PLAY RECAP ****
app1 : ok=24  changed=9   unreachable=0  failed=0  skipped=2  rescued=0  ignored=0
app2 : ok=17  changed=7   unreachable=0  failed=1  skipped=0  rescued=1  ignored=0
exit=2
    498 200
/opt/myapp/releases/v3
/opt/myapp/releases/v2
        server app1:8000 max_fails=2 fail_timeout=5s;   # app1
        server app2:8000 max_fails=2 fail_timeout=5s down;   # app2

On the user side, everything is still 200: app1 is already v3 and serving, while app2 has rolled back to v2 and stays removed. Note that the cluster is now in a “mixed-version” state, and the next step requires a decision: roll forward after a fix, or roll back fully.

Decision: full rollback to v2 (same zero-downtime path):
sed -i '/myapp_broken/d' inventories/staging/host_vars/app2.yml
: > load.log
ansible-playbook rolling_update.yml -e myapp_version=v2
sort load.log | uniq -c
docker exec lb1 grep "server app" /etc/nginx/nginx.conf
    455 200
        server app1:8000 max_fails=2 fail_timeout=5s;   # app1
        server app2:8000 max_fails=2 fail_timeout=5s;   # app2

The v2 release directory still exists, so copy/pip are ok, and only the link switch and restart are changed; each batch takes only a few seconds. In post_tasks, failed_so_far is empty, so app2 is automatically re-added.

Cleanup: kill $(cat load.pid); rm -f load.log load.pid.

Case 1: multiple LBs, but only one was removed

Problem: Production has lb1 and lb2 (keepalived VIP), and the playbook hard-codes delegate_to: lb1, so when the VIP floated to lb2, the release produced many 502s. Fix: All delegated tasks must loop over loop: "{{ groups['lb'] }}"; in the verification stage, check each LB separately. Limitation: With many LBs, a serial loop gets slow; you can put the removal in a separate play (hosts: lb), run in parallel, and use hostvars/fact to pass the batch’s node list, but complexity is higher.

Case 2: removal from a cloud load balancer

Problem: On Azure, the application nodes sit in the Azure Load Balancer backend pool, and there is no nginx to change. Fix: Removal becomes a cloud API call: move the NIC’s IP configuration out of the backend pool (the network interface module of azure.azcollection), or make the health probe fail (for example, the application provides /readyz a maintenance switch file, so the probe fails and the node is removed automatically after a few cycles), then wait for probe interval × threshold. On AWS, the equivalent is deregistering from the ALB target group (community.aws.elb_target) and waiting for the deregistration delay. Limitation: Cloud APIs have rate limits and eventual consistency; when delegating to localhost calls, add retries and throttle.

Case 3: a database migration made rollback impossible

Problem: The v5 migration renamed a column username to login, a problem occurred mid-release, and nodes rolled back to v4 all reported errors (column does not exist). Fix: expand/contract: v5 adds a login column, dual-writes, and reads compatibly; the old column is removed only after v6 is stable username. The migration runs as a separate play before the release, executed only once. Limitation: It requires cooperation from the development process (migration review); Ansible can only guarantee execution order.

Common errors and fixes

AnsibleUndefinedVariable: 'nginx_worker_connections' is undefined (template task delegated to lb1)

Cause: Delegation changes only the connection target; the template uses the original host’s (app1) variables, whereas nginx_worker_connections is defined in the lb group.

Fix: In the task vars , use hostvars[item].nginx_worker_connections to pass them in (this lesson’s approach), or move these variables to the all group.

502s still occur during the release; the log shows the upstream still includes the node being deployed

Cause: The removal task does not reload, or the reload runs only after the deployment (a handler was used).

docker exec lb1 sh -c 'grep "server app" /etc/nginx/nginx.conf; tail -3 /var/log/nginx/myapp.log'

Fix: Make reload an explicit task in pre_tasks; confirm wait_for state=drained runs after reload.

wait_for: Timeout when waiting for 127.0.0.1:8000 to drain

Cause: Connections still exist: old nginx workers are still processing long requests, keepalive connections are not closed, or other clients (monitoring, batch jobs connecting directly) are connecting to port 8000.

ansible app1 -b -a "ss -tnp state established '( sport = :8000 )'"

Fix: Identify the source of the connections; for monitoring sources, use exclude_hosts; set a reasonable timeout and accept forced switching.

When two hosts are in the same batch, only one is marked down in the LB config

Cause: The delegated template task does not have run_once, so the two hosts write the same file concurrently (race condition), each marking only itself as down.

Fix: addrun_once: true + nginx_down_hosts: "{{ ansible_play_batch }}" to the delegated template task so one write covers the whole batch.

After the release aborts, healthy nodes stay out of the LB

Cause: post_tasks does not execute when the play aborts (an intentionally conservative design).

Fix: After confirming the cause of the failure, run ansible-playbook lb.yml (default nginx_down_hosts: []) to restore; write this step into the release runbook and the failure branch of the AWX workflow.

Command-line questions
1. In an app play, write a task that runs only once on lb1 and checks the nginx config syntax.
- name: check LB config
  ansible.builtin.command: nginx -t
  delegate_to: "{{ groups['lb'][0] }}"
  run_once: true
  changed_when: false
2. Check which version app2 runs after the last rollback, and when the process started.
ansible app2 -b -m ansible.builtin.shell -a 'readlink /opt/myapp/current; systemctl show myapp -p ExecMainStartTimestamp --value; curl -s localhost:8000/healthz'
Scenario analysis
The team changed rolling_serial to 2 and removed the final fail from the rescue, hoping for “bad nodes roll back, good nodes keep releasing”. What are the consequences? How would you change it?

Without the fail, rescued hosts are not counted as failures, so the release continues through all batches; the result is a mixed-version cluster, and in post_tasks the failed node will, because failed_so_far is empty, be re-added to the LB (it is running the old version at this point and looks “fine”), so the problem is masked. Keep the fail so the release aborts. If a “best-effort” release is truly needed, at minimum use set_fact in rescue to mark rolled-back nodes, generate a report in post_tasks, and make the playbook end in failure (for example, a final play checks the markers and fails).

Verified instructional videos

▶
Ansible 101 - Episode 12 - Real-world Ansible Playbooks — Jeff Geerling
2020 · English · Multi-host orchestration concepts (for details such as delegate_to, follow this lesson)

No verified video on “Ansible zero downtime + delegate_to LB removal” was found. The rolling upgrade example in the official docs (lamp_haproxy) is good supplementary reading.

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: the control node reaches a hand past app1 to flip app1’s switch on lb1; label “delegate to”.
Narration: delegate to makes the task run on the load balancer, but the variables still belong to app1.
Shot 2 · 25–50s
Visual: traffic balls no longer flow to app1; the last few balls on app1 finish and disappear, and “drained” appears.
Narration: remove first, wait for connections to drain, and only then deploy.
Shot 3 · 50–80s
Visual: after app1 is deployed, its health light turns green, the switch flips back, and the balls flow in again; app2’s health light turns red, the arrow turns back to the old version, the switch stays off, and a red “ABORT” appears.
Narration: re-add only after the health check passes; on failure, roll back this node and stop the release.
Shot 4 · 80–100s
Visual: on the database table, first add a column (expand); in the next version, remove the old column (contract).
Narration: database changes must be backward-compatible so that code rollback is always safe.
or score ≥ 70% on the quiz

Module 7 · Deploying to containers and Kubernetes

46:00 – 53:00 · The same myapp, now deployed with community.docker and kubernetes.core; Ansible shifts from “executor” to an orchestrator that “submits the desired state and verifies it”
7 mincommunity.docker 5.4.0kubernetes.core 6.6.0The helm module has been adapted for Helm 4★★★★☆
Learning objectives
  • Use docker_image_build to build images, and use docker_container (including state: healthy) and docker_compose_v2 (wait: true) to deploy, and understand their idempotent comparisons (comparisons,image_name_mismatch).
  • Use kubernetes.core.k8s to submit Deployment/Service (apply,wait,wait_condition), and use kubernetes.core.helm to install charts (atomic which corresponds to --rollback-on-failure in Helm 4).
  • Explain where these modules run (the control node or jump host, through the Docker API or kube-apiserver), and the division of labor between Ansible and K8s native rolling updates and GitOps.
Prerequisites: The Docker lesson (images, Compose);the K8s lesson’s kind cluster lab (optional). Importance:★★★★☆

What: module list (verified 2026-11)

Collection / modulePurposeRequirements (on the host that runs the module)
community.docker.docker_image_buildBuild images with BuildKit/DockerDocker API ≥ 1.25, Python requests; no longer needs the Docker SDK for Python (the collection has built-in derived code)
community.docker.docker_containersingle containers; state: started/present/stopped/absent/healthy
community.docker.docker_network / docker_volumenetworks and volumes
community.docker.docker_compose_v2 (and _pull/_exec/_run)Compose projects; state: present/stopped/restarted/absentDocker CLI + Compose plugin ≥ 2.18.0; the old docker_compose (v1) is no longer in the collection
kubernetes.core.k8sCreate/update/delete any K8s objectPython ≥ 3.9,kubernetes ≥ 24.2.0, PyYAML ≥ 3.11,jsonpatch
kubernetes.core.k8s_info / k8s_rollback / k8s_scale / k8s_drainquery, rollback, scale, evict
kubernetes.core.helm / helm_repository / helm_infoHelm release managementhelm binary (docs require ≥ 3.0.0; Helm 4 parameter mapping is supported)

Why: since you already have Compose / kubectl / Argo CD, why still use Ansible?

  • Cross-system orchestration:“run the database migration → update the Deployment → wait for Available → record in the CMDB → notify Teams” is one workflow, and Ansible is good at chaining different systems together.
  • One shared inventory and secrets: nginx on VMs, applications in containers, and services in K8s share group_vars and Vault.
  • Cluster bootstrapping: install foundational components such as Argo CD/Flux, cert-manager, and monitoring; applications afterwards are handed to GitOps.

How: where these modules run

TargetAnsible connects toModule actually callsWho handles the rollout
systemd VMs (m3–m6)each VM (SSH)Python on the managed node runs apt/pip/systemctlAnsible: serial + delegate_to
Docker hostDocker host (SSH), or localhost + docker_host: ssh://…Docker Engine API (/var/run/docker.sock): create/start/inspectSingle host: Compose rebuilds containers; multiple hosts: still Ansible serial
Kuberneteslocalhost (or jump host),hosts: localhostkube-apiserver over HTTPS: GET/PATCH/apply, then polls object statusDeployment controller (maxSurge/maxUnavailable + readinessProbe); Ansible only submits and waits

Key shift: on K8s do not use serial to change Pods one by one—that is the Deployment controller’s job. Ansible’s responsibilities are: submit the desired state (k8s state=present apply=true) → wait for convergence (wait: true + wait_condition: Available) → perform business validation → on failure, execute k8s_rollback or helm a rollback.

When: Ansible vs. GitOps

Ansible pushArgo CD / Flux (pull + continuous reconciliation)
TriggerWhen a CI/AWX job runsGit changes or scheduled reconciliation
Drift correctionCorrects only at run timeContinuous correction
Cross-system stepsStrongWeak (requires hooks/workflows)
Recommended forCluster bootstrap, releases with pre/post steps, mixed environmentsDay-to-day delivery of applications inside K8s
Common misconceptions① “k8s A module returning ok means the release succeeded”—without wait , it only means the apiserver accepted the object; the Pods may still be in CrashLoopBackOff. ② “The k8s module must run on a cluster node”—it only needs access to the apiserver’s kubeconfig, usually hosts: localhost. ③ “Changing environment variables in docker_container takes effect in place”—container config is immutable, so the module will delete and recreate the container (causing a brief interruption); for zero downtime, you still need LB removal or multiple replicas.

Architecture diagram: call paths for the three targets

Control nodeansible-playbookkubeconfig · Vault SSH SSH / docker_host HTTPS (local execution) VM: app1/app2Python module → apt / pip / systemctl Docker hostEngine API: /containers/create, /start kube-apiserverapply (PATCH) → poll status Deployment controllernew ReplicaSet · maxSurge/maxUnavailablereadinessProbe decides when to continue Rollout handled by Ansibleserial + delegate_to (m5/m6) Single host rebuilt by ComposeMultiple hosts still use serial
Figure 7-1 The more “platform-based” the target, the less Ansible operates processes directly, and the more it submits desired state and waits

Flowchart: Ansible driving one K8s release

docker_image_build+ push / kind load Migration Jobk8s + wait Complete k8s applyDeployment new image wait_conditionAvailable=True uri business validationvia Service/Ingress rescue:k8s_rollback Same structure as m6: pre (migration) → deploy → wait → verify → roll back on failure; the only difference is that “deployment and rollout” is handled by the platform
Figure 7-2 block/rescue also applies to K8s releases

Step-by-step animation: where modules run and which APIs they call

Choose a target, then click “Play”. Each step shows the calls Ansible actually makes (modules run over SSH, Docker Engine API requests, kube-apiserver requests) and who is responsible for the “rollout”.

Core parameters

ModuleKey parameters
docker_image_buildname,tag,path,dockerfile,args (build arguments),rebuild
docker_containerimage,state: healthy (3.11.0+, waiting for healthy_wait_timeout default 300 seconds),env,networks,published_ports,restart_policy,healthcheck,comparisons,pull: missing/always/never,image_name_mismatch (default recreate since 4.0.0)
docker_compose_v2project_src or definition (+ project_name),state,pull,recreate: auto/always/never,wait,wait_timeout,remove_orphans,files,env_files
kubernetes.core.k8sstate: present/absent/patched,definition/src/template,apply,server_side_apply: {field_manager},wait,wait_condition,wait_timeout (default 120),kubeconfig,context
kubernetes.core.helmname,chart_ref,chart_version,release_namespace,create_namespace,values/values_files,wait,atomic
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
ARG APP_VERSION=dev
ENV APP_VERSION=$APP_VERSION
RUN useradd -m appuser
USER appuser
EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0:8000", "--access-logfile", "-", "app:app"]
---
- name: deploy myapp + PostgreSQL with containers
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    image_tag: v2
    pg_password: "{{ myapp_db_password | default('S3cure-Lab-Pass') }}"
  tasks:
    - name: build image
      community.docker.docker_image_build:
        name: myapp-pg
        tag: "{{ image_tag }}"
        path: files/myapp
        args: { APP_VERSION: "{{ image_tag }}" }

    - name: network
      community.docker.docker_network: { name: myapp-net }

    - name: PostgreSQL container (wait for health)
      community.docker.docker_container:
        name: myapp-db
        image: postgres:16
        networks: [ { name: myapp-net } ]
        env:
          POSTGRES_USER: myapp
          POSTGRES_PASSWORD: "{{ pg_password }}"
          POSTGRES_DB: myapp
        volumes: [ "myapp-pgdata:/var/lib/postgresql/data" ]
        healthcheck:
          test: ["CMD-SHELL", "pg_isready -U myapp -d myapp"]
          interval: 5s
          retries: 10
        state: healthy
      no_log: true

    - name: create table (idempotent)
      community.docker.docker_container_exec:
        container: myapp-db
        command: >-
          psql -U myapp -d myapp -c "CREATE TABLE IF NOT EXISTS hits(id bigserial primary key,
          host text not null, version text not null, ts timestamptz not null default now())"
      changed_when: false

    - name: app container (wait for health)
      community.docker.docker_container:
        name: myapp-app
        image: "myapp-pg:{{ image_tag }}"
        networks: [ { name: myapp-net } ]
        published_ports: [ "127.0.0.1:9000:8000" ]
        env:
          DATABASE_URL: "postgresql://myapp:{{ pg_password | urlencode }}@myapp-db:5432/myapp"
        healthcheck:
          test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/readyz', timeout=2)"]
          interval: 5s
          retries: 5
        restart_policy: unless-stopped
        state: healthy
      no_log: true
---
- name: deploy myapp with kubernetes.core
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    ns: myapp
    image_tag: v2
  module_defaults:
    group/kubernetes.core.k8s:
      context: kind-lab
  tasks:
    - name: namespace
      kubernetes.core.k8s:
        api_version: v1
        kind: Namespace
        name: "{{ ns }}"

    - name: PostgreSQL (lab use: emptyDir, not persistent)
      kubernetes.core.k8s:
        namespace: "{{ ns }}"
        apply: true
        wait: true
        definition: "{{ lookup('ansible.builtin.template', 'k8s/postgres.yaml.j2') | ansible.builtin.from_yaml_all | list }}"

    - name: myapp Deployment + Service (apply and wait for Available)
      kubernetes.core.k8s:
        namespace: "{{ ns }}"
        apply: true
        wait: true
        wait_condition: { type: Available, status: "True" }
        wait_timeout: 180
        definition: "{{ lookup('ansible.builtin.template', 'k8s/myapp.yaml.j2') | ansible.builtin.from_yaml_all | list }}"

    - name: read Deployment status
      kubernetes.core.k8s_info:
        kind: Deployment
        namespace: "{{ ns }}"
        name: myapp
      register: dep

    - ansible.builtin.debug:
        msg: "image={{ dep.resources[0].spec.template.spec.containers[0].image }} ready={{ dep.resources[0].status.readyReplicas }}"

module_defaults ’s group/kubernetes.core.k8s action group sets default parameters for all k8s modules in the collection (such as context/kubeconfig). How to verify:kubectl -n myapp rollout status deploy/myapp. Common errors:“Failed to import the required Python library (kubernetes)”—Ansible installed with pipx needs pipx inject ansible kubernetes.

Lab 7: run myapp in local Docker; deploy a Deployment to a kind cluster (about 7 min)

Container deployment (write the Dockerfile and containers.yml from the “Commands” page):
cd ~/ansible-lab/part6
ansible-playbook containers.yml
curl -s localhost:9000/; echo
ansible-playbook containers.yml | tail -2       # second run: all ok (idempotent)
TASK [build image] ****
changed: [localhost]
TASK [PostgreSQL container (wait for health)] ****
changed: [localhost]
TASK [app container (wait for health)] ****
changed: [localhost]
...
{"host":"5f2c8a1d3b7e","hits":1,"version":"v2"}
PLAY RECAP ****
localhost : ok=6  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
Experience “config change = container rebuild”:
docker inspect -f '{{.Id}}' myapp-app | cut -c1-12
ansible-playbook containers.yml -e image_tag=v3
docker inspect -f '{{.Id}} {{.Config.Image}}' myapp-app | cut -c1-30
curl -s localhost:9000/; echo
3c1f0a9e7b21
...
8d4e2b6c0f13 myapp-pg:v3
{"host":"8d4e2b6c0f13","hits":2,"version":"v3"}

The container ID changed: after finding a mismatch in the image, the module deletes and recreates the container (image_name_mismatch: recreate). During a single-container rebuild there is brief unavailability; with multiple hosts, the m6 removal process is still needed.

(Optional) kind cluster: prepare dependencies and images.
pipx inject ansible kubernetes          # install the kubernetes client into Ansible’s venv
kind get clusters | grep -q '^lab$' || kind create cluster --name lab
kind load docker-image myapp-pg:v2 --name lab
mkdir -p templates/k8s
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp, labels: { app: myapp } }
spec:
  replicas: 2
  strategy: { type: RollingUpdate, rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } }
  selector: { matchLabels: { app: myapp } }
  template:
    metadata: { labels: { app: myapp } }
    spec:
      containers:
      - name: myapp
        image: myapp-pg:{{ image_tag }}
        imagePullPolicy: IfNotPresent
        ports: [ { containerPort: 8000 } ]
        env:
        - { name: DATABASE_URL, value: "postgresql://myapp:lab@postgres:5432/myapp" }
        readinessProbe: { httpGet: { path: /readyz, port: 8000 }, periodSeconds: 3 }
        livenessProbe:  { httpGet: { path: /healthz, port: 8000 }, periodSeconds: 10 }
---
apiVersion: v1
kind: Service
metadata: { name: myapp }
spec:
  selector: { app: myapp }
  ports: [ { port: 80, targetPort: 8000 } ]
apiVersion: v1
kind: ConfigMap
metadata: { name: pg-init }
data:
  init.sql: |
    CREATE TABLE IF NOT EXISTS hits(id bigserial primary key, host text not null,
      version text not null, ts timestamptz not null default now());
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: postgres }
spec:
  replicas: 1
  selector: { matchLabels: { app: postgres } }
  template:
    metadata: { labels: { app: postgres } }
    spec:
      containers:
      - name: postgres
        image: postgres:16
        env:
        - { name: POSTGRES_USER, value: myapp }
        - { name: POSTGRES_PASSWORD, value: lab }
        - { name: POSTGRES_DB, value: myapp }
        volumeMounts: [ { name: init, mountPath: /docker-entrypoint-initdb.d } ]
        readinessProbe: { exec: { command: ["pg_isready", "-U", "myapp"] }, periodSeconds: 3 }
      volumes: [ { name: init, configMap: { name: pg-init } } ]
---
apiVersion: v1
kind: Service
metadata: { name: postgres }
spec:
  selector: { app: postgres }
  ports: [ { port: 5432 } ]
ansible-playbook k8s.yml
kubectl -n myapp get deploy,pod,svc
TASK [myapp Deployment + Service (apply and wait for Available)] ****
changed: [localhost]
TASK [ansible.builtin.debug] ****
ok: [localhost] => { "msg": "image=myapp-pg:v2 ready=2" }
NAME                       READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/myapp      2/2     2            2           40s
deployment.apps/postgres   1/1     1            1           55s

The lab writes the password in plaintext in the inventory for demonstration only; production should use a Secret (injected by External Secrets or Vault).

(Optional) Helm: use the helm module to install the podinfo chart and observe atomic:
ansible localhost -m kubernetes.core.helm_repository -a "name=podinfo repo_url=https://stefanprodan.github.io/podinfo"
ansible localhost -m kubernetes.core.helm -a "name=demo chart_ref=podinfo/podinfo release_namespace=demo create_namespace=true wait=true atomic=true kube_context=kind-lab"
helm -n demo list
Cleanup:
docker rm -f myapp-app myapp-db; docker network rm myapp-net; docker volume rm myapp-pgdata
kubectl delete ns myapp demo --ignore-not-found

Case 1: Ansible bootstraps, Argo CD takes over

Problem: The platform team needs to install the same set of foundational components on 5 AKS clusters; afterwards, application teams self-serve releases through Git. Fix: An Ansible playbook (hosts: localhost, looping over kubeconfig contexts), using helm module to install Argo CD and cert-manager, using k8s module to create Argo CD’s Application root object; from then on, application releases no longer go through Ansible. Limitation: Avoid Ansible and Argo CD managing the same object at once (they will overwrite each other); use server_side_apply.field_manager to make the owner easy to identify.

Case 2: chaining the migration Job with the release

Problem: When migrations run as Helm hooks, failure information is hard to collect. Fix: Ansible first k8s Create the migration Job and wait_condition: {type: Complete}, on failure, k8s_log collect logs and abort; on success, apply the Deployment. Limitation:wait_condition It only waits for one condition; when the Job fails (Failed) it waits until timeout, so a reasonable wait_timeout, or switch to k8s_info + until polling that checks both conditions.

Case 3: Compose releases to edge sites

Problem: 200 stores each have one Docker host running a Compose application. Fix:docker_compose_v2 (pull: always,wait: true) combined with serial: [1, "5%", "20%"] and max_fail_percentage: 2, and failed stores roll back to the previous image tag. Limitation: The module docs warn that newer Compose plugins may break module compatibility; store hosts’ Docker/Compose versions must be pinned and verified in staging.

Common errors and fixes

Failed to import the required Python library (kubernetes) on … Python /home/…/pipx/venvs/ansible/bin/python

Cause: The k8s module runs on the control node and needs the kubernetes client in the Python environment where Ansible runs.

Fix:pipx inject ansible kubernetes (inject PyYAML and jsonpatch as needed too); for execution environments (EE), add the dependencies in the builder definition.

Error connecting: Error while fetching server API version: ('Connection aborted.', PermissionError(13, 'Permission denied'))

Cause: The current user has no permission to access /var/run/docker.sock.

Fix: Add the user to the docker group and log in again (note that the docker group is effectively root), or make the task become: true.

docker_compose_v2: Docker CLI … compose plugin … version is too old / unknown docker command: "compose"

Cause: The Compose plugin is missing or below 2.18.0.

Fix: Install docker-compose-plugin; the old docker_compose (v1) module no longer exists, so do not fall back to it.

"Failed to gather information about Deployment(s) even after waiting for 120 seconds"

Cause: wait timed out: the Pod is not ready (image pull failed, probe failed).

kubectl -n myapp get pod
kubectl -n myapp describe pod -l app=myapp | tail -20

Fix: Images built locally for kind must be kind load docker-image and imagePullPolicy: IfNotPresent; check whether /readyz returns 503 because the database is not ready; appropriately increase wait_timeout.

docker_container reports changed on every run (the container is repeatedly rebuilt)

Cause: Task parameters do not match the running container’s config format (e.g., port syntax, env values typed as numbers), or the image tag is latest and pull: always pulls a new image.

Fix: Quote all env values; pin image tags; use --diff to see the differences the module detects, and if necessary use comparisons to change an option to ignore.

Command-line questions
1. Use an ad-hoc command to scale the myapp Deployment in the kind cluster to 3 replicas and wait for completion.
ansible localhost -m kubernetes.core.k8s_scale -a "kind=Deployment name=myapp namespace=myapp replicas=3 wait=true context=kind-lab"
2. Roll the k8s Deployment back to the previous ReplicaSet.
ansible localhost -m kubernetes.core.k8s_rollback -a "api_version=apps/v1 kind=Deployment name=myapp namespace=myapp context=kind-lab"
Scenario analysis
Someone proposes: “On K8s, also use Ansible’s serial to delete Pods one by one to achieve a controlled rollout.” What do you think? Give the correct approach.

Not appropriate: Pods are managed by a ReplicaSet, so deleting a Pod just recreates it as the same version; this cannot achieve a version rollout, and it bypasses platform mechanisms such as readinessProbe/PDB. Correct approach: change the Deployment template (image tag), use maxSurge/maxUnavailable to control the pace, and Ansible’s k8s module wait waits for Available, performs business validation, and on failure, k8s_rollback; for a canary, use Argo Rollouts or Gateway API weighted routing.

Verified instructional videos

▶
Ansible in 100 Seconds — Fireship
English · 100-second overview of Ansible’s positioning (push-based, agentless)
▶
Kubernetes Explained in 100 Seconds — Fireship
English · Understanding why rollouts on K8s are handled by the controller

No verified video on the “kubernetes.core / community.docker modules” was found.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: the same myapp icon lands on three bases in turn: a VM, the Docker whale, and the K8s helm.
Narration: the same application can be deployed to a VM, a container, or Kubernetes; the way Ansible is written changes accordingly.
Shot 2 · 25–55s
Visual: Ansible hands K8s only a “desired state” card, then watches the controller replace Pods one by one.
Narration: on Kubernetes, rollouts are handled by the Deployment controller; Ansible is responsible for submitting, waiting, and verifying.
Shot 3 · 55–80s
Visual: after Ansible sets up Argo CD, it steps aside, and an arrow from the Git repository takes over the releases.
Narration: use Ansible to bootstrap the cluster and GitOps for day-to-day delivery; each does its own job.
or score ≥ 70% on the quiz

Module 8 · Comprehensive architecture review

53:00 – 60:00 · Use failure mode analysis (FMEA) to review this lesson’s three-tier architecture and release process: what happens when each component fails, how to detect it, and how to recover
7 minFMEA · review scorecard · incident drills★★★★☆
Learning objectives
  • Perform failure mode analysis item by item for lb / app / db / control node / release process: failure mode → impact → detection → mitigation → severity × occurrence × detectability (RPN).
  • Score the architecture with an 8-dimension review scorecard and identify the highest-priority improvements.
  • Drill four types of incidents in the lab environment (an app node goes down, the database is unavailable, the LB config is manually broken, and the control node disconnects mid-release), and recover following the runbook.
Prerequisites: m1–m7. Importance:★★★★☆

What: what an architecture review looks at

An architecture review is not “checking code style”; it answers four questions: Where are the single points of failure? When they break, what do users see? How long until we notice? How long until we recover? FMEA (Failure Mode and Effects Analysis) structures these questions:

ComponentFailure modeUser impactDetectionCurrent mitigationSODRPN
lb1Host downWhole site unavailableExternal probeNone (single point)103260
lb1Config manually brokenNo effect after reload / outage after restartnginx -t, config drift detectionvalidate; regular lb.yml --check --diff934108
app1/app2Single node downBrief errors (passive checks)max_fails, monitoring2 nodes + proxy_next_upstream44348
appBad version releaseSome requests failHealth checks, error rateserial + threshold 0 + rescue rollback74384
db1Database downAll writes fail site-wide (/readyz 503)pg_isready, /readyzNo replica; backup restore (RTO of tens of minutes)102240
db1Accidental data deletionData loss (writes after the backup)Application errorsdaily pg_dump + restore drills1025100
BackupBackup files on the same machine as the databaseBackups are lost together when the host is damaged—None1028160
Release processControl node disconnects mid-releaseNodes stuck in removed state, mixed versionsPLAY RECAP missingRe-runnable playbooks; restore with lb.yml63590
SecretsVault password leakedDatabase credentials exposedAuditVault + no_log827112

S = severity, O = occurrence likelihood, D = difficulty of detection, each 1–10; RPN = S × O × D. The values are example scores; teams should score based on their own business. After sorting, handle these first: Off-site backups (160), Vault password management (112), LB config drift (108), accidental data deletion (100).

Why: why do the review after automation

Automation makes the “happy path” reliable, but it also makes people assume the whole system is reliable. This lesson’s process ensures “releases don’t cause downtime”, but it cannot solve “only one LB” or “no database replica”. The value of the review is to make the risks that automation does not cover explicit, and to decide whether to accept or invest.

How: review scorecard (8 dimensions)

DimensionScore 0Score 2Current state in this lesson
RedundancySingle point in any tier≥ 2 per tier and across failure domainsapp is redundant; lb/db are single points
Release safetyRestart everything at onceBatches + threshold + health checks + automatic rollbackMet
RollbackableRequires rebuildingSecond-level code rollback + compatible data changesrelease directory + expand/contract
Data protectionNo backupsOff-site backups + PITR + regular drillsLocal backups + drills
ObservabilityProcess-level onlyProbes + metrics + logs + alertsHealth endpoints, journald
Config consistencyManual editsAll via Ansible, with regular drift detectionManaged by Ansible, no regular detection
SecurityPlaintext passwords, reachable from the whole networkVault, least-privilege access (pg_hba), TLSVault + pg_hba, no TLS
RunbookNoneEach type of incident has steps and has been drilledThis module’s lab

When: when to hold reviews and drills

  • Before a new architecture goes live; whenever a new component (cache, message queue) is introduced; a GameDay incident drill once a quarter; and in the post-mortem after every major incident.

Comparison with similar methods

FMEAAzure Well-Architected reviewChaos engineering
ApproachComponent-by-component scoringQuestionnaire by five pillarsInject faults in real environments
OutputRisk priority (RPN)Improvement recommendations listVerify assumptions and runbook
This lessonTheory + scorecardcan serve as supplementary materialIncident drills in the lab
Common misconceptions① “Having automation means high availability”—automation improves the reliability of changes, not component redundancy. ② “Having a backup is enough”—a backup on the same machine as production that has never been restored in a drill is as good as no backup. ③ “Drills might break the environment, so skip them”—drill regularly in staging, so the runbook is not run for the first time during a production incident.

Risk heat map: single points and blast radius of this lesson’s architecture

lb1 · single pointDown = whole site unavailableImprovement: 2 nodes + keepalived / cloud LB app1 / app2Single node down: capacity halvedRelease: zero downtime verified db1 · single pointDown = writes failImprovement: streaming replication / managed database Backupon the same machine as db1Improvement: replicate to object storage Control node / release processDisconnect mid-run → nodes may be stuck in removed stateImprovement: run on AWX/CI runnersplaybooks re-runnable; failure branch runs lb.yml Config driftSomeone edits nginx.conf by handImprovement: daily --check --diff jobAlert on any difference found SecurityVault password file on the control nodeNo TLS between LB and appImprovement: external secrets management + mTLS Red = single point (affects whole site) Yellow = process/data risk Green = existing redundancy and automation protection Blue = security hardening item
Figure 8-1 Automation covers the “release” row, but the red single points still require architectural investment

Flowchart: incident response and where Ansible fits

Alert / probe failureDetect ad-hoc diagnosisansible all -m … Stop the bleedingRemove / roll back Restore desired stateIdempotent rerun of site.yml Verify--check --diff Post-mortemUpdate FMEA “Idempotent rerun of site.yml” is the most powerful recovery tool for a system managed by Ansible: the desired state lives in Git
Figure 8-2 Ansible handles diagnosis, stopping the bleeding, and restoring the desired state during incident response

Interactive: architecture review scorecard + incident drill simulation

On the left, check the capabilities your architecture already has to get a live score and the “next most important improvement”; on the right, choose an incident and step through the system’s behavior and the matching Ansible commands in the runbook.

Review scorecard
Incident drill
Choose an incident.

Commonly used review and drill commands

CommandPurpose
ansible-playbook site.yml --check --diffDrift detection: any changed means production differs from Git
ansible-playbook site.yml --syntax-check / --list-tasksStatic checks and review of execution order
ansible-lintRule checks (detailed in lesson 7); you can add a custom rule “release playbooks must have max_fail_percentage”
ansible all -m ansible.builtin.ping -oConnectivity snapshot at the start of an incident
ansible app -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/readyz" -oReadiness state of each node
ansible app -b -a "readlink /opt/myapp/current"Whether it is in a mixed-version state
docker exec lb1 grep "server app" /etc/nginx/nginx.confRemoval state in the LB
docker stop app1 / docker exec db1 systemctl stop postgresqlFault injection in the lab environment
---
- import_playbook: site.yml
# How to run: ansible-playbook drift_check.yml --check --diff
# Verdict: changed > 0 in PLAY RECAP means drift exists; in CI/AWX, parse the exit code and recap to send alerts
# Judge drift in CI (use the JSON callback and count changed)
ANSIBLE_STDOUT_CALLBACK=ansible.posix.json ansible-playbook site.yml --check \
  | python3 -c 'import json,sys; s=json.load(sys.stdin)["stats"]; c=sum(v["changed"] for v in s.values()); print("drift" if c else "clean", c); sys.exit(1 if c else 0)'

ansible.posix.json The callback belongs to the ansible.posix collection (included in the community package). Note: In check mode, command/shell tasks are skipped by default, and some tasks (such as those depending on the result of a previous step) may report false positives, so use check_mode and changed_when appropriately in the playbook.

Lab 8: run an FMEA on this lesson’s architecture and drill four types of incidents (about 7 min)

Incident A: app node down (while the load test is running):
while true; do curl -s -o /dev/null -m 2 -w "%{http_code}\n" localhost:8080/; sleep 0.05; done > load.log & echo $! > load.pid
docker stop app1; sleep 10; sort load.log | uniq -c
docker start app1; ansible-playbook app.yml --limit app1   # restore desired state (idempotent)
    180 200
      2 502

Passive health checks must fail first before a node is skipped, so a few errors appear; HAProxy’s active checks (m2) can shorten this window. Record in FMEA: S=4, mitigation = active checks.

Incident B: database unavailable:
: > load.log
docker exec db1 systemctl stop postgresql; sleep 5
ansible app -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/readyz status_code=200,503" -o | grep -o '"status": [0-9]*'
ansible app -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/healthz" -o | grep -o '"status": [0-9]*'
docker exec db1 systemctl start postgresql
sort load.log | uniq -c
"status": 503
"status": 503
"status": 200
"status": 200
     95 200
     87 500

/healthz still returns 200: No is issued because of the database failure (correct). But user requests return 500—db is a single point, a red item in the FMEA.

Incident C: someone manually broke the LB config, detect and restore it with drift detection:
docker exec lb1 sed -i 's/max_fails=2/max_fails=20/' /etc/nginx/nginx.conf
ansible-playbook lb.yml --check --diff | grep -E '^[-+] .*server'
ansible-playbook lb.yml          # restore the desired state from Git and reload
-        server app1:8000 max_fails=20 fail_timeout=5s;   # app1
+        server app1:8000 max_fails=2 fail_timeout=5s;   # app1
Incident D: control node disconnects mid-release:
timeout 25 ansible-playbook rolling_update.yml -e myapp_version=v3; echo "exit=$?"
docker exec lb1 grep "server app" /etc/nginx/nginx.conf
ansible app -b -a "readlink /opt/myapp/current"
# Runbook: restore the LB first, then decide whether to roll forward or roll back
ansible-playbook lb.yml
ansible-playbook rolling_update.yml -e myapp_version=v2
exit=124
        server app1:8000 max_fails=2 fail_timeout=5s down;   # app1
        server app2:8000 max_fails=2 fail_timeout=5s;   # app2
app1 | CHANGED | rc=0 >>
/opt/myapp/releases/v3
app2 | CHANGED | rc=0 >>
/opt/myapp/releases/v2

At the time of disconnection, app1 was deployed but still removed—capacity is halved, but no error is reported (a safe failure). Because every step is idempotent, rerunning any playbook converges to the desired state. Running releases on AWX/CI runners avoids disconnects caused by “closing the laptop lid”.

Complete the FMEA table: using the table on the “Theory” page, fill in the S/O/D you observed for each incident, calculate RPN, and write the top three as improvement tickets. Cleanup:kill $(cat load.pid); rm -f load.log load.pid.

Case 1: the review found “backups on the same disk as the database”

Problem: One system made backups very diligently, but wrote them to the same disk as the database; in the FMEA this item has D=8 (only found when the disk fails), giving the highest RPN. Fix: Add an upload step to the backup script (to Azure Blob’s azcopy or az storage blob upload, using a managed identity); Ansible deploys the script and credentials; restore drills now download from object storage and restore from there. Limitation: Object storage must enable soft delete / immutability policies to prevent ransomware from deleting backups along with everything else.

Case 2: GameDay found that the runbook could not be executed

Problem: During the “release fails midway” drill, the on-call engineer did not know the LB state and did not have permission to run lb.yml. Fix: Create a “restore LB” job template in AWX and grant the on-call team access; the release workflow’s failure branch runs it automatically; the first runbook step becomes “run the check job and output each node’s version and LB state”. Limitation: Automatic recovery would also re-add failed nodes (if they run the bad version), so the failure branch restores only nodes that are “healthy and on a consistent version”.

Case 3: review conclusion—not every single point must be eliminated

Problem: The internal reporting system was also asked to implement active-active LBs and database streaming replication, doubling the cost. Fix: Reviewed against the business SLO: 4 hours of downtime per month is allowed; the conclusion is to accept the db single point, but off-site backups and restore drill records within 1 hour are required. Limitation: Accepted risk must be documented in writing with an owner, and reviewed again whenever the SLO changes.

Interactive troubleshooting tree: releases and the three-tier architecture

Start from the symptom and narrow down step by step; each conclusion comes with a diagnostic command and a fix.

Additional: common errors

ERROR! the playbook: rolling_update.yml could not be found

Cause: Not running in the project directory, or project sync failed in AWX. Fix:cd ~/ansible-lab/part6; in AWX, check the project sync log.

UNREACHABLE! => {"msg": "Failed to connect to the host via ssh: … Connection refused"} (after restarting containers)

Cause: The node container was stopped or sshd did not start. Fix:docker start app1,docker exec app1 systemctl status ssh; if the container is rebuilt, its IP may change, so remember to rerun db.yml to update pg_hba.

Command-line questions
1. Detect whether the whole environment has config drift with a single command, without making any changes.
ansible-playbook site.yml --check --diff
2. At the start of an incident, quickly collect the version, service state, and readiness state of all app nodes.
ansible app -b -m ansible.builtin.shell -a 'echo $(readlink /opt/myapp/current) $(systemctl is-active myapp) $(curl -s -o /dev/null -w %{http_code} localhost:8000/readyz)'
Scenario analysis
Give an improvement plan for this lesson’s architecture that uses “one week of engineering time”, and explain why it is in this order.

1) Off-site backups + automated restore drills (highest RPN, lowest cost, protect irreplaceable data); 2) a scheduled drift-detection job + automatic LB recovery in the release failure branch (reduce human error and release risk); 3) two LB nodes with keepalived, or switch to a cloud LB (eliminate the site-wide single point); 4) database streaming replication or migration to a managed database (highest cost and complexity; decide based on the SLO). Principle: protect data first, then reduce change risk, and finally eliminate single points.

Verified instructional videos

▶
What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners — TechWorld with Nana
English · Reviews Ansible’s overall positioning; good for aligning team vocabulary before a review
▶
Automate EVERYTHING with Ansible! (Ansible for Beginners) — Techno Tim
English · Automation practice from a home-lab perspective

No verified video on “FMEA / architecture review + Ansible” was found.

Reference documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: on the three-tier diagram, lb1 and db1 flash red, and app1 and app2 turn green.
Narration: automation makes releases safer, but a single point is still a single point.
Shot 2 · 25–55s
Visual: three numbers in a table are multiplied to get RPN and sorted by size; the top item is “backups on the same machine as the database”.
Narration: severity × occurrence × detectability; handle the highest-scoring risk first.
Shot 3 · 55–80s
Visual: the on-call engineer runs lb.yml per the runbook; the config differences disappear and all the lights turn green.
Narration: the desired state lives in Git; an idempotent rerun is the most reliable recovery method.
or score ≥ 70% on the quiz

Command cheat sheet

All key commands, keywords, and recommended config snippets in this lesson

Inventory and variables

ansible-inventory --graph
ansible-inventory -i inventories/production --graph
ansible-inventory --host app2
ansible app -m ansible.builtin.debug -a var=myapp_version
ansible-playbook site.yml --list-hosts --list-tasks
ansible-playbook site.yml --limit 'app:&staging'

Load balancing

ansible-playbook lb.yml --check --diff
ansible-playbook lb.yml -e '{"nginx_down_hosts": ["app1"]}'
docker exec lb1 nginx -t
docker exec lb1 grep "server app" /etc/nginx/nginx.conf
ansible lb -b -m ansible.builtin.systemd_service -a "name=nginx state=reloaded"

Application tier

ansible-playbook app.yml
ansible app -b -a "readlink /opt/myapp/current"
ansible app -b -a "systemctl show myapp -p ActiveState,MainPID"
ansible app -m ansible.builtin.uri -a "url=http://127.0.0.1:8000/readyz" -o
ansible app1 -b -a "journalctl -u myapp -n 30 --no-pager"

Data tier

ansible-playbook db.yml
ansible db -b --become-user postgres -m community.postgresql.postgresql_ping -a db=myapp
ansible db -b --become-user postgres -a /usr/local/bin/pg_backup.sh
ansible-playbook restore_drill.yml
ansible db -b --become-user postgres -m community.postgresql.postgresql_query \
  -a "query='SELECT * FROM pg_hba_file_rules'"

Rolling releases and rollback

ansible-playbook rolling_update.yml -e myapp_version=v2
ansible-playbook rolling_update.yml -e myapp_version=v2 -e rolling_serial=2
ansible-playbook rolling_update.yml -e myapp_version=v1      # full rollback
ansible-playbook rolling_update.yml -e myapp_version=v2 --limit app2
ansible-playbook lb.yml                                      # restore LB after an abort

Containers and Kubernetes

ansible-playbook containers.yml -e image_tag=v3
pipx inject ansible kubernetes
kind load docker-image myapp-pg:v2 --name lab
ansible-playbook k8s.yml
ansible localhost -m kubernetes.core.k8s_rollback \
  -a "api_version=apps/v1 kind=Deployment name=myapp namespace=myapp context=kind-lab"

Play keywords

- hosts: app
  serial: [1, "30%", "100%"]   # canary → small batch → all
  max_fail_percentage: 0       # must be “exceeded” to abort
  any_errors_fatal: false
  order: sorted                # inventory/reverse_inventory/sorted/reverse_sorted/shuffle

Delegation and once per batch

- name: remove this batch
  ansible.builtin.template: { src: nginx.conf.j2, dest: /etc/nginx/nginx.conf, validate: "nginx -t -c %s" }
  vars:
    nginx_down_hosts: "{{ ansible_play_batch }}"
    nginx_worker_connections: "{{ hostvars[item].nginx_worker_connections }}"
  delegate_to: "{{ item }}"
  loop: "{{ groups['lb'] }}"
  run_once: true               # once per batch under serial

Quick troubleshooting table

SymptomMost likely causeFirst command
validate fails: open() …/.ansible/tmp/…/mime.typesrelative include path in the templatechange to an absolute path
host not found in upstreamLB cannot resolve backend hostnamesansible lb -a "getent hosts app1"
delegated task variable undefinedDelegation does not change the variable contextUse hostvars[item].var
status=226/NAMESPACEsystemd sandbox restrictions in containersjournalctl -u myapp
externally-managed-environmentnot using a venvpip module with virtualenv
Failed to set permissions on the temporary filesbecome_user is an unprivileged user and acl is missingapt install acl
no pg_hba.conf entrymissing rule / not reloaded / IP changedansible-playbook db.yml
bad version spreads to multiple hostsmax_fail_percentage not setset to 0
nodes not in LB after abortpost_tasks not executed (expected behavior)ansible-playbook lb.yml
k8s module missing the kubernetes librarypipx venv not injectedpipx inject ansible kubernetes

Recommended config snippet: release playbook skeleton

- hosts: app
  serial: "{{ rolling_serial | default(1) }}"
  max_fail_percentage: 0
  order: sorted
  vars:
    failed_so_far: "{{ ansible_play_hosts_all | difference(ansible_play_hosts) }}"
  pre_tasks:   [record current version, remove this batch (delegate_to + run_once), reload LB, wait_for drained]
  tasks:
    - block:   [include_role deploy, uri /readyz until version == target]
      rescue:  [point link back to previous version, restart, confirm healthy, fail to abort]
  post_tasks:  [re-add to LB (failed_so_far stays down), reload, verify via LB]

Capstone lab + final quiz

nginx + 2 app nodes + PostgreSQL: build from scratch, zero-downtime rolling release, automatic rollback on failure, full rollback, backup and restore
After class ≈ 40 minIntegrating all modules
Scenario myapp is about to go live in staging. Review requirements: ① one command builds the complete three-tier architecture from blank nodes; ② during the v2 release, the load-test client receives only 200s; ③ when releasing the defective v3, it automatically rolls back on the first failed node and aborts, with users unaffected; ④ a full rollback is possible via the same path; ⑤ the database has recoverable backups. The managed nodes are the 4 systemd containers from Module 0 (or 4 small-spec VMs; just replace the addresses in the inventory).
Reset nodes (start from blank, Module 0)
docker rm -f lb1 app1 app2 db1
run_node(){ docker run -d --name "$1" --hostname "$1" --network ansnet --privileged --cgroupns=private \
  --tmpfs /run --tmpfs /run/lock -p "127.0.0.1:$2:22" "${@:3}" ansible-node-systemd:24.04; }
run_node lb1 2221 -p 8080:80; run_node app1 2222; run_node app2 2223; run_node db1 2224
sleep 5; cd ~/ansible-lab/part6 && ansible all -m ansible.builtin.ping -o
Build with one command (m1–m4): make sure site.yml imports common/db/app/lb, and that db.yml, app.yml, and lb.yml each reference their own role.
---
- name: base configuration for all nodes (also gathers facts for templates such as pg_hba)
  hosts: myapp
  become: true
  tasks:
    - name: time zone and base tools
      ansible.builtin.apt:
        name: [tzdata, curl, acl]
        state: present
        update_cache: true
        cache_valid_time: 3600
time ansible-playbook site.yml -e myapp_version=v1
ansible-playbook site.yml -e myapp_version=v1 | tail -6       # second run: changed=0
for i in 1 2 3 4; do curl -s localhost:8080/; echo; done
PLAY RECAP ****
app1 : ok=15  changed=0  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
app2 : ok=15  changed=0  unreachable=0  failed=0  skipped=1  rescued=0  ignored=0
db1  : ok=19  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
lb1  : ok=6   changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
{"host":"app1","hits":1,"version":"v1"}
{"host":"app2","hits":2,"version":"v1"}
...
Zero-downtime release of v2 (m5, m6)
while true; do curl -s -o /dev/null -m 2 -w "%{http_code}\n" localhost:8080/; sleep 0.05; done > load.log & echo $! > load.pid
ansible-playbook rolling_update.yml -e myapp_version=v2
sort load.log | uniq -c; ansible app -b -a "readlink /opt/myapp/current"
    612 200
app1 | CHANGED | rc=0 >>
/opt/myapp/releases/v2
app2 | CHANGED | rc=0 >>
/opt/myapp/releases/v2
Defective version v3: this time break app1 (the first batch)
echo 'myapp_broken: true' > inventories/staging/host_vars/app1.yml
: > load.log
ansible-playbook rolling_update.yml -e myapp_version=v3; echo "exit=$?"
sort load.log | uniq -c
ansible app -b -a "readlink /opt/myapp/current"
docker exec lb1 grep "server app" /etc/nginx/nginx.conf
fatal: [app1]: FAILED! => {… "msg": "app1: v3 failed checks, rolled back to v2; node stays removed. …"}
NO MORE HOSTS LEFT ****
exit=2
    401 200
app1 | CHANGED | rc=0 >>
/opt/myapp/releases/v2
app2 | CHANGED | rc=0 >>
/opt/myapp/releases/v2
        server app1:8000 max_fails=2 fail_timeout=5s down;   # app1
        server app2:8000 max_fails=2 fail_timeout=5s;   # app2

Canary effect: app2 is never touched, all nodes remain on v2, and users receive only 200s.

Fix and recover: remove the fault injection, restore the LB, then formally release v3; then rehearse a full rollback to v2.
rm inventories/staging/host_vars/app1.yml
ansible-playbook lb.yml
: > load.log
ansible-playbook rolling_update.yml -e myapp_version=v3
ansible-playbook rolling_update.yml -e myapp_version=v2      # full rollback
sort load.log | uniq -c
Data protection (m4)
ansible db -b --become-user postgres -a /usr/local/bin/pg_backup.sh
ansible-playbook restore_drill.yml
ansible-playbook site.yml --check --diff | tail -6       # drift detection: should all be changed=0 (m8)
(Optional) container / K8s version (m7): ansible-playbook containers.yml,ansible-playbook k8s.yml.
Cleanup: kill $(cat load.pid); rm -f load.log load.pid. Keep the nodes for lesson 7 (troubleshooting and optimization); to free resources: docker rm -f lb1 app1 app2 db1 && docker network rm ansnet. If you used Azure VMs: az group delete -n rg-ansible-lab --yes --no-wait.
Acceptance checklist

Open-ended self-check (answer on your own first, then expand the reference answer)

1. Why must both the LB backend list and the pg_hba rules be generated from the inventory?

Scaling only requires changing the inventory for all related configs to stay in sync, avoiding omissions from hand-written lists; during review, the inventory change alone shows the scope of impact.

2. serial: 2 and do not set max_fail_percentage, and one host per batch goes bad. What happens?

The failed host is removed, and the remaining hosts and later batches keep running, because the play only stops when an entire batch fails; the bad version spreads to one host per batch. You should set max_fail_percentage: 0.

3. For a template task delegated to lb1, which host do the template’s variables come from?

From the original host (e.g., app1). Delegation only changes the connection target; to get LB group variables, use hostvars['lb1'] or hostvars[item] .

4. Why doesn’t this lesson’s deployment role use a handler to restart the application?

Handlers run only at the end of a section, but the health check must target the new process; so restart immediately on change, then check.

5. What is the LB state when a release aborts? Why is it designed this way?

post_tasks does not run, so this batch’s nodes stay removed; even if a failed node has rolled back, it is not automatically re-added. This is a conservative design: it is better to lose capacity than to send traffic to unverified nodes. To restore, use lb.yml.

6. When should you stop using “Ansible serial rolling” and hand the job to the platform?

When the target is Kubernetes (the Deployment controller handles rollouts) or a managed cloud service (VMSS/ECS and similar have native rollouts and health probes); Ansible steps back to submitting desired state, waiting, verifying, and cross-system orchestration.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for the technical facts in this lesson (verified: 2026-11-15)
TopicVerified conclusionSource (accessed 2026-11-15)
ansible-core / community packagecore 2.21 (2026-05 GA, EOL 2027-11), 2.20, and 2.19 (EOL 2026-11) are maintained; community package 14.x is based on core 2.21; control node Python 3.12–3.14, managed node 3.9–3.14Release and maintenance
serial / order / throttle / run_onceserial supports numbers, percentages, and lists (can be mixed; the last value repeats); percentages are calculated from the play’s total host count, at least 1 per batch; order has five values; throttle can only reduce concurrency; under serial, run_once executes once per batch, and “execute only once” uses ansible_play_hosts_all[0] a conditionControlling playbook execution
max_fail_percentage / any_errors_fatal“The percentage set must be exceeded, not equaled”; when used with serial, it is calculated per batch; any_errors_fatal first completes the failing task in the current batch, then stops the whole playError handling in playbooks
community.postgresql4.2.0; 23 modules (including postgresql_user/db/table/privs/pg_hba/query/ping, postgresql_alter_system); postgresql_set is deprecated; requires psycopg2 ≥ 2.5.1 or psycopg3 ≥ 3.1.8; the pg_hba module does not handle reload; the db module’s dump/restore states do not need psycopg; to avoid peer authentication failures, use become_user postgrescommunity.postgresql
community.docker5.4.0; Compose has only the docker_compose_v2 series (requires Compose plugin ≥ 2.18.0); docker_container does not depend on the Docker SDK for Python (requires requests and Docker API ≥ 1.25),state: healthy since 3.11.0,image_name_mismatch default recreate since 4.0.0community.docker
kubernetes.core6.6.0; k8s requires Python ≥ 3.9, kubernetes ≥ 24.2.0, PyYAML ≥ 3.11, jsonpatch; wait_timeout defaults to 120; the helm module requires helm ≥ 3.0.0; under Helm 4, atomic is mapped to --rollback-on-failurekubernetes.core
community.general.haproxycommunity.general 13.5.1; state enabled/disabled/drain; socket default /var/run/haproxy.sock; requires an admin-level sockethaproxy module
Delegation and wait_fordelegate_to / delegate_facts / run_once; wait_for’s state: drainedDelegation · wait_for
nginx / PostgreSQLreload signal semantics, upstream parameters; pg_hba first match, pg_dump formatnginx control · pg_hba.conf

Video verification notes

The following videos were verified on 2026-11-15 via the YouTube oEmbed endpoint, with titles and channels matching: Jeff Geerling, “Ansible 101 - Episode 2 - Ad-hoc tasks and Inventory” (7kVfqmGtDL8), “Episode 4 - Your first real-world playbook” (SLW4LX7lbvE), “Episode 5 - Playbook handlers, environment vars, and variables” (HU-dkXBCPdU), “Episode 6 - Ansible Vault and Roles” (JFweg2dUvqM), “Episode 12 - Real-world Ansible Playbooks” (_QZr4xKhir4); Fireship, “Ansible in 100 Seconds” (xRMPKQweySE) and “Kubernetes Explained in 100 Seconds” (PziYflu8cB8); TechWorld with Nana, “What is Ansible | Ansible Playbook explained | Ansible Tutorial for Beginners” (1id6ERvfozo); Techno Tim, “Automate EVERYTHING with Ansible! (Ansible for Beginners)” (w9eCU4bGgjQ). oEmbed does not return durations or dates; the 2020 years for the Jeff Geerling series come from the author’s blog. No verified videos were found for the serial/delegate_to zero-downtime, community.postgresql, and kubernetes.core topics, so storyboard scripts are provided instead. All videos are in English and predate ansible-core 2.21; for details, follow this lesson and the official docs.

Audio narration notes

The “Audio” page uses the browser’s Web Speech API (en-US) to read the narration aloud in real time; English terms are pronounced with en-US; results depend on the voice packs installed on the system. This courseware cannot embed MP3; if offline audio is needed, pass the narration script to a TTS service to generate it.

Known limitations

  • The lab commands were not actually executed in the generation environment; the IPs, container IDs, PIDs, counts, times, and ok/changed numbers in the “expected output” are all example values.
  • The managed nodes are privileged containers running systemd and differ from real VMs (sandbox options, cgroups, networking); unsuitable parts are explained in troubleshooting, and they can also be replaced with small-spec VMs.
  • IPs change when containers are rebuilt, so db.yml must be rerun to update pg_hba; in production, use fixed internal addresses or subnet rules.
  • gunicorn’s systemd notification (Type=notify) and nginx upstream resolve parameters follow the official docs for the installed version; for nginx/PostgreSQL versions in the Ubuntu 24.04 repository, the version actually installed by apt applies (PostgreSQL defaults to 16).
  • The Python dependency version ranges in requirements are examples; pin to the actual versions on PyPI.
  • The times, request counts, and error rates in the animations are illustrative values used to explain the mechanism; batch calculation and threshold checks follow the ansible-core docs and source logic.
  • The S/O/D scores in the FMEA are examples; the team should assess them against its business SLOs.