iac/nixos
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Renovate Bot d7abac336e
All checks were successful
nixos / nixos (push) Successful in 22s
deps: Update blog digest to 5ff625f
2026-11-17 09:23:03 +00:00
..
hosts services: serve czsk.it from its flake, beside the container 2026-11-17 13:18:47 +04:00
keys nixos: comin deploys only signed commits 2026-11-17 11:54:15 +04:00
modules until comin status --json | jq -e '.deployer.deployment.generation.selected_commit_id == "$H" and (.deployer.deployment.status == "done" or .deployer.deployment.status == "failed")' >/dev/null; do sleep 10; done 2026-11-17 13:11:13 +04:00
secrets nixos: drop the rehearsal pair and other migration leftovers 2026-11-17 11:11:33 +04:00
.sops.yaml nixos: drop the rehearsal pair and other migration leftovers 2026-11-17 11:11:33 +04:00
flake.lock deps: Update blog digest to 5ff625f 2026-11-17 09:23:03 +00:00
flake.nix deps: Update blog digest to 5ff625f 2026-11-17 09:23:03 +00:00
README.md ci: evaluate only, comin deploys 2026-11-17 11:39:40 +04:00

NixOS

Each server's whole system, as one flake. A server is created by OpenTofu (../tofu, OpenTofu), converts itself to NixOS on first boot, and gets its configuration from here. How the servers moved here from Debian and Ansible is on branch migration.

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
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 (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. The servers themselves (and DNS, firewalls, buckets) are OpenTofu in ../tofu; its state is in the bucket asxpio-tofu-main.

Changing something

Edit, push a branch (CI evaluates every host), merge to main: each host's comin (modules/comin.nix) pulls main within a minute, builds nixosConfigurations.<hostname> on the host and switches to it. A branch testing-<hostname> on top of main is applied to that host alone with test. comin status on the host shows the state.

By hand, when comin can't fetch (Forgejo or Traefik on ops broken), over WireGuard, building on the host itself:

git archive HEAD | ssh root@10.20.0.10 'rm -rf /root/iac; mkdir /root/iac; tar -x -C /root/iac'
ssh root@10.20.0.10 'cd /root/iac/nixos && nixos-rebuild switch --flake .#asxpio-ops'

comin moves on from there with the next commit on main.

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). 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 a throwaway server first (below).

Building the servers from scratch

What you need: a Hetzner Cloud project and its API token, Object Storage keys (hel1 and fsn1), an SSH key listed in ../tofu/keys.tofu, and, to restore data, the restic password (../RESTORE.md).

The existing servers are billed below today's list price, and a new server is not. For asxpio-ops and asxpio-services use "Reinstalling in place" below; this section is for a new project or a lost server.

  1. Create the infrastructure (network, firewalls, DNS, buckets, servers):

    cd tofu
    cp secrets.auto.tfvars.example secrets.auto.tfvars   # fill in the token and keys
    export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=...   # for the state bucket
    tofu init
    tofu apply
    

    In a new project the state bucket does not exist yet: comment out the backend "s3" block for the first apply, then restore it and run tofu init -migrate-state.

  2. Wait about four minutes. Each server boots Debian, and cloud-init (../tofu/cloud-init/nixos.yaml.tftpl) runs a pinned nixos-infect, which installs NixOS over the running system and reboots. The result is a bare NixOS: root login with the keys from keys.tf, public and private network, nothing else.

    ssh root@<ops public IP> nixos-version
    ssh -J root@<ops public IP> root@10.10.0.20 nixos-version   # services: no public SSH
    

    If a server still answers as Debian after ten minutes, read /var/log/nixos-infect.log on it.

  3. Set the host's facts in hosts/<name>/default.nix: the public addresses (tofu output), and on ops the WireGuard endpoint the others use. Add the host's age recipient to .sops.yaml and re-encrypt its secrets:

    ssh root@<ip> cat /etc/ssh/ssh_host_ed25519_key.pub | ssh-to-age
    sops updatekeys secrets/<name>.yaml
    
  4. Install the configuration (same addresses as in step 2; add NIX_SSHOPTS="-J root@<ops public IP>" for services):

    cd nixos
    nixos-rebuild switch --flake .#asxpio-ops \
      --target-host root@<ip> --build-host root@<ip>
    ssh root@<ip> reboot     # once: new kernel command line, interface names
    

    From here on root and the admin users log in only from WireGuard and the private network (asxpio.sshFrom): connect your WireGuard client to ops first, or go through the other server over the private network.

  5. Restore the data: ../RESTORE.md.

  6. Remove what the conversion left behind: rm -rf /old-root (the Debian image, about 2 GB).

