Ansible Real-World Project: Deploy a Production Web App from Zero (Terraform + Ansible + CI/CD)

TL;DR

  • What you build: four servers (lb-1, app-1, app-2, db-1), four roles (common, postgres, app, nginx_lb), two playbooks (site.yml from zero, deploy.yml for every new version), a Flask API with a /health endpoint, PostgreSQL with its password in Ansible Vault, and a GitHub Actions workflow that deploys on push.
  • Where it runs: on your laptop with Docker (four systemd containers, free) or on Google Cloud, AWS or Azure with the Terraform in infra/. The playbooks do not know the difference; one inventory variable, private_ip, makes them portable.
  • Measured on a clean machine (ansible-core 2.21.5, Docker Compose 2.38.2, 2026-10-16): make site built the whole stack in 117.9 seconds, a second make site took 52.2 seconds and changed 0 tasks, make deploy VERSION=1.1.0 took 22.1 seconds while a loop hit the load balancer twice a second: 46 requests, 0 failures, versions seen 1.0.0 then 1.1.0.
  • Safety net, proven: a deploy with a broken database URL on app-1 failed on app-1 after the 60-second port wait, and every request to the load balancer was answered by app-2 on the old version. The roll-forward to 1.1.1 took 30.1 seconds.
  • Measured on real clouds (2026-10-20): AWS, make site INV=cloud 169 seconds, rolling deploy 47 seconds with 84 requests and 0 failures. Google Cloud, 246 and 56 seconds, 92 requests and 0 failures. terraform destroy afterwards, every time.
  • Five things broke and are fixed below: sshd refused the mounted key on a Linux host whose user is not uid 1000, ansible-core 2.19+ rejects {{ app_name }} in a play name, cache_valid_time: 3600 skipped apt update on a freshly built image, samenet in pg_hba.conf matches nobody on Google Cloud where every NIC is a /32, and my own GCP startup script held the apt lock for eight minutes.
  • Code: project-01-production-web-app.
  • Not your exact case? If you need the four-server lab first, read Ansible lab on your laptop with Docker; if Ansible itself is new, start with the Ansible full course.

The video walks through this whole project on the laptop lab, and it is Part 1 of a 4-part series: AWS, Google Cloud and Azure with Terraform come next. It premieres on 27 October 2026 at 15:30 UTC. The chapters, with the section of this post that covers the same step:

Introduction

Most Ansible tutorials stop at "install nginx". This one does not. I am going to build what a real team ships:

Project 01 overview: three Ansible playbooks run from your laptop or GitHub Actions against four servers (nginx load balancer, two Flask app servers, PostgreSQL) that live either in Docker on your laptop or as Terraform-created VMs on GCP, AWS or Azure

  • Terraform creates the four servers (or Docker gives you four containers on your laptop, for free)
  • Ansible configures everything with four roles: common, postgres, app, nginx_lb
  • Ansible Vault keeps the database password out of git
  • A rolling deploy with serial: 1 and a health gate, so users never see a 502
  • GitHub Actions runs that deploy on every push to main

And the whole thing works the same way on Docker, Google Cloud, AWS and Azure. Pick the one you have access to; the playbooks do not know the difference.

Everything lives in the project-01-production-web-app folder of my Ansible course repo: github.com/rahulwagh/ansible-zero-to-expert-masterclass.

In this post:

  1. Where to run it: laptop or cloud
  2. The application we deploy
  3. Inventory: one variable makes it portable
  4. The four roles
  5. site.yml: the whole stack from zero
  6. deploy.yml: zero-downtime rolling deploy
  7. A deploy that fails on purpose
  8. CI/CD with GitHub Actions
  9. HTTPS with Let's Encrypt
  10. What broke when I ran this
  11. Troubleshooting

If some of the building blocks below are new to you (inventory groups, group_vars, templates, handlers, Vault), they are covered step by step in my course: Ansible Zero to Hero on Udemy, and the free chapter list is in Ansible full course - zero to hero. This project is what you build after it.

