Skip to content
rustc0Public

About

A production-style cloud infrastructure and deployment project using Terraform, Ansible, Docker, and AWS to provision, harden, configure, and deploy a containerized application with automated, reproducible infrastructure.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

app-infra

Terraform creates the box; Ansible makes it usable. The split is deliberate: Terraform (tf/) owns anything with an AWS API behind it (instance, security group, key pair), Ansible (ans/) owns everything that lives inside the OS (sshd, packages, the Docker daemon). Neither one reaches into the other's half.

The target is a single Debian EC2 instance, reached as the admin user with the key pair Terraform provisioned.

Path What it holds
tf/ The AWS side: Debian AMI lookup, security group, EC2 instance
ans/ The OS side: one role per concern, plus the playbook that orders them
scripts/ The glue between them (see below)
Makefile The entry point for both

Quick start

make up

That is the whole thing, from nothing to a running app. make up runs scripts/deploy.sh, which does in order what you would otherwise do by hand:

  1. terraform init + terraform apply — the instance and its security group.
  2. scripts/inventory.sh — reads terraform output public_ip and writes ans/inventory/hosts.ini. This is the only place the address crosses from the Terraform half of the repo to the Ansible half, so nothing is pasted by hand and nothing goes stale after a replace.
  3. scripts/wait-for-ssh.sh — polls until sshd answers. A fresh instance accepts an apply well before it accepts a connection, so running the playbook immediately fails on unreachable rather than on anything real.
  4. ansible-galaxy collection install — the collections in requirements.yml.
  5. ansible-playbook playbooks/site.yml — the roles, in order.

Every step is idempotent, so running make up against an existing stack is a deploy, not a rebuild. It fails fast before touching AWS if a required binary is missing or ans/secrets/vault.yml does not exist — better than an instance that exists and can't be configured.

The other targets

make help lists them. The ones that matter:

Target What it does
make up Provision then configure, end to end
make provision terraform apply only
make inventory Re-render ans/inventory/hosts.ini from the outputs
make configure / make deploy Run the playbook against the current inventory
make check The playbook as --check --diff — changes without making them
make ping Confirm SSH works before changing anything
make destroy terraform destroy

And the variables, overridable per invocation:

Variable Default Why
AUTO_APPROVE 0 1 skips Terraform's approval prompt (CI)
VAULT_PASS_FILE unset A password file instead of --ask-vault-pass
SSH_USER admin Written into the generated inventory
SSH_KEY current Private key path; unset keeps whatever the inventory has
ARGS empty Passed through to ansible-playbook, e.g. ARGS=--tags app
make up AUTO_APPROVE=1 VAULT_PASS_FILE=~/.vault-pass   # unattended
make check ARGS="--limit server"

By hand

The Make targets are a convenience, not a dependency — nothing in ans/ or tf/ knows they exist. The equivalent by hand:

cd tf && terraform apply             # get the instance + its public IP
terraform output public_ip           # paste into ans/inventory/hosts.ini

cd ../ans
ansible-galaxy collection install -r requirements.yml
ansible -m ping hosts                # confirm SSH works before changing anything
ansible-playbook playbooks/site.yml --ask-vault-pass

ans/ansible.cfg points at inventory/hosts.ini and roles/, so the Ansible commands need no flags — but they must be run from ans/, which is why the Makefile cds there for you.

First run only

The app role needs two secrets, and refuses to touch the host without them. Create ans/secrets/vault.yml holding vault_postgres_password and vault_jwt_secret, then:

ansible-vault encrypt ans/secrets/vault.yml

Generate both rather than copying them from anywhere: openssl rand -base64 32. In particular do not reuse the JWT_SECRET from chatApp/.env.example — that is a real-looking key sitting in a public repo.

No registry credential is needed. The chatapp-{backend,frontend,gateway} packages are public, so the server pulls anonymously and the role has no docker login step at all. Making them private would mean restoring that step and storing a GitHub PAT (classic, read:packages, nothing else) in the vault.

The Ansible side

Path What it holds
ans/ansible.cfg Inventory + roles path, so commands need no flags
ans/inventory/hosts.ini The one host. Generated by make inventory
ans/vars/main.yml Per-deployment overrides, loaded by the playbook
ans/playbooks/site.yml The entry point — runs every role, as root, against hosts
ans/roles/ One role per concern (below)
ans/secrets/ Git-ignored. Holds vault.yml: DB password and JWT key
ans/requirements.yml Galaxy collections: community.general (ufw), community.docker (docker_compose_v2)

