iac/nixos/README.md
Sergei Poljanski 6d9122eeff
Some checks failed
nixos / nixos (push) Has been cancelled
main: the current setup only
Both servers run NixOS. The Ansible code and the move itself leave main
for their own branches: `ansible` is the Debian/Ansible setup as it was
before the migration, `migration` keeps the plan and record, the data
scripts and everything else the move needed.

README and RESTORE describe the setup as it is now: NixOS, Podman,
sops, OpenTofu, the backup paths and hooks of the new layout. The
README carries the TODO list that MIGRATION.md had. The Forgejo
sanitising script stays, under hosts/rehearsal, with the rules for
rehearsing on restored production data in the NixOS README. Renovate
no longer looks at Ansible files.

Assisted-by: Claude:opus-5-5
2026-11-17 10:08:40 +04:00

225 lines
9.8 KiB
Markdown

# 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
hosts/rehearsal/ overrides that turn the two hosts into a test pair
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`: 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 \
--target-host root@10.20.0.20 --build-host root@10.20.0.20
```
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 the rehearsal pair 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):
```sh
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.
```sh
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:
```sh
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):
```sh
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**.
```sh
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, and `known_hosts` entries change.
## Secrets
`secrets/<host>.yaml` is encrypted with [sops](https://github.com/getsops/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`.
```sh
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.
## Rehearsal
`.#rehearsal-ops` and `.#rehearsal-services` are the two hosts' own
configurations plus `hosts/rehearsal/`: other keys and addresses, dummy
secrets, SSH open to the world, backups into local directories, and
anything that would act as production (the XMPP server) started by hand
only. **Every change is tried there first**, and the pair should be able
to do everything production does before a production host is converted.
Two servers on a private network with the production addresses:
```sh
hcloud network create --name rehearsal --ip-range 10.10.0.0/20
hcloud network add-subnet rehearsal --type cloud --network-zone eu-central --ip-range 10.10.0.0/23
tofu -chdir=../tofu output -json user_data | jq -r '."asxpio-ops"' > /tmp/ops.yaml
tofu -chdir=../tofu output -json user_data | jq -r '."asxpio-services"' > /tmp/services.yaml
hcloud server create --name rehearsal-ops --type cx23 --image debian-13 --location hel1 \
--ssh-key <your key> --network rehearsal --user-data-from-file /tmp/ops.yaml
hcloud server create --name rehearsal-services --type cx23 --image debian-13 --location hel1 \
--ssh-key <your key> --network rehearsal --user-data-from-file /tmp/services.yaml
```
Then, per server: put its age recipient in `.sops.yaml` (`&rehearsal_*`)
and `sops updatekeys secrets/rehearsal-<role>.yaml`; put its addresses in
`hosts/rehearsal/<role>.nix` (and ops's public key in services' file,
the other way round for WireGuard); `nixos-rebuild switch --flake
.#rehearsal-<role> --target-host root@<ip> --build-host root@<ip>`;
reboot once.
With test data: `touch /var/lib/.data-in-place`. With a restored copy
of production: restore that night's snapshot to `/` (RESTORE.md, "A whole
host"), and mind what the copy carries:
- Production credentials. Anything that would use them outward stays
off in `hosts/rehearsal/`: XMPP and the Telegram gateway, mail
(Forgejo, Grafana, crawler), the bucket replica, certificate pushes,
the interop runner, Minecraft's outward plugins (DiscordSRV,
ServerBackup, AutoUpdateGeyser).
- On ops, run `hosts/rehearsal/sanitize-forgejo.sh` before any runner
meets the data: it removes production's queued jobs, schedules,
Actions secrets, runners and webhooks.
- 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 servers 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 rehearse.
- 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](https://github.com/nix-community/nixos-anywhere).