1. Where to run it: laptop or cloud

1git clone https://github.com/rahulwagh/ansible-zero-to-expert-masterclass.git
2cd ansible-zero-to-expert-masterclass/project-01-production-web-app
3make deps                     # Galaxy collections: community.postgresql, community.general
4echo ansible-demo > .vault_pass   # the demo vault password (gitignored); change it later with ansible-vault rekey

Option A: Docker on your laptop (free)

infra/docker/ starts four Ubuntu 22.04 containers that run real systemd and sshd. Ansible treats them exactly like VMs, the same trick as my Ansible lab on a laptop with Docker. The one thing worth knowing: the containers share the host's cgroup namespace (cgroup: host), because without it systemd cannot supervise forking services such as PostgreSQL. The lab.sh script handles that, and falls back to plain docker run if your Docker Compose is older than 2.15.

1make lab-up

This is the real output on my test machine. The image build is the slow part, about 2 minutes the first time, and the ping at the end is what tells you the lab is usable:

 1$ make lab-up
 2./infra/docker/lab.sh up
 3==> Creating SSH key /tmp/azm/project-01-production-web-app/infra/keys/lab
 4==> Creating /tmp/azm/project-01-production-web-app/.vault_pass with the demo vault password (ansible-demo). Change it with: ansible-vault rekey
 5==> docker compose: building the node image (first run ~2 min) and starting lb-1 app-1 app-2 db-1
 6 Container app-1  Started
 7 Container db-1   Started
 8 Container app-2  Started
 9 Container lb-1   Started
10==> Waiting for SSH
11==> Ping
12db-1  | SUCCESS => {"changed": false, "ping": "pong"}
13app-2 | SUCCESS => {"changed": false, "ping": "pong"}
14app-1 | SUCCESS => {"changed": false, "ping": "pong"}
15lb-1  | SUCCESS => {"changed": false, "ping": "pong"}
16
17$ docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
18NAMES     STATUS              PORTS
19app-1     Up About a minute   80/tcp, 0.0.0.0:2232->22/tcp
20lb-1      Up About a minute   0.0.0.0:2231->22/tcp, 0.0.0.0:8080->80/tcp, 0.0.0.0:8443->443/tcp
21db-1      Up About a minute   80/tcp, 0.0.0.0:2234->22/tcp
22app-2     Up About a minute   80/tcp, 0.0.0.0:2233->22/tcp

Port map: localhost:8080 is lb-1's port 80. SSH is 2231 to 2234. If the ping says Permission denied (publickey,password) instead, you are on a Linux host whose user is not uid 1000; the fix is one chown and it is explained in the what broke section.

Option B: Google Cloud, AWS or Azure (Terraform)

Each infra/<cloud>/ folder provisions the same four servers, opens 22/80/443 from the internet and everything between the servers inside the VPC, installs your public key for an ansible user, and, this is the useful part, prints a ready-made inventory:

1ssh-keygen -t ed25519 -f infra/keys/lab -N ""
2cd infra/gcp                                  # or infra/aws · infra/azure
3cp terraform.tfvars.example terraform.tfvars  # gcp: project_id · azure: subscription_id · aws: nothing needed
4terraform init && terraform apply
5cd ../..
6./scripts/gen-inventory.sh gcp                # writes ansible/inventory/cloud.ini
7make ping INV=cloud

The generated inventory looks like this:

 1[loadbalancers]
 2lb-1  ansible_host=34.68.10.21 private_ip=10.20.0.2
 3
 4[appservers]
 5app-1 ansible_host=34.68.10.22 private_ip=10.20.0.3
 6app-2 ansible_host=34.68.10.23 private_ip=10.20.0.4
 7
 8[dbservers]
 9db-1  ansible_host=34.68.10.24 private_ip=10.20.0.5
10
11[all:vars]
12ansible_user=ansible
13ansible_ssh_private_key_file=../../infra/keys/lab
14ansible_python_interpreter=/usr/bin/python3