Role defaults (ans/roles/*/defaults/main.yml) are written so the playbook runs correctly with no vars file at all. ans/vars/main.yml exists to override them for this particular deployment, not to duplicate them.

Role order

site.yml runs the roles in a deliberate sequence, hardening from the outside in before anything is installed that could be attacked:

  1. ssh — lock down the only way in.
  2. firewall — close everything else off.
  3. auditd — start recording before there is anything worth recording.
  4. updates — keep the base system patching itself.
  5. docker — only then install the runtime the app will use.
  6. app — last, once there is a hardened host with a runtime to deploy onto.

The roles

ssh

Drops a 00-hardening.conf into /etc/ssh/sshd_config.d/: no root login, no password or keyboard-interactive auth, keys only, a capped MaxAuthTries and LoginGraceTime, no X11 forwarding.

It's a drop-in rather than an edit of sshd_config because Debian's main config includes sshd_config.d/*.conf first and sshd honours the first value it sees — so a 00- prefixed file wins without the role ever having to parse or rewrite the distro's file. The template is gated on sshd -t -f %s, and a second task validates the whole assembled config, so a bad edit fails the play instead of bricking SSH on the handler's restart.

firewall

UFW with default-deny inbound, default-allow outbound, SSH allowed (optionally narrowed to one CIDR via firewall_ssh_allowed_from), and 80/443 open for the app. SSH is allowed before UFW is enabled — the other order locks you out of your own box mid-play.

This duplicates the AWS security group on purpose. The security group is the edge; UFW is the host-level fallback for when something is misconfigured, or when the instance ends up somewhere with a laxer group attached.

One known gap, noted in the role's defaults: Docker writes its own iptables rules and containers published with -p bypass UFW entirely. Containers should bind to 127.0.0.1 and sit behind a reverse proxy rather than trusting UFW to stop them.

auditd

Installs auditd and writes /etc/audit/rules.d/50-hardening.rules with watches on the files that matter for after-the-fact questions: sshd config, sudoers, and the passwd/group/shadow set. Each watch is -p wa (writes and attribute changes) with a key, so ausearch -k sudoers answers "who changed this, when".

Kept deliberately small. A full CIS ruleset generates far more noise than a single-app box can justify; auditd_extra_watches is the seam for adding to it without touching the role.

updates

unattended-upgrades restricted to the Debian security origin only, plus the apt daily timers to actually trigger it. Security patches land without anyone logging in; feature updates don't, so they can't break the app unsupervised.

Automatic reboot is off by default (updates_auto_reboot) — that's a decision for when the app is actually running and its restart behaviour is known.

docker

Removes the distro's docker.io/podman-docker packages that conflict with upstream, adds Docker's own apt repo via deb822_repository (signed, with architecture derived from facts so the role works on both x86 and Graviton), then installs Engine, containerd, buildx and the Compose plugin.

Finishes by adding docker_users to the docker group and creating /opt/app + /opt/app/data, mode 0750, owned by the app user. Group membership is root-equivalent — that's the tradeoff for not needing sudo on every deploy command, and the reason the list is an explicit variable rather than "whoever is logged in".

This role installs the runtime and nothing else. It does not deploy the app.

app

Deploys chatApp — a four-container stack (Postgres, a FastAPI backend, a built frontend, and an nginx gateway that terminates TLS).

The server builds nothing. Images are built by GitHub Actions in the chatApp repo and pushed to ghcr.io/rustc0/chatapp-{backend,frontend,gateway}; this role renders two files and runs docker compose up -d. Those packages are public, so the pull is anonymous and the role stores no registry credential. The entire deployed footprint is:

/opt/app/compose.yml    # image: refs only, no build:, mode 0640
/opt/app/.env           # rendered from the vault, mode 0600

No source tree, no Dockerfiles. That is deliberate and not just tidiness: the box is a t3.micro with 1 GB of RAM, and an npm build on it is a coin flip. Keeping builds in CI also means the artifact that was tested is the artifact that ships.

app_image_tag is the deploy control. CI tags every image with its commit sha; setting that sha and re-running the playbook rolls the stack forward, and setting the previous one rolls it back. It defaults to latest, which is convenient and not reproducible — pin it for anything you care about.

Two things the compose file does not do, both on purpose:

  • Postgres is not published. The dev docker-compose.yml maps ${POSTGRES_PORT}:5432; since Docker bypasses UFW (see the firewall note above), that would be the database on the open internet. The backend reaches it over the compose network by name, so there is nothing to publish.
  • Nothing is bind-mounted from the host. The dev file mounts ./backend over /app, which would drag the source onto the server and shadow the image. The only volumes are named ones for state: chatapp-db-data, chatapp-avatars, and chatapp-gateway-certs — the last so the gateway's self-signed cert survives a redeploy instead of being reissued each time.

Secrets come from ans/secrets/vault.yml and the role asserts they are non-empty before it touches the host, so a missing vault fails the play rather than deploying a stack with a blank database password.

Deploying a new version

git push                             # in chatApp; CI builds and pushes to GHCR
# set app_image_tag to the new commit sha in ans/vars/main.yml
make deploy

Rolling back is the same command with the previous sha. make check first shows exactly what would change in compose.yml and .env without writing anything.

Checking a deploy

On the box:

docker compose -f /opt/app/compose.yml ps        # all four healthy
docker compose -f /opt/app/compose.yml logs backend | grep -i alembic

From anywhere:

curl -I  http://<public_ip>/     # 301 to https
curl -kI https://<public_ip>/    # 200; -k because the cert is self-signed
nc -zv <public_ip> 5432          # MUST be refused

That last one is the check worth actually running. UFW cannot catch a published container port, so nothing on the host will stop a stray ports: entry from putting the database on the internet — only the compose file's not having one does. docker inspect chatapp-db --format '{{json .NetworkSettings.Ports}}' should print {"5432/tcp":null}.

Re-running the playbook unchanged should report changed=0 for the app role.

TODO

Security

  • Real TLS certificate. The gateway self-signs with CN=localhost, so every browser warns. Needs a domain pointed at the instance, then certbot (or an ACM cert if an ALB ever goes in front). Blocks anyone else using this.
  • Narrow SSH. Both layers are currently open to the world — firewall_ssh_allowed_from: any in ans/vars/main.yml and ssh_allowed_cidr = "0.0.0.0/0" in tf/terraform.tfvars. Key-only auth and MaxAuthTries 3 mean this is noisy rather than dangerous, but both want your own CIDR.
  • Private images. The GHCR packages are public, which is why the server needs no registry credential at all. Making them private means a long-lived PAT in the vault and a rotation schedule — or moving to ECR and pulling with an IAM instance role, which needs no stored secret either.

Operations

  • Database backups. chatapp-db-data is currently the only copy of the data and lives on one EBS volume. pg_dump on a timer to S3 is the small version of this.
  • Tags on every role, so a deploy can be --tags app instead of a full hardening run. Worth doing once deploys get frequent.
  • Read the audit log. auditd writes to disk and nothing ships or alerts on it, so it only helps if you already know to go looking.
  • Health alerting. Containers have healthchecks and restart: unless-stopped, but nothing notices if one restarts in a loop.

Deployment

  • Pin app_image_tag to a sha as the normal case. It defaults to latest, which is convenient and not reproducible.
  • Keep compose.yml.j2 in step with chatApp/compose.prod.yml. They are duplicates across two repos today — the first time they drift will be confusing. Either generate one from the other, or have the role fetch it.
  • Zero-downtime deploys. docker compose up -d recreates containers, so a deploy is a brief outage. Fine now; not fine with users.
  • Drop /opt/app/data from docker_app_dirs if nothing claims it — the stack uses named volumes, not a host directory.

Capacity

  • Watch memory on the t3.micro. 1 GB for Postgres + Python + two nginx is tight but real; CI does the building, so the box never compiles. Bump instance_type if it starts swapping.

Expect the role list in site.yml to grow from the bottom: the hardening layer is meant to be stable, and app-facing roles get appended after docker.

About

A production-style cloud infrastructure and deployment project using Terraform, Ansible, Docker, and AWS to provision, harden, configure, and deploy a containerized application with automated, reproducible infrastructure.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages