iac/MIGRATION.md
Sergei Poljanski ce8b1a678e
docs: plan the ops conversion around the WireGuard hub; TODO list
ops is the WireGuard hub, so converting it takes the admin network
down for everyone, and services with it. The Phase 2 plan now says how
ops is reached at every point: WireGuard until the stop, its public
address in the bootstrap system, then WireGuard again, with a
break-glass root login from the admin's exit address (services' IPv4,
through Xray) for this phase only. The new system is activated with
`nixos-rebuild test` under a 15-minute dead-man reboot first, so a
lock-out ends in the reachable bootstrap system instead of a console
session; only after the laptop is back on WireGuard does `switch` make
it the boot default.

A TODO section tracks what is left, starting with deleting /old-root
on services after a week.

Assisted-by: Claude:opus-5-5
2026-11-17 07:46:42 +04:00

21 KiB
Raw Blame History

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.

TODO

  • 2026-11-24 or later, if services has run without surprises: rm -rf /old-root on asxpio-services (about 47 GB of Debian and its Docker data), then delete its snapshot pre-nixos-2026-11-17 in the Hetzner console.
  • Delete the two offline runners (ids 1 and 2) in Forgejo → Site administration → Runners.
  • Phase 2 (asxpio-ops), below.
  • One week after Phase 2: rm -rf /old-root on asxpio-ops, delete its snapshot.

Where things stand (2026-11-17)

asxpio-services runs NixOS since 2026-11-17 (Phase 1 below, done) and is deployed by .forgejo/workflows/nixos.yaml from main. asxpio-ops still runs Debian, deployed by Ansible from main; Ansible no longer manages services (inventory group nixos). Snapshot pre-nixos-2026-11-17 of services is kept until /old-root is deleted.

Phase 1 took 34 minutes of downtime (02:29–03:03 UTC, plus a few seconds for XMPP at 03:31), most of it the first build. What it taught, and is now in the config or the runbook:

  • Xray on services carries the admin's uplink (all traffic, WireGuard included, because of DPI). It was moved to a temporary server (claude-test-xray, same config from sops) and the admin's client switched before anything stopped. Phase 2 does not stop it.
  • Build on the server, not from the workstation. nixos-rebuild --build-host sent every derivation through the admin's slow uplink; copying the repo (git archive HEAD | ssh … tar -x) and running nixos-rebuild switch on the host took four minutes.
  • Podman DNS was open on podman0 only: CI jobs (own networks) could not resolve names. Fixed in modules/podman.nix.
  • IPv6 for published ports: Podman's default network forwards IPv4 only, Docker on Debian did both; XMPP was unreachable over IPv6 for half an hour. XMPP has its own IPv6 network now; anything else that publishes ports and has an AAAA record needs the same.
  • The rehearsal ran nothing that downloads inside a CI job, and never tested IPv6 from outside. Both are now part of the checks below.

Everything else ran first on the rehearsal pair (two cx23 in the personal project), most of it on a restored copy of 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:

    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:

        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.

Phase 1 is done (2026-11-17); the steps stay as the record and for a reinstall. 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):

    hcloud server create-image --type snapshot --description pre-nixos asxpio-services
    
  2. Stop what writes, then Docker:

    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:

    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):

    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:

    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)

Harder than Phase 1 for one reason: ops is the WireGuard hub. Every admin connection (and asxpio-services' only admin path) goes through wg0 on ops. While ops is converted, WireGuard is down for everyone (laptop, aleks, zerrtika, sanya, and services' spoke).

The admin's internet keeps working throughout: it leaves through Xray on services, which this phase does not touch. Its exit address is services' public IPv4, 46.62.228.216, and that is the address ops sees for anything the admin sends it outside WireGuard.

How ops is reached at each point

Point Path Why it works
Debian, before the stop WireGuard, as now —
nixos-infect's bootstrap system ssh root@135.181.27.77 Hetzner allows 22 from anywhere (Forgejo's git SSH); the bootstrap sshd has no AllowUsers; same host key
nixos-rebuild test (new system, not yet the boot default) WireGuard again (same keys); break-glass: ssh root@135.181.27.77 from 46.62.228.216 the flake allows root from that one address during this phase only
locked out anyway wait: a dead-man timer reboots into the bootstrap system after 15 min test does not change the boot default
after switch WireGuard; break-glass until removed —

services during the window: unreachable from outside (its SSH is WireGuard/private only); reach it through ops once ops answers: ssh -J root@135.181.27.77 root@10.10.0.20. It keeps running; only its log shipping to Loki and the runner's link to Forgejo pause.