Four small VMs cost roughly $0.05 to $0.08 per hour on any of the three clouds. terraform destroy when you are done. The split of work here, Terraform for the servers and Ansible for everything inside them, is the one I argue for in Terraform for on-premises infrastructure as well; the playbooks are the part that does not change when the platform does.

The 7 commands you will use, explained visually

Everything in this project is driven by seven short commands. Each one is a line in the project's Makefile that stands in for a longer command. The explorer below draws what each command does, one box at a time: press Next (or the → key) to reveal the next step, ↓ to jump to the next command, and ⤢ Present for fullscreen. The left column lists only the files that command reads, creates or keeps secret.

command 1 of 7

make lab-up

runs

Files this command touches

readscreatessecret, not in git
→ next step · ← back · ↓ ↑ jump between commands · space auto-play · click the diagram to enlarge it, esc to close
You typeIt really runsMeasured on my run
make depsansible-galaxy collection install -r requirements.yml -p collectionscollections already present
make lab-up./infra/docker/lab.sh up89 s including the image build
make pingansible -i inventory/docker.ini all -m ping4 pongs
make siteansible-playbook -i inventory/docker.ini site.yml117.9 s from zero, 52.2 s with nothing to do
make deploy VERSION=1.1.0ansible-playbook -i inventory/docker.ini deploy.yml -e app_version=1.1.022.1 s, 0 failed requests
make smokeansible-playbook -i inventory/docker.ini smoke-test.yml10 requests, 1 version
make lab-down./infra/docker/lab.sh downinstant

Add INV=cloud to any of the Ansible ones (make site INV=cloud) to run against inventory/cloud.ini instead of the Docker lab.

2. The application we deploy

app/app.py is a small Flask API, but it is a real one: it talks to PostgreSQL, it has a /health endpoint the load balancer and the deploy use, and it prints its version and which server answered, so you can watch a rolling deploy happen in the browser.

EndpointPurpose
GET /HTML page: version, server name, DB status, note count
GET /health{"status":"ok","version":"1.0.0","server":"app-1","db":"ok"}
GET /api/notes · POST /api/notesnotes stored in PostgreSQL

It is configured entirely through environment variables, which Ansible writes into /opt/notes-api/.env:

1DATABASE_URL=postgresql://notes:<vault-secret>@db-1:5432/notes
2APP_VERSION=1.0.0

Through the load balancer, after make site, the two app servers alternate and the notes land in PostgreSQL:

 1$ curl -s http://localhost:8080/health
 2{"db":"ok","server":"app-1","status":"ok","version":"1.0.0"}
 3$ curl -s http://localhost:8080/health
 4{"db":"ok","server":"app-2","status":"ok","version":"1.0.0"}
 5
 6$ curl -s -X POST -H 'Content-Type: application/json' -d '{"text":"hello from the repro run"}' http://localhost:8080/api/notes
 7{"created_on":"app-1","id":1,"text":"hello from the repro run"}
 8$ curl -s http://localhost:8080/api/notes
 9[{"created_at":"2026-10-16T22:43:33.224720+00:00","created_on":"app-1","id":1,"text":"hello from the repro run"}]
10
11$ curl -s -o /dev/null -w 'GET / -> HTTP %{http_code}, %{size_download} bytes in %{time_total}s\n' http://localhost:8080/
12GET / -> HTTP 200, 896 bytes in 0.009766s

3. Inventory: one variable makes it portable

Every host carries a private_ip. On the clouds it is the VPC address. On the Docker lab it is simply the container name, because Docker's embedded DNS resolves db-1 and app-1 on the compose network:

1[appservers]
2app-1 ansible_host=127.0.0.1 ansible_port=2232 private_ip=app-1

Every place that needs "how do servers reach each other" uses that variable and nothing else:

