# Case Study: Deploying a Web App Across Environments — Ansible: Automate Servers with Playbooks

Source: https://www.geekswithgeeks.com/en/ansible/wrap-case-study

> Design a repository and workflow that deploys a web app to staging and production safely.

## The design

Repository: `inventories/staging` and `inventories/production`, each with `hosts.ini` and `group_vars` (ports, replica counts, vaulted secrets with separate vault passwords). Roles: `common` (users, packages, firewall), `nginx`, `app_deploy` (release directory, systemd unit, template config, handler to reload). Pipeline: on pull request run syntax-check, ansible-lint and Molecule; on merge deploy to staging with `--check --diff` then for real; production runs through the controller with an approval step, a canary host first, then `serial: 25%` with health checks and `max_fail_percentage`. Rollback is a re-run with the previous release variable. Every run is logged with the commit ID.

## A safe deployment pipeline

Inventory, roles, secrets, tests and rolling rollout work together as one routine.

![Four parts: define, protect, verify, roll out.](assets/figures/ansible/section-8-map.svg) — Figure 8.1 — Define, protect, verify and roll out.

## The setup on one page

Each line maps to a section of this course.

```text
Inventory      per-environment dirs + group_vars                 (Sec 1, 3)
Playbooks      idempotent, named tasks, handlers, check --diff     (Sec 2, 4)
Roles          common, nginx, app_deploy; pinned collections       (Sec 5)
Secrets        Vault per environment; no_log; least privilege      (Sec 6)
Quality        syntax-check, ansible-lint, Molecule in CI          (Sec 7)
Rollout        canary host, serial batches, health checks, rollback (Sec 7)
```

## Practise the rollback

Rehearse rolling back in staging so it is a known, quick procedure rather than something improvised during an outage.

**Quiz:** Why deploy to a canary host first in production?

- [ ] It avoids needing health checks
- [ ] Canary hosts are faster
- [x] To catch problems while only one machine is affected
- [ ] Production rejects batches

*Answer:* To catch problems while only one machine is affected. A small first step limits the blast radius of a bad change.