Reinstalling in place

Keeps the server, its addresses and its price; wipes the disk.

cd tofu
hcloud server disable-protection asxpio-services rebuild
tofu output -json user_data | jq -r '."asxpio-services"' |
  hcloud server rebuild --image debian-13 --user-data-from-file - asxpio-services
tofu apply          # puts the rebuild protection back

Then continue at step 2 above. The server gets new SSH host keys, so step 3's sops updatekeys is needed.

Secrets

secrets/<host>.yaml is encrypted with sops for the keys in .sops.yaml: the admin's age key and the host's SSH host key. The host decrypts at boot into /run/secrets.

sops secrets/asxpio-services.yaml     # edit; needs ~/.config/sops/age/keys.txt

The SSH host key is therefore part of a host's identity. It survives the in-place conversion and is in the backup (/etc/ssh); a rebuilt server has a new one and needs sops updatekeys.

Data and the marker file

Services that own data (asxpio.waitForData: Postgres, Garage, Forgejo, Minecraft, SillyTavern, XMPP, the backup itself) do not start until /var/lib/.data-in-place exists. A fresh install therefore never creates empty state where a restore is about to land, and never backs up an empty host over a full one. After restoring or moving the data: touch /var/lib/.data-in-place, then start the units or reboot.

Testing on a copy of production

The test pair used for the migration (.#rehearsal-ops, .#rehearsal-services: other keys and addresses, dummy secrets, backups into local directories) was removed after it; git log -- nixos/hosts/rehearsal finds it to bring back. A throwaway server is created like a real one (above, in the personal project), then gets that night's snapshot restored (RESTORE.md, "A whole host").

A restored copy carries production credentials:

  • Anything that would use them outward stays off: XMPP and the Telegram gateway, mail (Forgejo, Grafana, crawler), the bucket replica, certificate pushes, the CI runners, Minecraft's outward plugins (DiscordSRV, ServerBackup, AutoUpdateGeyser).
  • Before any runner meets Forgejo's data, delete production's queued jobs, schedules, Actions secrets, runners and webhooks (the removed hosts/rehearsal/sanitize-forgejo.sh does that).
  • Start app containers by hand only, with mail pointed at nothing and INDEXNOW_KEY empty; never vhpbot or asxpio-monitor.
  • Limit SSH to your address with a Hetzner firewall, keep backup credentials in /run only, and delete the server when done.

How the first boot works, and its limits

  • nixos-infect is pinned by commit and checksum in ../tofu/servers.tofu; it replaces the operating system, so bump it deliberately and try it on a throwaway server.
  • It keeps the Debian image's partitions (modules/hetzner.nix matches them) and moves the old system to /old-root.
  • bootstrap.nix in the cloud-init corrects three things for the first generation: the scripted initrd (the takeover does not exist in the systemd initrd, which NixOS 26.05 uses by default), the IPv4 default route, and the private network's route. All three were found and verified on test servers on 2026-11-16.
  • The scripted initrd is deprecated upstream. When a NixOS release drops it, keep nix_channel at the last release that has it (the flake then upgrades the system), or switch the first boot to nixos-anywhere.