1# group_vars/all/main.yml
2db_host: "{{ hostvars[groups['dbservers'][0]]['private_ip'] }}"
1# roles/nginx_lb/templates/notes-api.conf.j2
2upstream notes_api {
3{% for host in groups['appservers'] %}
4    server {{ hostvars[host]['private_ip'] }}:{{ app_port }} max_fails=1 fail_timeout=5s;
5{% endfor %}
6}

That is the whole secret to "works on four platforms". The SSH side of the inventory, one key for the ansible user on every host, is the setup from SSH keys with Ansible.

4. The four roles

common

Base packages, hostname, and /etc/hosts entries so every server can reach the others by name. Note the two container-aware conditions: hostname is skipped on Docker (the container already has it) and /etc/hosts is only written when private_ip is an actual IP.

postgres

 1- name: Allow each app server to connect (password auth)
 2  ansible.builtin.lineinfile:
 3    path: "/etc/postgresql/{{ postgres_version }}/main/pg_hba.conf"
 4    line: "host    {{ db_name }}    {{ db_user }}    {{ _src }}    scram-sha-256"
 5  vars:
 6    _ip: "{{ hostvars[item]['private_ip'] }}"
 7    _src: "{{ (_ip is match('^\\d+\\.\\d+\\.\\d+\\.\\d+$')) | ternary(_ip ~ '/32', 'samenet') }}"
 8  loop: "{{ groups['appservers'] }}"
 9  notify: Restart postgresql
10
11- name: Apply config changes before creating the database
12  ansible.builtin.meta: flush_handlers
13
14- name: Database user (password comes from Ansible Vault)
15  community.postgresql.postgresql_user:
16    name: "{{ db_user }}"
17    password: "{{ db_password }}"
18  become_user: postgres
19  no_log: true

Two details that bite people. First, the loop writes one pg_hba.conf line per app server, 10.20.0.2/32 and so on, instead of the tempting one-liner samenet. I had samenet here until the Google Cloud run on 2026-10-20 (section 10, item 5): on GCP every VM's NIC is a /32, so "same network" matches nobody and PostgreSQL refused both app servers. The Docker lab keeps samenet, because there private_ip is a container name, not an address, and the lab's bridge network is what samenet means. Second, flush_handlers forces the PostgreSQL restart to happen before we try to create the user, instead of at the end of the play. If handlers and flush_handlers are new to you, Ansible handlers explained is the background.

The password lives in group_vars/all/vault.yml, encrypted:

1ansible-vault view ansible/inventory/group_vars/all/vault.yml
2# vault_db_password: "N0tes-Demo-Pa55"

app

Creates a system user, copies the code, builds a virtualenv, writes .env (mode 0640, it carries the secret), installs a systemd unit for gunicorn, and then the important part:

 1- name: Apply pending restarts now
 2  ansible.builtin.meta: flush_handlers
 3
 4- name: Wait for the app to listen
 5  ansible.builtin.wait_for:
 6    port: "{{ app_port }}"
 7
 8- name: Health check must pass before Ansible moves to the next app server
 9  ansible.builtin.uri:
10    url: "http://127.0.0.1:{{ app_port }}/health"
11    status_code: 200
12    return_content: true
13  register: health
14  retries: 10
15  delay: 3
16  until: health.status == 200 and (health.json.status | default('')) == 'ok'

If the new version does not come up healthy, the play fails on that server and the other app server is still serving the old version. That is the whole safety net, and section 7 shows it doing its job.

nginx load balancer

Templates the upstream block above, validates with nginx -t, reloads, and optionally runs certbot (section 9). The validate-before-reload order is the same one that saves you from Apache failing to start after a config change.

5. site.yml: the whole stack from zero

1- hosts: all           ; become: true ; roles: [common]
2- hosts: dbservers     ; become: true ; roles: [postgres]
3- hosts: appservers    ; become: true ; serial: 1 ; roles: [app]
4- hosts: loadbalancers ; become: true ; roles: [nginx_lb]
1make site            # Docker lab
2make site INV=cloud  # any cloud