Before the window (no downtime)

  1. App healthchecks in the compose files (Phase 0 step 3): asxpio, datacenterbingo, blog. Deployed on Debian through their normal CI, so the first deploy on NixOS can reach "healthy".
  2. Storage repo: disable its deploy workflow (Phase 0 step 4).
  3. Secrets: compare every ops secret in sops with the vault, /opt/storage/.env and the live values, as was done for services.
  4. Final rehearsal on claude-test-nixos-a with that night's ops backup: migration/ops-data.sh /restore, the apps pulled and healthy through the Docker CLI, monitoring history moved. Proves the data script end to end on fresh data.
  5. Break-glass in the flake: root SSH from 46.62.228.216 for ops only (asxpio.sshFrom override in hosts/asxpio-ops), merged before the window, removed after it.
  6. Announce to the WireGuard users: their tunnel drops for about 30 minutes; to everyone: sites, Forgejo and the registry are down for about 30 minutes. Freeze pushes (Phase 0 step 6).
  7. Snapshot of ops in the Hetzner console (the prod token is read-only), pre-nixos-<date>.

The window (about 25–35 minutes of downtime)

From a workstation on WireGuard, in the repo. Every step is a separate go-ahead.

  1. Ansible off: merge a commit to main that removes .forgejo/workflows/deploy.yaml; check no run is left. Ansible would otherwise apply the Debian roles to the converted ops on the next push.

  2. Fresh backup, dumps, stop (WireGuard still up):

    ssh root@10.20.0.10 'restic-backup run; set -e; d=/var/backups/restic-stage; install -d -m 700 $d; \
      docker stop asxpio asxpio-monitor datacenterbingo blog czsk vhpbot vhpbot-dev || true; \
      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 image prune -af; docker ps -q | xargs -r docker stop -t 60; \
      systemctl stop docker.socket docker containerd'
    

    Downtime starts. Undo: systemctl start docker.

  3. Convert: write /etc/nixos/bootstrap.nix (from tofu output -json user_data | jq -r '."asxpio-ops"'), then run nixos-infect as in Phase 1 step 3. Its existing 2 GB swapfile carries the build. WireGuard goes down here. Wait for ssh root@135.181.27.77 'test -d /old-root'.

  4. Build and test, not switch, on the host (Phase 1 lesson):

    git archive HEAD | ssh root@135.181.27.77 'rm -rf /root/iac; mkdir /root/iac; tar -x -C /root/iac'
    ssh root@135.181.27.77 'systemd-run --unit=deadman --on-active=15min systemctl reboot; \
      cd /root/iac/nixos && NIX_CONFIG="experimental-features = nix-command flakes" \
      nixos-rebuild test --flake .#asxpio-ops'
    

    Then from the laptop: WireGuard handshake, ssh root@10.20.0.10, ssh root@10.20.0.20. Only then: systemctl stop deadman.timer. If anything fails, do nothing: in 15 minutes ops reboots into the bootstrap system, reachable on 135.181.27.77, and the cause can be fixed there.

  5. Make it the boot default: nixos-rebuild switch --flake .#asxpio-ops (same build, instant).

  6. Data, start, images: ssh root@10.20.0.10 'bash -s /old-root' < nixos/migration/ops-data.sh, then reboot once.

  7. Check (all from outside where possible):

    • WireGuard: all five peers handshake again (wg show on ops).
    • Every site over IPv4 and IPv6 (Grafana → Probes, plus curl -6 from services); certificates are the old ones from acme.json.
    • Forgejo: web, git clone and push over SSH and HTTPS, the registry serves a pull; CI on services reaches Forgejo again.
    • asxpio: admin login, render an invoice. datacenterbingo: photos, /data.json. garage status; an anonymous read of the public bucket.
    • An app deploy from CI reaches "healthy".
    • Grafana: targets up, logs from both hosts, security panel clean; the first alert evaluation after the move sends nothing unexpected.
    • systemctl start restic-backup xmpp-cert-sync succeed (the push now uses the new key).
    • systemctl --failed empty; the login summary is clean.

After

  • Remove the break-glass from the flake, and the Debian ops key from xmppCertSyncKeysExtra (hosts/asxpio-services/xmpp-cert-install.nix).
  • Delete /old-root/var/lib/docker once the apps run (frees the old images on the small disk); the rest of /old-root after a week (TODO).
  • Phase 3.

Rollback: before step 3, systemctl start docker. After it, rebuild from the snapshot in the Hetzner console. services keeps working against a Debian ops: nothing on it 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), and claude-test-xray once the admin's client points at the production Xray again.

  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:

    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)