iac/MIGRATION.md
Sergei Poljanski ebbf458983
All checks were successful
nixos / nixos (push) Successful in 55s
docs: the full migration plan; ci: deploy NixOS hosts
MIGRATION.md is now the complete plan for moving production from
Ansible and Terraform to NixOS and OpenTofu: what was rehearsed and
how, the preparation that needs no downtime, one runbook per host with
its checks and rollback, the clean-up including the branch renames,
and the rules for running restored production data on test servers.

The NixOS workflow now deploys on main, ops first, building on each
host. It checks /etc/NIXOS before touching a host, so it skips both
servers until their conversion and cannot reach a Debian one.
known_hosts moves to the repository root for it.

Renovate learns the Nix files: version comments, the runner's job
images and flake.lock (weekly). The Ansible patterns stay until
Ansible is gone.

Assisted-by: Claude:opus-5-5
2026-11-17 05:15:16 +04:00

326 lines
15 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Moving production from Ansible and Terraform to NixOS and OpenTofu
The plan and the runbook. Delete this file when the last step is done.
**End state:** both servers run NixOS built from `nixos/`, deployed by
`.forgejo/workflows/nixos.yaml`; services are native NixOS services
where nixpkgs has a module and Podman containers otherwise; no Docker
daemon, no Ansible; infrastructure in `terraform/` is applied with
OpenTofu. The servers themselves stay: they are billed below today's
list price, so each one is converted **in place** and never recreated.
**Nothing in production changes without the owner's go-ahead for that
step.** Every step below that touches a server says so.
## Where things stand (2026-11-17)
Production is untouched: both servers run Debian, deployed by Ansible
from `main`. Branch `nix` holds the new system, and every part of it ran
on the rehearsal pair (two cx23 in the personal project), most of it on
a restored copy of last night's production data:
| Area | Rehearsed | Notes |
|---|---|---|
| First boot (cloud-init + nixos-infect) | yes | 3–4 min to a bare NixOS |
| In-place conversion with Docker data | yes | data kept under `/old-root` |
| Base, SSH, firewall, WireGuard, sops | yes | same host keys, same peers |
| Postgres 18.7, Garage 2.5, Forgejo 17 | yes, prod data | roles, buckets, keys from sops |
| Traefik, label routing via Podman | yes | certificates: staging CA only |
| asxpio, datacenterbingo on Podman | yes, prod data | mail and IndexNow disabled |
| Minecraft, SillyTavern, Xray, ACME forward | yes, prod data | Discord plugin kept off |
| XMPP (ejabberd, apushd, tackygram) | dummy data only | never started on prod data on purpose |
| CI runner + jobs | yes | against the rehearsal Forgejo |
| Backup, restore, bucket replica | yes | replica: config only, no run |
| Monitoring, logs, alerts, security baseline | yes | 28 targets up, 0 unknown items |
| CI deploy job | evaluate only | deploys nothing until a host is NixOS |
What each service became, and why:
| Was (Ansible role, container) | Now |
|---|---|
| `base`, `ssh_hardening`, `swap` | `modules/base.nix`, `hetzner.nix` |
| `wireguard` | `modules/wireguard.nix`, keys in sops |
| `traefik` | native `services.traefik`; native services' routes in Nix, apps keep labels |
| `forgejo` | native `services.forgejo` as user `git`; no SSH passthrough needed |
| storage repo: Postgres, Garage | native `services.postgresql`, `services.garage` (2.x pinned) |
| `monitoring`, `monitoring_agent` | native Prometheus, Loki, Grafana, Alloy, exporters, cAdvisor (Podman) |
| `restic_backup`, `s3_replicate`, `crawler_alert`, `xmpp_cert_sync` | systemd units from Nix, same scripts and schedules |
| `forgejo_runner`, `forgejo_runner_interop` | native runner module; interop as its own unit |
| `sillytavern`, `minecraft`, `xray`, `acme_forward` | native modules |
| `xmpp` | Podman containers (a custom build, not nixpkgs' ejabberd) |
| App stacks (asxpio, datacenterbingo, blog, czsk, vhpbot) | unchanged compose stacks on Podman, deployed by their own CI |
## Phase 0: preparation (no downtime)
Everything here can be done while Ansible still runs production.
1. **Push `nix`** and let CI evaluate it. It does not deploy: the job
skips any host without `/etc/NIXOS`, and branches never deploy.
2. **OpenTofu.** Once, from a workstation:
```sh
cd terraform
tofu init -reconfigure
tofu plan # expected: only the new user_data output
tofu apply # writes the output; changes no resource
```
The state is the one Terraform wrote; the servers ignore
`user_data`, `image` and `ssh_keys`, so nothing can be replaced.
3. **App repositories: healthcheck in the compose file.** Podman ignores
the `HEALTHCHECK` of OCI-format images, which is what the app CI
builds, so the deploy's wait for "healthy" would time out on NixOS.
Copy each image's healthcheck into its compose file (asxpio,
datacenterbingo, blog; czsk has none). Under Docker the result is the
same, so this ships now, through the normal deploy. The exact block
for asxpio:
```yaml
healthcheck:
test: ["CMD-SHELL","ruby -rnet/http -e 'port = ENV.fetch(\"PUMA_PORT\", \"3000\"); exit(Net::HTTP.get_response(URI(\"http://127.0.0.1:#{port}/healthz\")).code == \"200\" ? 0 : 1)'"]
interval: 30s
timeout: 5s
start_period: 20s
retries: 3
```
Read the others with `skopeo inspect --raw --config docker://<image>`.
4. **Storage repo: stop its deploys.** Its CI starts Postgres and Garage
containers in `/opt/storage`; after the ops conversion those would
fight the native services for their ports. Disable the deploy
workflow (or archive the repo) before Phase 2. Its secrets
(`ASXPIO_*`, `BINGO_*`, `PUBLIC_*`) stay: the app repos use the same
values.
5. **Secrets.** `nixos/secrets/asxpio-*.yaml` were filled on 2026-11-16
and 17 from the Ansible vault, `/opt/storage/.env` and the Garage RPC
secret. If any of those changed since, update the sops file
(`sops nixos/secrets/asxpio-ops.yaml`). Keys: WireGuard, Xray config,
restic password, S3, alert SMTP, Forgejo (secret key, internal token,
JWT secrets, SMTP, metrics token), Postgres roles, Garage keys and RPC
secret, Traefik ACME email, runner tokens, Grafana admin password,
Hetzner read-only token. The vault and sops must agree until Ansible
is gone.
6. **Freeze.** On conversion day: no pushes to the app repos, to `iac`,
or Renovate merges, from the start of a phase until its checks pass.
7. **Rehearse once more against the latest backups** (both hosts), on a
fresh rehearsal pair, following `nixos/README.md` → Rehearsal and the
rules at the end of this file. It costs about €0.02 an hour and is the
only way to know that the night's data still fits the config.
**Go/no-go for Phase 1:** steps 1–7 done, last night's restic backup of
both hosts green, a Hetzner snapshot of the host just taken.
## Phase 1: asxpio-services (owner's go-ahead required)
Downtime about 15–20 minutes for Minecraft, SillyTavern, XMPP, Xray and
CI. asxpio-ops and everything on it stays up. Services first: it has
less data and nothing on ops depends on it.
From a workstation on WireGuard, in the repo:
1. **Snapshot** (the rollback):
```sh
hcloud server create-image --type snapshot --description pre-nixos asxpio-services
```
2. **Stop what writes, then Docker:**
```sh
ssh root@10.20.0.20 'docker stop -t 120 minecraft; cd /opt/xmpp && docker compose stop; \
docker stop forgejo-runner forgejo-runner-interop sillytavern xray acme-forward; \
systemctl stop docker.socket docker containerd'
```
3. **Convert** (the same lines cloud-init runs; `tofu output -json
user_data | jq -r '."asxpio-services"'` shows them filled in). Write
`/etc/nixos/bootstrap.nix` with the content from there, then:
```sh
ssh root@10.20.0.20 'umount -l /tmp; curl -fsSL -o /root/nixos-infect \
https://raw.githubusercontent.com/elitak/nixos-infect/40f62a680bb0e8f2f607d79abfaaecd99d59401c/nixos-infect \
&& echo "4354bd68773b41da65c0e815202c43c8549713b3ed3ff6381c71fbc0b0a840ab /root/nixos-infect" | sha256sum -c \
&& PROVIDER=hetznercloud NIX_CHANNEL=nixos-26.05 NIXOS_IMPORT=./bootstrap.nix \
setsid bash /root/nixos-infect > /var/log/nixos-infect.log 2>&1 < /dev/null &'
```
It reboots into a bare NixOS after about four minutes. WireGuard is
down until step 4; reach it through ops over the private network:
`ssh -J root@10.20.0.10 root@10.10.0.20`.
4. **Switch to the flake** (through ops, as above):
```sh
cd nixos
NIX_SSHOPTS="-J root@10.20.0.10" nixos-rebuild switch --flake .#asxpio-services \
--target-host root@10.10.0.20 --build-host root@10.10.0.20
```
Services that own data stay stopped: the marker file is missing.
5. **Move the data and start everything:**
```sh
ssh root@10.20.0.20 'bash -s /old-root' < migration/services-data.sh
ssh root@10.20.0.20 reboot
```
6. **Check:**
- `wg show` on ops: the services peer has a fresh handshake.
- `systemctl --failed` empty; Grafana's security panel shows nothing
unknown for asxpio-services.
- Minecraft log reaches `Done`; join once (Java and Bedrock).
- SillyTavern on `http://10.20.0.20:8000`.
- An XMPP client logs in; a message to a contact goes through.
- Forgejo → Site administration → Runners: the new runner idle (it
registered itself again); delete the old, offline entry. Push an
empty commit to an app repo and watch a full CI run.
- `systemctl start restic-backup` succeeds (it continues the same
repositories).
**Rollback:** until step 3, start Docker and the containers again.
After it: `hcloud server disable-protection asxpio-services rebuild`,
rebuild from the snapshot, `tofu apply`. Debian comes back as it was at
the snapshot.
After a week without surprises: `rm -rf /old-root`, delete the snapshot.
## Phase 2: asxpio-ops (owner's go-ahead required)
Downtime about 30–45 minutes for every site, Forgejo, the registry and
monitoring: the conversion itself, the first build of the system, then
pulling each app image again (Docker's image store does not carry over).
Announce it.
ops is the WireGuard hub, so during the window the admin network is
down. Until step 4, ops is reachable as root on its public address
(nixos-infect's bootstrap system has no address restriction); from step
4 on, over WireGuard again, or from services over the private network.
1. **Snapshot**, as in Phase 1.
2. **Dumps and stop**, the staged copies the data script loads:
```sh
ssh root@10.20.0.10 'set -e; d=/var/backups/restic-stage; install -d -m 700 $d; \
docker exec storage-postgres pg_dumpall -U postgres > $d/pg_dumpall.sql; \
sqlite3 /opt/forgejo/data/gitea/gitea.db ".backup $d/forgejo-gitea.db"; \
docker exec storage-garage /garage meta snapshot --all; \
docker ps -q | xargs -r docker stop -t 60; systemctl stop docker.socket docker containerd'
```
3. **Convert**, as in Phase 1 step 3, on 135.181.27.77.
4. **Switch to the flake** on its public address:
```sh
nixos-rebuild switch --flake .#asxpio-ops --target-host root@135.181.27.77 \
--build-host root@135.181.27.77
```
From here on root logs in from WireGuard and the private network only;
WireGuard is up again with the same keys, so clients reconnect.
5. **Move the data, start everything, pull the app images:**
```sh
ssh root@10.20.0.10 'bash -s /old-root' < migration/ops-data.sh
ssh root@10.20.0.10 reboot
```
The script moves Forgejo, Garage, Traefik's certificates, the
monitoring history and `/opt/<app>`; loads the Postgres dump (roles
then get their passwords from sops); regenerates Forgejo's hooks and
SSH keys file; and runs `docker compose pull && up -d` for each app
as `deploy` (vhpbot-prod builds locally).
6. **Check:**
- Every site answers (Grafana → Probes). Certificates are the old ones
from `acme.json`; Traefik renews as before.
- `git clone` over SSH and HTTPS; a push; the package registry serves
a pull.
- asxpio: log in to the admin, render an invoice (the boot test that
catches what a database check does not).
- datacenterbingo shows photos (Garage through the app) and
`/data.json`.
- `garage status`; `curl -I https://s3.asxp.io/public/<a known key>`.
- Grafana: targets up, logs from both hosts, security panel clean.
- CI: push an empty commit to an app repo; the deploy reaches
"healthy" (Phase 0 step 3).
- `systemctl start restic-backup xmpp-cert-sync` succeed.
**Rollback:** as in Phase 1. If services has already moved, it keeps
working against a Debian ops: nothing on services depends on how ops is
built.
## Phase 3: clean-up
1. Merge `nix` into `main`: `deploy.yaml` (Ansible) then finds no change
to apply, `nixos.yaml` deploys both hosts from now on.
2. Delete `ansible/`, `.forgejo/workflows/deploy.yaml`, the
`ANSIBLE_VAULT_PASSWORD` secret, `ansible/known_hosts` (the root copy
`known_hosts` stays), the Ansible parts of `renovate.json`.
3. Retire the storage repo (archive). Optional, later: drop the
`storage` network from the app compose files and point their
`DATABASE_URL`/`S3_ENDPOINT` at the host, then remove `apps.nix`'s
compatibility entries.
4. On both hosts after a week: `rm -rf /old-root`; delete the snapshots;
on ops remove the old Postgres 17 volume data, which went with
`/old-root`.
5. Delete the rehearsal servers, network and firewall (`managed-by=claude`
in the personal project).
6. Rotate what sat in the old history and the vault for a year
(`INTERNAL_TOKEN`, the JWT secrets, runner tokens), now in sops; and
give Grafana its own `secret_key` (production keeps the default for
now because its database was written with it; Grafana documents the
rotation).
7. Update the workspace `CLAUDE.md` (servers, deploys, gotchas).
8. Branches, last, because until then `main` is what deploys:
```sh
git push origin main:retired/ansible # keep the Ansible line
# Forgejo → Settings → Branches: default branch nix; unprotect main
git push origin --delete main
git push origin nix:main
# Forgejo: default branch main again; then
git push origin --delete nix
git branch -m main retired/ansible && git branch -m nix main
```
## Rules for the rehearsal pair
Restored data carries production credentials inside it. Anything that
would use them outward is kept from starting in `hosts/rehearsal/`, and
the following must hold every time:
- **Before a runner meets restored Forgejo data,** run
`migration/rehearsal-sanitize-forgejo.sh` on the rehearsal ops. A
restored database still has production's queued jobs, schedules and
Actions secrets; on 2026-11-16 the test runner picked up a queued
production job and was stopped only by the different secret key.
- XMPP and the Telegram gateway, Forgejo's mail, mirrors and webhooks,
Grafana mail, the crawler mail, the bucket replica and the interop
runner do not start there. The Minecraft plugins that talk outward
(DiscordSRV, ServerBackup, AutoUpdateGeyser) are set aside before
every start: on 2026-11-16 DiscordSRV was missed on the first start
and logged the production bot in from the test server for 15 seconds.
- Apps run with mail pointed at nothing and `INDEXNOW_KEY` empty; the
asxpio monitor worker (external probes) stays off.
- SSH is limited by a Hetzner firewall to the admin; backup credentials
are on the servers only in `/run`, only during a restore.
- Delete the servers when testing ends: they hold production data.
## Risks
| Risk | Mitigation |
|---|---|
| Lock-out after the switch | Phase steps say how each host is reached at each point; services through ops and the other way round; Hetzner console last |
| nixos-infect breaks with a later NixOS | pinned by commit and checksum; `nix_channel` pinned to 26.05; nixos-anywhere as the fallback (`nixos/README.md`) |
| ops disk (38 GB) | 18 GB free today; the Nix store adds 3–5 GB, `/old-root` holds the old images until deleted; delete `/old-root/var/lib/docker` once the apps run |
| Data of newer versions than 26.05 ships | Prometheus, Grafana, Xray, SillyTavern from nixos-unstable; Garage 2.x pinned; checked on the rehearsal pair with prod data |
| Something only production does | XMPP on real data and Let's Encrypt issuance were not rehearsed; both have a snapshot rollback and are checked first in their phase |
| A deploy during the window | freeze (Phase 0 step 6); the storage repo's deploy is off (step 4) |