The first run on the fresh lab, 117.9 seconds end to end:

 1$ make site
 2cd ansible && ansible-playbook -i inventory/docker.ini site.yml
 3
 4PLAY [Base setup on every server] **********************************************
 5TASK [common : Update apt cache] ***********************************************
 6changed: [app-2]
 7changed: [app-1]
 8changed: [lb-1]
 9changed: [db-1]
10TASK [common : Base packages every server needs] *******************************
11changed: [db-1]
12...
13PLAY [Database server] *********************************************************
14TASK [postgres : Install PostgreSQL and the Python driver Ansible's modules need] ***
15changed: [db-1]
16RUNNING HANDLER [postgres : Restart postgresql] ********************************
17changed: [db-1]
18TASK [postgres : Database user (password comes from Ansible Vault)] ************
19changed: [db-1]
20...
21PLAY [Application servers, one at a time] **************************************
22TASK [app : Health check must pass before Ansible moves to the next app server] ***
23ok: [app-1]
24TASK [app : Report] ************************************************************
25ok: [app-1] => {
26    "msg": "app-1 is healthy on version 1.0.0"
27}
28...
29PLAY [Load balancer] ***********************************************************
30TASK [nginx_lb : The load balancer answers] ************************************
31ok: [lb-1]
32
33PLAY RECAP *********************************************************************
34app-1                      : ok=17   changed=11   unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
35app-2                      : ok=17   changed=11   unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
36db-1                       : ok=11   changed=9    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
37lb-1                       : ok=12   changed=8    unreachable=0    failed=0    skipped=4    rescued=0    ignored=0
38[took 117896 ms]

Open http://localhost:8080 (or lb-1's public IP). Refresh a few times and the "served by" line alternates between app-1 and app-2. Run make site a second time and nothing changes; this is the idempotency check, 52.2 seconds on my run:

1$ make site
2PLAY RECAP *********************************************************************
3app-1                      : ok=15   changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
4app-2                      : ok=15   changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
5db-1                       : ok=10   changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
6lb-1                       : ok=11   changed=0    unreachable=0    failed=0    skipped=4    rescued=0    ignored=0
7[took 52166 ms]
8tasks reported changed on the second run: 0

The ok counts are lower on the second run because the handlers (Restart postgresql, Reload systemd, Restart app) only run when something notified them, and nothing did.

6. deploy.yml: zero-downtime rolling deploy

Bump the version and deploy while a loop hits the load balancer twice a second:

1make deploy VERSION=1.1.0
 1$ make deploy VERSION=1.1.0
 2cd ansible && ansible-playbook -i inventory/docker.ini deploy.yml -e app_version=1.1.0
 3
 4PLAY [Rolling deploy] **********************************************************
 5TASK [app : Environment file (DATABASE_URL carries the Vault secret, so 0640)] ***
 6changed: [app-1]
 7RUNNING HANDLER [app : Restart app] ********************************************
 8changed: [app-1]
 9TASK [app : Wait for the app to listen] ****************************************
10ok: [app-1]
11TASK [app : Health check must pass before Ansible moves to the next app server] ***
12ok: [app-1]
13TASK [app : Report] ************************************************************
14ok: [app-1] => {
15    "msg": "app-1 is healthy on version 1.1.0"
16}
17TASK [Show which server and version the load balancer just returned] ***********
18ok: [app-1] => {
19    "msg": "LB → app-2 running 1.0.0"
20}
21...
22TASK [app : Report] ************************************************************
23ok: [app-2] => {
24    "msg": "app-2 is healthy on version 1.1.0"
25}
26TASK [Show which server and version the load balancer just returned] ***********
27ok: [app-2] => {
28    "msg": "LB → app-1 running 1.1.0"
29}
30
31PLAY RECAP *********************************************************************
32app-1                      : ok=15   changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
33app-2                      : ok=15   changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
34[took 22085 ms]

LB → app-2 running 1.0.0 while app-1 was being restarted is the line that matters: a user at that moment got the old version from the other server, not an error. The request loop that ran during those 22 seconds:

1requests: 46  ok: 46  failed: 0
222:43:46.152 {"db":"ok","server":"app-2","status":"ok","version":"1.0.0"}  HTTP200
322:43:46.682 {"db":"ok","server":"app-1","status":"ok","version":"1.1.0"}  HTTP200
422:43:47.214 {"db":"ok","server":"app-1","status":"ok","version":"1.1.0"}  HTTP200

Three things make that work together:

  1. serial: 1 in deploy.yml: one app server at a time.
  2. The health gate in the app role: Ansible does not move on until /health says ok (up to 10 retries, 3 seconds apart).
  3. In nginx, max_fails=1 fail_timeout=5s plus proxy_next_upstream error timeout http_502 http_503 http_504: a request that lands on the restarting server is retried on the healthy one.

make smoke sends ten requests through the load balancer and prints which server answered and which versions were seen. Run straight after the deploy, all ten came from app-1 and one version was seen:

1$ make smoke
2TASK [Who answered] ************************************************************
3ok: [lb-1] => {
4    "msg": ["app-1", "app-1", "app-1", "app-1", "app-1", "app-1", "app-1", "app-1", "app-1", "app-1"]
5}
6TASK [Versions seen] ***********************************************************
7ok: [lb-1] => {
8    "msg": ["1.1.0"]
9}

Ten in a row from app-1 is not a bug: app-2 had been restarted seconds earlier, and nginx keeps a server out of rotation for fail_timeout (5 seconds) after the one failed attempt that max_fails=1 allows. Run make smoke again a few seconds later and the answers alternate.

7. A deploy that fails on purpose

A safety net you have never seen catch anything is a theory. So I broke the next deploy deliberately: db_host pointed at nowhere.invalid on app-1 only, then make deploy VERSION=broken:

 1$ make deploy VERSION=broken
 2TASK [app : Environment file (DATABASE_URL carries the Vault secret, so 0640)] ***
 3changed: [app-1]
 4RUNNING HANDLER [app : Restart app] ********************************************
 5changed: [app-1]
 6TASK [app : Wait for the app to listen] ****************************************
 7fatal: [app-1]: FAILED! => {"changed": false, "elapsed": 60, "msg": "Timeout when waiting for 127.0.0.1:8000"}
 8
 9PLAY RECAP *********************************************************************
10app-1                      : ok=10   changed=2    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
11make: *** [Makefile:18: deploy] Error 2
12[took 70789 ms]
13
14$ curl -s http://localhost:8080/health
15{"db":"ok","server":"app-2","status":"ok","version":"1.1.0"}
16$ curl -s http://localhost:8080/health
17{"db":"ok","server":"app-2","status":"ok","version":"1.1.0"}

The app on app-1 could not start, wait_for gave up after 60 seconds, the play stopped on app-1 and never touched app-2, and every request to the load balancer was answered by app-2 on the previous version. Fix the variable, roll forward:

1$ make deploy VERSION=1.1.1
2    "msg": "app-1 is healthy on version 1.1.1"
3    "msg": "LB → app-2 running 1.1.0"
4    "msg": "app-2 is healthy on version 1.1.1"
5    "msg": "LB → app-1 running 1.1.1"
6PLAY RECAP *********************************************************************
7app-1                      : ok=15   changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
8app-2                      : ok=15   changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
9[took 30145 ms]

That 60-second wait is wait_for's default timeout. On a real deploy I would lower it to 30 and let the health check's retries do the waiting, so a broken release fails in half the time.

8. CI/CD with GitHub Actions

.github/workflows/deploy-project-01.yml (at the repo root) turns a push to main into that rolling deploy. It needs three repository secrets:

SecretValue
SSH_PRIVATE_KEYcontents of infra/keys/lab
INVENTORY_INIcontents of ansible/inventory/cloud.ini
VAULT_PASSWORDyour vault password

The job installs Ansible and the collections, writes the key, inventory and vault password from the secrets, then:

1ansible-playbook -i inventory/ci.ini deploy.yml -e app_version=${GITHUB_SHA::7}
2ansible-playbook -i inventory/ci.ini smoke-test.yml

concurrency: deploy-production guarantees two pushes never deploy at the same time. Change a line in app/app.py, push, and refresh the browser.

9. HTTPS with Let's Encrypt

On a cloud server with a DNS record pointing at lb-1:

1# ansible/inventory/group_vars/all/main.yml
2enable_ssl: true
3domain_name: notes.example.com
4letsencrypt_email: you@example.com
1make site INV=cloud

The nginx_lb role installs certbot and runs certbot --nginx --redirect, guarded by creates: so it only ever runs once. Renewal is handled by the systemd timer certbot installs.

10. What broke when I ran this

I ran the whole project as a script on a clean Ubuntu 24.04 machine (a GitHub Actions runner) on 2026-10-16, with ansible-core 2.21.5, Docker 28.0.4 and Docker Compose v2.38.2. Three things failed before the output above was possible. All three are in the repository as I write this, with the fixes below.

1. sshd refused the key: Permission denied (publickey,password) from all four containers. make lab-up built the image, started the containers, waited the full 60 seconds for SSH and then every ping failed. The journal inside lb-1 had the reason:

1$ docker exec lb-1 journalctl -u ssh --no-pager -n 2
2Oct 16 22:37:27 lb-1 sshd[84]: Authentication refused: bad ownership or modes for file /home/ansible/.ssh/authorized_keys
3Oct 16 22:37:27 lb-1 sshd[84]: Connection closed by authenticating user ansible 172.18.0.1 port 45830 [preauth]
4
5$ docker exec lb-1 ls -ln /home/ansible/.ssh/
6-rw-r--r-- 1 1001 1001 102 Oct 16 22:35 authorized_keys

The public key is bind-mounted into the container, so it keeps the host owner's uid. My user on that machine is uid 1001; the ansible user in the container is uid 1000; sshd's StrictModes refuses an authorized_keys owned by someone else. Docker Desktop on Mac and Windows maps file ownership to the container user, which is why this never showed up on my laptop. The fix on a Linux host is one command, and the mount picks it up immediately:

1$ sudo chown 1000:1000 infra/keys/lab.pub
2$ make ping
3db-1  | SUCCESS => {"changed": false, "ping": "pong"}

2. make deploy died before connecting anywhere: Error processing keyword 'name': 'app_name' is undefined. The play in deploy.yml was named Rolling deploy of {{ app_name }}. Older Ansible printed that literally; ansible-core 2.19 and later template play names before host variables exist and fail. The fix is a static name, - name: Rolling deploy, which is what every output above shows.

3. Every apt install in the common role failed with No package matching 'acl' is available, and the task before it, Update apt cache, had reported ok. The lab's Dockerfile deletes /var/lib/apt/lists/* to keep the image small, but the directory itself was created minutes ago, and the apt module's cache_valid_time: 3600 looks at that timestamp and decides the cache is fresh:

1$ docker exec lb-1 sh -c 'ls /var/lib/apt/lists | wc -l; stat -c "lists dir mtime: %y" /var/lib/apt/lists; date -u'
20
3lists dir mtime: 2026-10-16 22:39:30.515575826 +0000
4Fri Oct 16 22:40:41 UTC 2026

Zero package lists, a 71-second-old directory, no update. Removing the cache_valid_time: 3600 line makes apt update run every time (a few seconds per host); on cloud VMs the lists exist, which is why it worked there. I will put the fixes for 2 and 3, and a copy of the key with the right owner, into the repository.

5. Google Cloud, 2026-10-20: both app servers failed their health check, and journalctl -u notes-api on app-2 said why:

1psycopg2.OperationalError: connection to server at "10.20.0.4", port 5432 failed:
2FATAL:  no pg_hba.conf entry for host "10.20.0.2", user "notes", database "notes", SSL encryption

pg_hba.conf had the samenet line, and on AWS that had been enough. On GCP it is not, because the VM's own address has no subnet behind it:

1$ ip -o -4 addr show ens4
22: ens4    inet 10.20.0.4/32 metric 100 scope global dynamic ens4

A /32 has no "same network". The fix is the loop you saw in section 4: one host ... 10.20.0.2/32 ... line per app server, taken from private_ip, with samenet kept only for the Docker lab. Re-run from a fresh terraform apply: make site INV=cloud in 246 seconds, failed=0, and make deploy INV=cloud VERSION=1.1.0 in 56 seconds with 92 requests through the load balancer and 0 failures.

6. Same Google Cloud run, app-1 never got that far: Could not get lock /var/lib/apt/lists/lock. It is held by process 1589 (apt-get). Process 1589 was my own doing:

1$ ps -o pid,etime,cmd -p 1589
2    PID     ELAPSED CMD
3   1589       08:00 apt-get update
4$ ps aux | grep metadata_script
5root  1564  ... /usr/bin/google_metadata_script_runner startup

The Terraform for GCP had a startup script that ran apt-get update && apt-get install -y python3 python3-apt, and eight minutes after boot it was still fetching package lists, holding the lock Ansible needed. Ubuntu's cloud images already ship both packages, so the script did nothing useful. It is gone now, the equivalent cloud-init packages: lines are gone from the AWS and Azure Terraform too, and every apt task in the roles has lock_timeout: 600 so a boot-time unattended-upgrades run cannot cause the same failure.

7. My own request loop lied to me at first: it said 92 requests, 46 failed. The /health JSON ends with a newline, so each request wrote two lines and my counter saw the second line as a failure. The 46 requests, 46 of them HTTP 200, is the corrected count. Worth saying because "0 failures" is the number this whole post rests on.

11. Troubleshooting

SymptomFix
Permission denied (publickey,password) from every container on Linuxyour uid is not 1000: sudo chown 1000:1000 infra/keys/lab.pub (section 10)
'app_name' is undefined on make deploy with Ansible 2.19+use a static play name in deploy.yml
No package matching 'acl' is available right after make lab-upremove cache_valid_time: 3600 from the common role
Attempting to decrypt but no vault secrets foundCreate .vault_pass at the repo root (echo ansible-demo > .vault_pass). ansible.cfg points at it.
systemctl start postgresql hangs forever on DockerThe containers must share the host cgroup namespace. Use make lab-up (it handles it) rather than a hand-written docker run.
App health check fails with a DB errorCheck db_host resolves from the app server (getent hosts db-1) and that pg_hba.conf on db-1 has a line for that app server's private_ip (journalctl -u notes-api on the app server shows no pg_hba.conf entry for host ... when it does not).
Could not get lock /var/lib/apt/lists/lock on a cloud VMSomething else ran apt-get at boot (a startup script, cloud-init packages, unattended-upgrades). The roles wait up to 10 minutes (lock_timeout: 600); do not add apt runs to the VM's startup script.
nginx returns 502 for everyonemake smoke to see which upstream is down; journalctl -u notes-api on the app server.
make smoke shows one server ten timesthe other one restarted within the last 5 seconds (fail_timeout); run it again
Terraform: file("../keys/lab.pub") not foundCreate the key first: ssh-keygen -t ed25519 -f infra/keys/lab -N "".
IPs changed after a stop/start in the cloud./scripts/gen-inventory.sh <cloud> again.

Conclusion

Four roles, two playbooks, one variable that makes it portable, and a deploy that never shows users an error: 118 seconds from four empty servers to a working stack, 22 seconds per release, and a broken release that fails on one server while the other keeps serving. If you can run this project end to end, you can automate real infrastructure with Ansible.

Did this save you a debugging session? Stay in the loop -