This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This repo manages infrastructure for multiple hosts using Ansible + Docker Compose (most hosts) or OpenTofu (tower).
Ansible hosts (mx1, web1, web2, web3): each top-level directory contains ansible/ (playbooks and roles) and containers/ (Docker Compose stacks).
OpenTofu hosts (tower): each top-level directory contains terraform/ (.tf files) and docs/ (node-specific setup guide). tower is also configured by Ansible: it has ansible/ and containers/ like the other hosts, deployed after each OpenTofu apply. Run tofu commands from the terraform/ subdirectory. Variables are passed via TF_VAR_* env vars; the S3 backend requires -backend-config flags at init time — see tower/docs/setup.md. OpenTofu version: 1.13.x (pinned in .github/workflows/tower-tofu-apply.yml; Renovate bumps it together with required_version). Note: error() in expressions requires ≥ 1.9. When updating providers, regenerate the lock file with tofu providers lock -platform=linux_amd64 so CI hashes are included.
cd <host>/ansible
ansible-playbook playbook.ymlSCHEDULED_RUN=true enables heavy tasks (OS hardening, APT updates, Docker install). Default is false for quick deploys.
Required environment variables before running (used by lookup('env', ...)): BORG_PASSPHRASE, BORG_REPOSITORY, MYSQL_PASSWORD, BORG_HEARTBEAT_URL.
Deployment flow: Ansible copies the local containers/ directory to /opt/containers/ on the remote host, then deploys each stack via community.docker.docker_compose_v2. The docker_stacks map in roles/system/containers/defaults/main.yml controls which stacks are deployed:
docker_stacks:
<service>:
env_file: true # deploy only if .env exists; false = always deploy
state: present # or restartedShared network: All containers use an external Docker network app-infra. The network is created by the system/containers role with optional IPv6 support via DOCKER_IPV6_SUBNET.
Migrations: One-time Ansible tasks in ansible/migrations/, tracked in /opt/ansible/migrations.db per host. Run first, before other roles. Use timestamped filenames: YYYYMMDD_NNNN_description.yml.
- The repository is public. Do not commit identifying details: hostnames and domains of the hosts (tower's comes
from the
TOWER_HOSTNAMEenvironment secret), names of personal machines or tailnet nodes, what hardware or OS they run, or account identifiers. This applies to comments, docs, commit messages and PR text too. Inject runtime values through environment secrets →.env/TF_VAR_*, and write<tower-hostname>-style placeholders in docs - No
version:key indocker-compose.yml(deprecated in Compose V2) - Always bind ports to localhost:
127.0.0.1:<port>:<port>; use incremental ports (3001, 3002, ...) per host - Prefer
.envfiles over inlineenvironment:blocks; setenv_file: - .envin compose - Fixed image tags — no
latest; prefer-alpinevariants; new PostgreSQL stacks pin the same full tag as the existing ones (e.g.postgres:18.7-alpine3.23), notpostgres:18-alpine - Network declaration in every compose file:
The exceptions are the
networks: app-infra: external: true
tailscalestack (mx1, web1, web2, web3; not tower, the control plane), which runs withnetwork_mode: hostso that the host itself is the tailnet node, andheadscaleon tower, the control plane, which also uses host networking so it listens on IPv4 and IPv6 without Docker NAT (STUN needs the client's real source address)
The system/monit role (first-party; runs on every deploy) installs and
configures monit on the Ansible hosts (mx1,
web1, web2, web3). It monitors filesystem space usage and alerts at two
thresholds (defaults 80% and 90%, set in the role's defaults/main.yml).
- Base config:
/etc/monitrc(Ansible-managed, overwritten). monit's CLI is bound to a localhost unix socket (/run/monit.sock) — no TCP exposure. - Disk checks:
/etc/monit.d/disk.cfg(Ansible-managed). Filesystems are declared viamonit_disk_filesystemsin the role defaults (default:/; uncomment the/var/lib/dockerentry on hosts where it is a separate mount). - Both thresholds fire email and a chat push.
Two files are deployed only if absent (force: no), so hand-edited secrets
survive re-runs — they are intentionally kept out of git and Ansible vars:
/etc/monit.d/mail.cfg— hand-edit SMTP server +set alert <addr>for email notifications (see the committedmail.cfg.example)./etc/monit/notify-chat.env— hand-fillTELEGRAM_BOT_TOKEN/TELEGRAM_CHAT_IDand/orSLACK_WEBHOOK_URLfor chat notifications. The/etc/monit/notify-chat.shhelper curls whichever channel is configured and is a silent no-op otherwise.
After editing either file on a node: monit reload.
Role selection note:
pgolm.monit(MIT, Galaxy) was evaluated as the best community option (supportsfilesystemchecks + mail templating), but a thin first-party role was chosen to avoid a stale dependency and because SMTP/chat secrets are hand-edited on the node rather than templated by Ansible.
Every service must have these two options by default:
cap_drop:
- ALL
security_opt:
- no-new-privileges:trueWhen to add cap_add back (always pair with cap_drop: [ALL]):
NET_BIND_SERVICE— container binds a privileged port (< 1024) directly, e.g. SMTP (25, 465, 587), IMAP (993), HTTPS (443)NET_ADMIN— VPN/network management (e.g. a WireGuard or Tailscale client container; not headscale, which is only a control server and needs justNET_BIND_SERVICE). The kernel-modetailscalestack also needsNET_RAW: tailscaled's iptables/nftables rules fail with "Permission denied" without itSYS_NICE— real-time scheduling (e.g. MySQL)CHOWN— init/setup containers thatchownvolume paths on startup
Stateless containers (no writable volume mounts) also get read_only: true plus tmpfs for any paths the runtime needs to write:
read_only: true
tmpfs:
- /tmp # all runtimes
- /run # nginx (PID file)Applied to: cloudflared, mailflow frontend + backend, n8n runner. headscale is stateful but also runs read_only: true: it writes only to its data volume and a /var/run/headscale tmpfs.
calcom is not read-only — its entrypoint installs NPM packages and writes a build cache on startup, which breaks under read_only: true. Keep cap_drop: [ALL] + no-new-privileges:true, omit read_only/tmpfs.
Containers exempt from cap_drop (do not add):
watchtower— requires Docker socket managementauthentik worker— runs asrootwith Docker socket for blueprint managementsandbox-runner-1(web3 n8n stack) —privileged: trueDocker-in-Docker that runs n8n Assistant's sandboxes;no-new-privilegeswould be inherited by the sandboxes it starts. Never publish its ports- Any init container whose sole job is
chown(needsCAP_CHOWN; dropping all caps breaks it) - All data store images (PostgreSQL, MySQL, Redis, KeyDB, Valkey, OpenSearch, Meilisearch) — their entrypoints start as
rootand usegosuto drop to the database user, which requiresCAP_SETUID/CAP_SETGID. Bothcap_drop: [ALL]andno-new-privileges:truebreak this pattern and prevent the container from starting.
This section is not enforced by CI. Nothing checks a compose file, so a service that omits
cap_droppasses review only if someone catches it. The rules above are the contract; applying them is the reviewer's job.Two things make this harder to eyeball than it looks. Service names are ambiguous across stacks —
workeris the Docker-socket-holding authentik worker in one stack and an ordinary hardened twenty.crm worker in another, so "the worker is exempt" is not a safe rule of thumb. And three services deliberately publish a port on all interfaces: the MX (it exists to receive SMTP), headscale (host networking: tailnet control plane + DERP on 443/tcp, STUN on 3478/udp), frankenphp (terminates ACME HTTP-01). Anything else must bind127.0.0.1. Thetailscalestack publishes nothing but uses host networking, so its WireGuard socket (41641/udp) listens on the host's interfaces like a host daemon.
- Create
<host>/containers/<service>/docker-compose.yml - Add to
docker_stacksin<host>/ansible/roles/system/containers/defaults/main.yml - Apply the container contract above — CI will not check it for you
- Run
ci/validate.shfor the checks that do exist
ci/validate.sh runs every check that CI runs: yamllint, ansible-lint,
tofu validate / tofu fmt for tower, a zizmor audit of the validation
workflow, ci/n8n-versions-check.sh, which fails unless web3's n8n and
n8nio/runners images are pinned to the same version and the n8n sandbox
service API, runner and sandbox images to the same release, and
ci/headscale-check.sh, which runs the headscale image pinned in
tower/containers/headscale/docker-compose.yml (configtest, policy check)
against the committed config and policy and needs docker. Run it before pushing;
the same failures otherwise surface as a red PR.
In CI only yamllint and the n8n versions check run on every pull request. The other checks run when the
diff touches what they read, per the pathspecs in the "Detect which checks the
change affects" step of validate.yml. When a check starts reading a new path,
add it there: otherwise a PR that changes only that path skips the check, and a
skipped check counts as passed. ansible-lint's list works the other way round:
it names what ansible-lint may skip, three of the trees .ansible-lint
excludes (*/containers/, */terraform/, */docs/) plus Markdown. Keep
those in step, but never mirror .github/, which .ansible-lint also
excludes but which defines the ansible-lint job.
Headscale's config and policy live in git at
tower/containers/headscale/config/ and are mounted read-only. Never tell
anyone to edit them on the node. Operations, upgrades, restore, and why its
users and nodes are not in OpenTofu: tower/docs/headscale-setup.md.
Configs live in .yamllint and .ansible-lint. Two things to know when
editing them:
.ansible-lintskip_listentries each carry a reason. Adding a new skip to silence a finding is a decision that should be argued in a review, not a reflex — prefer fixing the finding..yamllintmust keepcomments-indentation: falseand the twooctal-valuessettings.ansible-lint --fixsilently disables itself when the project yamllint config disagrees with its expectations, so removing them breaksfqcnremediation without any visible error.
ansible-lint --fix fqcn is safe to run and is how the FQCN migration was
done. Verify with git diff afterwards: it should only add module
qualification.
When nftables is the firewall backend, three things must be correct:
- CrowdSec bouncer mode: must be
nftables(not iptables) in/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml - IP forwarding: both
net.ipv4.ip_forward: 1andnet.ipv6.conf.all.forwarding: 1required for containers to reach external services - Conntrack tuning (in
defaults/main.ymlundersysctl_overwrite):net.netfilter.nf_conntrack_max: 262144 net.netfilter.nf_conntrack_tcp_timeout_established: 86400 net.netfilter.nf_conntrack_tcp_timeout_time_wait: 30
community.docker and community.general are used by the role tree
(community.docker.docker_compose_v2, community.general.ufw, …) and are
pinned in every host's ansible/requirements.yml. They were previously
resolved only as a transitive dependency of geerlingguy.docker, which
declares no dependencies of its own — so a clean runner would have failed
ansible-lint's syntax check. Keep them listed.
web3's n8n and n8nio/runners must be pinned to the same version. Renovate
updates only the n8n image, on the renovate/n8n branch;
.github/workflows/n8n-sync-runners.yml then pins the runners to the same tag
with ci/n8n-sync-runners.sh, pushing with the N8N_SYNC_TOKEN secret so the
push runs Validate like any other. Until it has run, ci/n8n-versions-check.sh fails the required yamllint check. When
bumping n8n by hand, run ci/n8n-sync-runners.sh after editing the n8n tag.