From ebbf4589835b1859a0d7cf71fd25c176ba93935d Mon Sep 17 00:00:00 2001 From: Sergei Poljanski Date: Tue, 17 Nov 2026 05:15:16 +0400 Subject: [PATCH] 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 --- .forgejo/workflows/nixos.yaml | 65 ++++- MIGRATION.md | 484 +++++++++++++++++++++------------- known_hosts | 2 + nixos/README.md | 62 +++-- nixos/flake.nix | 1 + renovate.json | 36 ++- 6 files changed, 437 insertions(+), 213 deletions(-) create mode 100644 known_hosts diff --git a/.forgejo/workflows/nixos.yaml b/.forgejo/workflows/nixos.yaml index bd291be..d4b3144 100644 --- a/.forgejo/workflows/nixos.yaml +++ b/.forgejo/workflows/nixos.yaml @@ -1,8 +1,17 @@ name: nixos -# Every push: evaluate each host, so a broken config never reaches main. -# Deploying from here is added when the first host runs NixOS -# (MIGRATION.md, step 4); until then hosts are switched by hand. +# Every push: evaluate every host, so a broken config never reaches main. +# main: build and switch each production host that already runs NixOS. +# A host still on Debian is skipped (it is checked for /etc/NIXOS first), +# so this job cannot touch a server before its conversion. +# +# Secret: SSH_DEPLOY_KEY (user deploy). Service secrets are decrypted on +# the hosts by sops-nix; CI holds none of them. +# +# Switching asxpio-services can restart the runner that runs this job: +# the change lands, the job shows as cancelled, the next run confirms. + +run-name: "${{ github.ref == 'refs/heads/main' && 'deploy' || 'evaluate' }}: ${{ github.ref_name }}" on: push: @@ -12,7 +21,7 @@ on: workflow_dispatch: jobs: - evaluate: + nixos: runs-on: nix-latest env: NIX_CONFIG: | @@ -26,10 +35,56 @@ jobs: - name: Checkout uses: actions/checkout@v7.0.1 + # Job containers are unprivileged, so Nix cannot sandbox builds in + # them. Evaluating catches config errors; the build itself happens + # on each server during the deploy. - name: Evaluate working-directory: nixos run: | - for host in asxpio-ops asxpio-services rehearsal; do + for host in asxpio-ops asxpio-services rehearsal-ops rehearsal-services; do nix eval --raw ".#nixosConfigurations.$host.config.system.build.toplevel.drvPath" echo done + + - name: Set up SSH + if: github.ref == 'refs/heads/main' + env: + SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }} + run: | + umask 077 + mkdir -p ~/.ssh + printf '%s\n' "$SSH_DEPLOY_KEY" > ~/.ssh/id_ed25519 + cp known_hosts ~/.ssh/known_hosts + # The runner's own host is reached through asxpio-ops: a job + # container connecting to its host arrives from a bridge address + # that sshd refuses. + cat > ~/.ssh/config <<'EOF' + Host asxpio-ops + HostName 10.10.0.10 + User deploy + Host asxpio-services + HostName 10.10.0.20 + User deploy + ProxyJump asxpio-ops + EOF + + - name: Deploy + if: github.ref == 'refs/heads/main' + working-directory: nixos + # Ops first: services reaches it for WireGuard, logs and Forgejo + run: | + # Tools from the flake's dev shell: the same pinned nixpkgs + for host in asxpio-ops asxpio-services; do + os=$(nix develop -c ssh "$host" 'test -e /etc/NIXOS && echo nixos || echo other') + if [ "$os" != nixos ]; then + echo "$host: not NixOS yet, skipped" + continue + fi + echo "== $host" + nix develop -c nixos-rebuild switch --flake ".#$host" \ + --target-host "$host" --build-host "$host" --sudo + done + + - name: Remove credentials + if: always() + run: rm -f ~/.ssh/id_ed25519 diff --git a/MIGRATION.md b/MIGRATION.md index e7ba59b..9742598 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,206 +1,326 @@ -# Moving from Ansible to NixOS +# Moving production from Ansible and Terraform to NixOS and OpenTofu -Plan and runbook. Delete this file when the last step is done. +The plan and the runbook. Delete this file when the last step is done. -**Goal:** both servers run NixOS built from `nixos/`; services are -native NixOS services where nixpkgs has a module and Podman containers -otherwise; no Docker, no Ansible. The servers themselves stay (they are -billed below list price): each is converted in place. +**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. -## Where things stand (2026-11-16) +**Nothing in production changes without the owner's go-ahead for that +step.** Every step below that touches a server says so. -Both servers still run Debian and are still deployed by Ansible from -`main`. Nothing below has touched them. +## Where things stand (2026-11-17) -On branch `nix`, each item verified on the rehearsal pair -(`nixos/README.md`): +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: -- OpenTofu renders one cloud-init for both servers; a new or rebuilt - server becomes NixOS by itself in about three minutes. OpenTofu plans - no change to the live servers. -- The same conversion run by hand on a Debian host with Docker data - keeps everything on disk (under `/old-root`), SSH host keys included. -- Base system: users with their Debian UIDs, SSH with the same crypto - settings, fail2ban, nftables firewall, journal cap, Podman. -- Secrets in sops, per host; the production files already hold the - WireGuard keys, the Xray config, the restic password, the S3 keys and - the alert mail account. -- WireGuard: hub on ops, spoke on services, IPv4 and IPv6 through the - tunnel, NAT on the hub. -- asxpio-services: Xray, SillyTavern, Minecraft (Paper, with Geyser) - and the ACME forwarder as native services; XMPP as Podman containers - (ejabberd started with test secrets; not started on production data). -- asxpio-ops: Postgres 18.7, Garage 2.5.0 and Forgejo 17.0.1 as native - services, with roles, buckets, keys and grants set from sops. -- Backup: the same script, schedule and retention; a run with hooks and - a restore were done against local repositories. -- **Real data:** last night's backups of both hosts were restored onto - the rehearsal pair and moved into the new layout with - `nixos/migration/*-data.sh`. Forgejo served the repositories, Postgres - had the 13 tables and the read-only `bingo` role, Garage the buckets - and objects, Minecraft the world (Java and Bedrock ports), SillyTavern - its users. Restore times: ops 6.3 GiB in under a minute, services - 25 GiB in three and a half. - -Found by rehearsing, fixed in the config: Garage refuses a credential -file with mode 0440; Geyser needs `libcrypto` and netlink, which the -container had and the NixOS unit did not; SillyTavern ignores the -module's listen flags. - -Still to port, in this order: - -- asxpio-services: `s3_replicate`, the monitoring agent, both CI runners - (against the rehearsal Forgejo). -- asxpio-ops: Traefik, monitoring, `crawler_alert`, `xmpp_cert_sync`, - the app stacks on Podman with their new database and S3 addresses. -- Retire the `storage` repo once ops is converted: Postgres and Garage - are defined here now. - -## What each service becomes - -Versions: nixpkgs 26.05 on 2026-11-16 against what runs today. - -| Today (Ansible role, container) | On NixOS | Data move | +| Area | Rehearsed | Notes | |---|---|---| -| `base`, `ssh_hardening`, `swap` | `modules/base.nix`, host files (done) | none | -| `wireguard` | `networking.wireguard` + sops | keys from the vault; same keys, so peers do not change | -| `traefik` 3.7.19 | native `services.traefik` (3.7.16), routes as Nix instead of container labels | `acme.json` | -| `forgejo` 17.0.1 | native `services.forgejo` (17.0.1) | `/opt/forgejo/data` to `/var/lib/forgejo`, SQLite as is | -| storage: Postgres 18.7 | native `services.postgresql` (18.7) | `pg_dumpall`, load (the image is musl, the package glibc: no reuse of the data directory) | -| storage: Garage 2.5.0 | native `services.garage` with a 2.x package (the default is 1.3.1: pin it) | metadata and data directories as is | -| `monitoring`: Prometheus, Grafana, Loki, blackbox | native modules | Grafana DB, Prometheus TSDB optional; Loki chunks are in S3 | -| `monitoring_agent`: Alloy, node-exporter, cAdvisor | native `services.alloy`, `services.prometheus.exporters.node`; cAdvisor against Podman | none | -| `restic_backup` | `services.restic.backups`, same repositories, hooks and schedule | none (repositories continue) | -| `s3_replicate`, `crawler_alert`, `xmpp_cert_sync` | systemd units from Nix | none | -| `forgejo_runner`, `forgejo_runner_interop` 13.2.1 | native `services.gitea-actions-runner` (forgejo-runner 13.2.1), jobs in Podman | re-register or copy `.runner` | -| `xray` 26.11.9 | native `services.xray` | config from the vault | -| `sillytavern` 1.19.0 | native `services.sillytavern` | data directory | -| `minecraft` (Paper on temurin 21) | native `services.minecraft-server` with `papermc` | world directory; check the Paper build matches the world | -| `xmpp` (anotherim-server, apushd, tackygram) | Podman containers: the server is a custom build, not nixpkgs' ejabberd | volumes | -| `acme_forward` (nginx) | native `services.nginx`, or dropped if XMPP certs move to `security.acme` | none | -| App stacks: asxpio, datacenterbingo, blog, czsk, vhpbot | Podman, started by their own CI as today, through the Docker-compatible socket; a flake per app is a later project in each app's repo | none (`/opt/`) | +| 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 | -Traefik has a native module, so it stays. Its Docker provider reads -labels from Podman's socket as well; routes for native services go in -the file provider, written from Nix. Caddy (`services.caddy`) would be -the simpler native choice, but changing proxy and operating system in -one move doubles what can go wrong: reconsider after step 6. +What each service became, and why: -## Steps +| 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 | -1. **Secrets** (done for what is ported). sops-nix: - `nixos/secrets/.yaml`, encrypted for an admin age key and each - host's SSH host key. Values move over from the Ansible vault as their - services move. The vault password leaves CI at the end. -2. **Network and access first** (done): WireGuard, firewall, SSH. An - admin reaches a converted host the usual way. -3. **Port asxpio-services** (no chicken-and-egg: Forgejo and CI live or - depend on ops), service by service from the table, each one tried on - the rehearsal pair. Before the conversion, restore last night's - backup of the host onto the rehearsal server and check each service - comes up on real data (versions differ slightly from the containers: - table above). -4. **Convert asxpio-services** (runbook below). Add the deploy job to - `.forgejo/workflows/nixos.yaml`: on `main`, `nixos-rebuild switch - --target-host` as user `deploy`. Remove the services roles from - `ansible/site.yaml`. -5. **Port asxpio-ops** the same way. Order inside the host: Postgres and - Garage, Forgejo, Traefik, monitoring, then the app stacks on Podman. - Rehearse the app deploy workflows against Podman before the day. -6. **Convert asxpio-ops** (runbook below), from a workstation: its own - CI cannot deploy the host it runs through. -7. **Clean up.** Delete `ansible/`, `deploy.yaml`, the vault secret in - CI, `/old-root` on both hosts, the Postgres 17 volume, this file. - Then make the branch the default: +## 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 - git push origin main:retired/ansible # keep the old line - # Forgejo: Settings -> Branches -> default branch: nix; unprotect main + 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://`. + +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/`; 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/`. + - 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; then + # Forgejo: default branch main again; then git push origin --delete nix git branch -m main retired/ansible && git branch -m nix main ``` - Do this last: until then `main` is what deploys the hosts. - -Each step ends with both hosts working, so the work can stop between -any two. - -## Converting a host in place - -Tested end to end on 2026-11-16 (cx23, Debian 13, Docker 29.9.3): the -conversion took three and a half minutes, containers and volumes were -intact afterwards. Expect 15 to 30 minutes of downtime per host, -depending on how much data changes format (table above). - -Before: - -1. Announce the window; no CI job running. -2. `restic-backup run` on the host and check both repositories. -3. Take a Hetzner snapshot of the server. **This is the rollback:** - rebuilding from it returns the Debian system as it was, on the same - server. -4. Stop the services so nothing writes during the move - (`docker stop -t 120 minecraft` first on services), then stop Docker. - Take the dumps the new services load: `pg_dumpall` on ops. - -Convert (as root on the host; the same commands cloud-init runs): - -5. Write `/etc/nixos/bootstrap.nix` with the content from - `terraform/cloud-init/nixos.yaml.tftpl` (`tofu output user_data` - shows it with the values filled in). -6. Run the `runcmd` line from the same file. The host reboots into a - bare NixOS. Reach it as root: ops on its public address, services - through ops over the private network. -7. `nixos-rebuild switch --flake .#` (see `nixos/README.md`). - Services that own data stay stopped: the marker file is missing. -8. Move the data and start everything, then reboot once: - - ```sh - ssh root@ 'bash -s /old-root' < nixos/migration/-data.sh - ``` - - On ops the script loads the Postgres dump from - `/old-root/var/backups/restic-stage`: put `pg_dumpall.sql` and a - `sqlite3 .backup` of Forgejo's database (`forgejo-gitea.db`) there in - step 4. What the script does not move stays in `/old-root`: `/home`, - `/root/backups`, the app stacks' `/opt/`. -9. Verify: WireGuard up, every service of the host answers, - `systemctl --failed` empty, one CI run, one backup run. - -After a week without surprises: `rm -rf /old-root`, delete the snapshot. - -Rollback, at any point after step 6: `hcloud server disable-protection - rebuild`, rebuild from the snapshot, `tofu apply`. - ## 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/`: - XMPP and the Telegram gateway, Forgejo's mail, mirrors and webhooks, - Minecraft's Discord plugin. On 2026-11-16 that plugin was missed on - the first start: the bot logged in from the test server for about 15 - seconds and cleared its slash commands on shutdown. Check a service's - plugins and integrations before its first start on real data. -- A Hetzner firewall limits SSH to the admin; the backup credentials are - on the servers only in `/run` and only during a restore. +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 -- **Lock-out.** A converted host without WireGuard is reachable only as - described in step 6. Step 2 exists to remove that risk; the Hetzner - console is the last resort. -- **ops is small.** 18 GB free today; the Nix store takes 3 to 5 GB and - `/old-root` another 2 GB plus the old container images. Prune images - before, delete `/old-root/var/lib/docker` early. -- **App deploys on Podman.** The app workflows call `docker compose`; - compose against Podman's socket mostly works, healthcheck waits and - network names are where it differs. Rehearse (step 5). -- **The CI runner on Podman** starts job containers through the socket; - the earlier attempt (branch `nixos-services`) had this working piece - by piece but never under a full pipeline. -- **First-boot method.** nixos-infect depends on the scripted initrd, - which upstream is retiring (`nixos/README.md`, last section). +| 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) | diff --git a/known_hosts b/known_hosts new file mode 100644 index 0000000..ed9c64c --- /dev/null +++ b/known_hosts @@ -0,0 +1,2 @@ +10.10.0.10,10.20.0.10 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEzuhnXIFERF+slCGpjnQFhaO5iTVqVn9OMbt7jeFOUf +10.10.0.20,10.20.0.20 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDArwdI8bHpQhNnMqz7vOIGJvb5eYE7GahtkbxrNgtvp diff --git a/nixos/README.md b/nixos/README.md index d58b641..71508e5 100644 --- a/nixos/README.md +++ b/nixos/README.md @@ -2,32 +2,43 @@ Each server's whole system, as one flake. A server is created by OpenTofu (`../terraform`), converts itself to NixOS on first boot, and gets its -configuration from here. Moving the services over from `../ansible` is in -progress: see `../MIGRATION.md` for what already lives here. +configuration from here. Production is moving over from `../ansible`; +the plan and its state are in `../MIGRATION.md`. ``` -flake.nix inputs (nixpkgs 26.05, unstable for a few packages, sops-nix), hosts, dev shell -modules/hetzner.nix disk, boot and network of a Hetzner Cloud VM -modules/base.nix users, SSH, fail2ban, firewall, journal cap, Nix settings -modules/wireguard.nix the admin network; ops is the hub -modules/podman.nix Podman, for what has no native NixOS service -modules/backup.nix nightly restic backup, `restic-backup` command -modules/alert.nix mail when a unit fails -hosts/asxpio-ops/ what only asxpio-ops has -hosts/asxpio-services/ what only asxpio-services has, one file per service -hosts/rehearsal/ overrides that turn the two hosts into a test pair -migration/ one-off scripts that move Debian-era data into place -secrets/*.yaml sops-encrypted, one file per host +flake.nix inputs (nixpkgs 26.05, unstable for a few packages, sops-nix), hosts, dev shell +modules/hetzner.nix disk, boot and network of a Hetzner Cloud VM +modules/base.nix users, SSH, fail2ban, firewall, journal cap, Nix settings +modules/wireguard.nix the admin network; ops is the hub +modules/podman.nix Podman, and the Docker CLI on its socket +modules/backup.nix nightly restic backup, `restic-backup` command +modules/alert.nix mail when a unit fails +modules/monitoring-agent.nix node, container and security metrics, logs to Loki +hosts/asxpio-ops/ Traefik, Forgejo, Postgres, Garage, monitoring, app stacks +hosts/asxpio-services/ runners, Minecraft, XMPP, Xray, SillyTavern, one file each +hosts/rehearsal/ overrides that turn the two hosts into a test pair +migration/ one-off scripts: Debian-era data into place, rehearsal clean-up +secrets/*.yaml sops-encrypted, one file per host ``` Services run as native NixOS services wherever nixpkgs has a module; -the rest are Podman containers declared here. There is no Docker. +the rest are Podman containers declared here (XMPP) or deployed by their +own repositories (the app stacks on ops). There is no Docker daemon: +`docker` is the Docker CLI talking to Podman's socket, so `docker ps`, +`docker compose` and the apps' CI deploys work as they did. + +Each service file also says what it adds to the backup +(`asxpio.backup`), which ports and users the security baseline should +expect (`asxpio.security`), and whether it waits for restored data +(`asxpio.waitForData`). All tools used below come from the dev shell: `nix develop ./nixos`. ## Changing something -Edit, push a branch (CI evaluates every host), then switch the host: +Edit, push a branch (CI evaluates every host), merge to `main`: CI +builds each host on itself and switches to it, ops first. A host that +does not run NixOS yet is skipped. By hand, over WireGuard: ```sh nixos-rebuild switch --flake .#asxpio-services \ @@ -36,8 +47,11 @@ nixos-rebuild switch --flake .#asxpio-services \ Only units whose definition changed restart. Undo with `nixos-rebuild switch --rollback` on the host, or pick the previous -generation in the boot menu (Hetzner console). Update all packages with -`nix flake update`, then commit `flake.lock`. +generation in the boot menu (Hetzner console). Package updates come from +Renovate (`flake.lock` weekly, pinned images and versions as they are +released); by hand: `nix flake update`, commit `flake.lock`. + +Try anything risky on the rehearsal pair first (below). ## Building the servers from scratch @@ -170,9 +184,17 @@ hcloud server create --name rehearsal-services --type cx23 --image debian-13 --l Then, per server: put its age recipient in `.sops.yaml` (`&rehearsal_*`) and `sops updatekeys secrets/rehearsal-.yaml`; put its addresses in -`hosts/rehearsal/.nix`; `nixos-rebuild switch --flake +`hosts/rehearsal/.nix` (and ops's public key in services' file, +the other way round for WireGuard); `nixos-rebuild switch --flake .#rehearsal- --target-host root@ --build-host root@`; -reboot once; `touch /var/lib/.data-in-place`. +reboot once. + +With test data: `touch /var/lib/.data-in-place`. With a restored copy of +production: restore last night's snapshot to `/restore`, run +`migration/ops-data.sh /restore` or `services-data.sh /restore`, and on +ops `migration/rehearsal-sanitize-forgejo.sh` before the runner starts. +Read the rehearsal rules in `../MIGRATION.md` first: restored data +carries production credentials. ## How the first boot works, and its limits diff --git a/nixos/flake.nix b/nixos/flake.nix index 5baed2d..1b49b34 100644 --- a/nixos/flake.nix +++ b/nixos/flake.nix @@ -54,6 +54,7 @@ restic rclone jq + openssh ]; }; diff --git a/renovate.json b/renovate.json index 8edb1a8..0ab4a13 100644 --- a/renovate.json +++ b/renovate.json @@ -14,11 +14,22 @@ "# renovate: datasource=(?\\S+) depName=(?\\S+)\\s+[a-z_0-9]+:\\s*\"?(?[^\"\\s]+)\"?" ] }, + { + "description": "Versions in the NixOS config, marked the same way: # renovate: ... above `name = \":\";` or `name = \"\";`", + "customType": "regex", + "managerFilePatterns": [ + "/^nixos/.+\\.nix$/" + ], + "matchStrings": [ + "# renovate: datasource=(?\\S+) depName=(?\\S+)\\s+[A-Za-z_0-9]+ = \"(?:[^\"]*:)?(?[^\":]+)\";" + ] + }, { "description": "Runner job images, pinned in the labels: docker://:", "customType": "regex", "managerFilePatterns": [ - "/^ansible/roles/forgejo_runner/(templates/config\\.yaml\\.j2|tasks/main\\.yaml)$/" + "/^ansible/roles/forgejo_runner/(templates/config\\.yaml\\.j2|tasks/main\\.yaml)$/", + "/^nixos/hosts/asxpio-services/runner\\.nix$/" ], "matchStrings": [ "docker://(?[a-z0-9./_-]+):(?[A-Za-z0-9._-]+)" @@ -37,7 +48,8 @@ { "description": "Runner labels name their line (node-20, debian-12, python-3.11): never leave it", "matchFileNames": [ - "ansible/roles/forgejo_runner/**" + "ansible/roles/forgejo_runner/**", + "nixos/hosts/asxpio-services/runner.nix" ], "matchUpdateTypes": [ "major" @@ -47,7 +59,8 @@ { "description": "python-3.11 / python-3.12 labels stay on their minor line", "matchFileNames": [ - "ansible/roles/forgejo_runner/**" + "ansible/roles/forgejo_runner/**", + "nixos/hosts/asxpio-services/runner.nix" ], "matchPackageNames": [ "python" @@ -57,7 +70,8 @@ }, { "matchFileNames": [ - "ansible/roles/forgejo_runner/**" + "ansible/roles/forgejo_runner/**", + "nixos/hosts/asxpio-services/runner.nix" ], "matchPackageNames": [ "python" @@ -75,7 +89,8 @@ { "description": "Both label files carry the same pins: one PR per image", "matchFileNames": [ - "ansible/roles/forgejo_runner/**" + "ansible/roles/forgejo_runner/**", + "nixos/hosts/asxpio-services/runner.nix" ], "groupName": "runner job images", "matchUpdateTypes": [ @@ -101,5 +116,14 @@ "The deploy job that applies this shows as cancelled; the next run confirms the result." ] } - ] + ], + "nix": { + "enabled": true + }, + "lockFileMaintenance": { + "enabled": true, + "schedule": [ + "before 6am on monday" + ] + } }