my homelab: used desktops, incus, and nixos

neel saninov 17, 202616 min readhomelab · nix · infra · hardware

contents

my homelab is three used office desktops running an incus cluster. it hosts a mix of containers and vms: my git server and its ci runner, a vpn gateway, a monitoring stack, sandboxes, and some windows vms. almost all of it is defined in git now. opentofu describes the cluster (networks, acls, storage, instances), everything inside a linux instance is a nixos flake, and the windows images are built by nix too.

this post covers the hardware first, then how the declarative side is put together and what broke along the way.

hardware#

dell optiplex 3090lenovo thinkcentre m70qdell optiplex 5070
form factormicrotinysff / tower
cpui5-10500t, 6c/12t, 3.8 ghz boosti7-10700t, 8c/16t, 4.5 ghz boosti7-9700, 8c/8t, 4.7 ghz boost
ram24 gib32 gib48 gib
storage512 gb nvme512 gb nvme, 1 tb sata ssd256 gb nvme, 2 tb 2.5" hdd (5400 rpm)
nicrealtek rtl8111, 1 gbeintel i219-v, 1 gbeintel i219-v, 1 gbe
gpuintel uhd 630intel uhd 630intel uhd 630

all three are 9th/10th gen intel business desktops. these show up on the used market in bulk when companies replace them. they have vt-x and vt-d, idle low, and run linux without anything special. the two t-series chips are 35w parts, which is why they fit in the small cases.

how i split work between them mostly follows from the specs:

  • the thinkcentre has the most threads, so it runs ci. a nix build of a full nixos image uses every core it gets.
  • the optiplex 5070 has the most ram and the largest disk, so it runs the vm-heavy and storage-heavy things. the windows sandbox vms for malbox need a few gigabytes each, and anything that needs bulk storage lives on the 2 tb drive. it's a 5400 rpm laptop hdd, so it's slow, but it's fine for large files read sequentially.
  • the optiplex 3090 runs the ovn northbound database, my dev container, and the vpn gateway. it has the least ram, so it's the one i'd upgrade first.

limits#

every instance is pinned to one node. the storage pools use the dir driver, which is local to each cluster member, so an instance's disk lives on the node it runs on. memory limits on containers are caps, not reservations, so the totals on a node can add up to more than its physical ram. that's fine for containers that are mostly idle, but vms actually hold the memory they're given, so those are what really fill a node.

each node has one 1 gbe port on the home lan. there's no separate storage or management network at the physical layer. all the separation is done with incus and ovn networks on top of that one link. 1 gbe is the main bottleneck: copying a large image or volume between nodes tops out around 110 mb/s, so moving a 500 gib volume would take over an hour. that's another reason storage-heavy instances stay where they are.

moving a volume between nodes
slowest disk
1 gbe · this lab112 mib/s · link-bound
1 h 16 min
2.5 gbe280 mib/s · link-bound
30 min
10 gbe1121 mib/s · link-bound
8 min
throughput is the slower of the link (~94% of line rate after tcp overhead) and the disk on either end. with the 5400 rpm hdd on one side, a faster nic buys nothing.

none of the integrated gpus are passed into instances. for gpu work (my ml research) i use georgia tech's cluster instead.

firmware is current on the two dells. the lenovo is still on a 2021 bios, because updating it means evacuating the node first.

two layers#

the split i ended up with: tofu owns everything incus knows about, and nix owns everything inside an instance.

  • one opentofu repo with the lxc/incus provider: nodes, storage pools, the default profile, server config, networks, acls, instances.
  • a nixos flake template plus the base incus images built from it.
  • one flake per service.

the service repos don't create incus networks, instances, or volumes, and the tofu repo never says what runs inside an instance. the two layers only have to agree on a few things, mostly nic names and ports. if tofu names a nic wan0, the flake has to configure wan0.

before this, everything was made by hand with the incus cli. the vpn gateway was a hand-configured alpine container, the monitoring box was a debian container running docker compose, and the acls were made by hand too. it worked, but the only record of how the cluster was set up was the cluster itself.

the tofu side#

the whole cluster is three files: main.tf (provider, nodes, storage, profile, server config), networks.tf (acls, bridges, ovn networks), and instances.tf (one table entry per instance).

the first version used modules, and each module took network and pool names as variables. adding an instance meant editing the module, its variables.tf, and the root module. i flattened it into one table, and used moved blocks so tofu moved the existing state instead of destroying and recreating instances:

moved {
  from = module.core.incus_instance.monitor
  to   = incus_instance.monitor
}

after one apply the moved blocks can be deleted. an instance entry now looks like this:

web = {
  host  = "node-b"
  type  = "container"
  image = "nxt-container"
  config = {
    "limits.cpu"    = "2"
    "limits.memory" = "2GiB"
  }
  root = { pool = "local", size = "10GiB" }
  nics = {
    eth0 = { network = "net-provision" }
    wan0 = { network = "net-lab-wan", name = "wan0" }
  }
}

one incus_instance resource turns the table into instances, with dynamic blocks for nics, extra disks, and other devices like /dev/kvm passthrough or proxy devices:

resource "incus_instance" "this" {
  for_each = local.instances

  name     = each.key
  type     = each.value.type
  image    = try(each.value.image, null)
  target   = each.value.host
  profiles = [incus_profile.default.name]
  config   = try(each.value.config, null)

  dynamic "device" {
    for_each = each.value.nics
    content {
      name       = device.key
      type       = "nic"
      properties = device.value
    }
  }

  lifecycle {
    ignore_changes = [running]
  }
}

ignore_changes = [running] keeps tofu from starting something i stopped on purpose. the table refers to networks and pools by name strings, so tofu can't infer ordering, and the resource has an explicit depends_on on every network and pool.

adopting things that already existed#

the cluster was older than the repo, so the first job was getting existing objects into state without recreating them. the first commit had a script that read incus list --format=json and similar commands and printed import blocks for tofu plan -generate-config-out. not everything can be imported with the provider version i'm on: images and snapshots have no import support, and only custom storage volumes can be imported.

server config was the most confusing part. incus_server has no import support at all. what works is adding the resource with values identical to the live server and applying. the plan shows a create, but it only records state and re-sends the same values.

server config keys also have scopes. some are per cluster member and some are cluster-wide (incus lists them at /1.0/metadata/configuration), so there's one incus_server per member with a target, and a separate one for global keys:

resource "incus_server" "local" {
  for_each = local.server_local_config

  target = each.key
  config = each.value # cluster.https_address, core.metrics_address, ...
}

resource "incus_server" "global" {
  config = {
    "network.ovn.northbound_connection" = "tcp:${local.nodes.node-a}:6641"
  }

  depends_on = [incus_server.local]
}

other cluster behavior that showed up in the config:

  • clustered bridge networks need a per-member "pending" definition before the network itself can be created, so new bridges have a for_each = local.nodes resource with target set. bridges that existed before a node joined don't need this, because joining members get existing networks automatically.
  • incus evaluates acl drop rules before allow rules no matter what order you write them in, so you can't rely on an allow placed above a drop.

networks#

most networks are plain incus bridges: a nat uplink for lab instances, a management network with no gateway, one for the git server and its runner, an isolated one for the malware sandbox with no gateway or nat, and a couple for isolated vms with dns filtering. there are also three ovn networks: two vpn segments and a provisioning network.

every lab network drops traffic to the home lan. that's one acl merged into each network's config:

locals {
  block_home_lan = {
    "security.acls"                        = incus_network_acl.block-home-lan.name
    "security.acls.default.egress.action"  = "allow"
    "security.acls.default.ingress.action" = "allow"
  }
}

resource "incus_network" "net-lab-wan" {
  name = "net-lab-wan"
  type = "bridge"
  config = merge(local.block_home_lan, {
    "ipv4.routing" = "true"
  })
}

the monitoring network is the exception. it defaults to drop in both directions, and its acl allows dhcp and the cluster nodes only. those allow rules are generated from the same node list main.tf uses, so adding a node also lets monitoring scrape it:

[
  for node, address in local.nodes : {
    action      = "allow"
    description = "Allow observability target ${node}"
    destination = "${address}/32"
    state       = "enabled"
  }
]

the provisioning network is how nix gets into instances. every nix-managed instance has a nic on it, and its acl only lets my dev container talk to provisioned guests. guests can't reach each other on it.

the two vpn segments use a nixos gateway container as their dhcp gateway instead of the ovn router. the gateway has a wan nic, a nic on each segment, and a wireguard tunnel. its nftables forward chain only lets the segments out through the tunnel, and drops anything going to the wan nic or between segments:

iifname "${sandboxIf}" oifname "${vpnIf}" ip saddr ${sandboxCidr} accept
iifname "${trustedIf}" oifname "${vpnIf}" ip saddr ${trustedCidr} accept

iifname "${sandboxIf}" oifname "${wanIf}" drop
iifname "${trustedIf}" oifname "${wanIf}" drop
iifname "${sandboxIf}" oifname "${trustedIf}" drop
iifname "${trustedIf}" oifname "${sandboxIf}" drop

if the tunnel is down, anything on those segments has no internet instead of falling back to the home connection. port forwards are a small module that takes a list of { port, protocols, target } entries and generates both the dnat rules and the matching forward-chain accepts, so the two can't drift apart.

packet tracer
from
to
  1. vm
    vm on sandbox
    on vpn segment sandbox
  2. net
    ovn · vpn segment sandbox
  3. acl
    incus acl
    sandbox-isolation + block-home-lan
  4. nft
    gateway forward chain
    nftables, policy drop
  5. wg
    wg0 tunnel
    up
  6. dst
    internet
    via the vpn exit
acceptgateway · nftables forward
chain forward {
  type filter hook forward priority filter; policy drop;
  # …
  iifname "${sandboxIf}" oifname "${vpnIf}" ip saddr ${sandboxCidr} accept
}

the gateway is the segment's dhcp gateway, and the only accept for this segment is out through wg0.

pick a source and a destination. the packet stops at the first rule that decides. incus checks acl drop rules before allows, whatever order they're written in.

from flake to instance#

new linux instances start from a flake template:

mkdir my-host && cd my-host
nix flake init -t git+https://git.neels.dev/neelsani/nxt

it has a container and a vm configuration that share a deploy user with key-only ssh, systemd-networkd doing dhcp on every interface, flakes enabled, and sops-nix. instances take their hostname from the incus instance name through an lxc template, so one image works for every instance:

networking.hostName = "";

virtualisation.lxc.templates.hostname = {
  enable = true;
  target = "/etc/hostname";
  template = ./hostname.tpl; # {{ instance.name }}
  when = [ "create" "copy" ];
};

the same flake builds the incus images. an incus image is a metadata tarball plus a squashfs rootfs for containers or a qcow2 disk for vms:

mkImage = name: build: rootfs: pkgs.runCommand "${name}-incus-image" { } ''
  mkdir $out
  ln -s ${build.metadata}/tarball/*.tar.xz $out/metadata.tar.xz
  ln -s ${rootfs} $out/${baseNameOf rootfs}
'';

the images carry no secrets. each instance generates its own ssh host key on first boot, and that's the key sops-nix decrypts with.

ci builds both images and publishes them to a latest release. three things broke getting that working:

  • the vm disk is assembled inside a qemu vm, and nix refused to build it because ci jobs run in an unprivileged container with no /dev/kvm. overriding requiredSystemFeatures = [ ] lets qemu fall back to software emulation. it's slower but works.
  • my git server sits behind cloudflare, which rejects request bodies over 100 mb. the images are bigger than that, so the release job splits anything over 90 mib into numbered parts and publishes a SHA256SUMS for the whole files.
  • the release job deletes and recreates the latest tag, which would trigger another run, so the workflow only runs on branch pushes.
if [ "$(stat -c %s "$file")" -gt $((90 * 1024 * 1024)) ]; then
  split -b 90M -d -a 2 "$file" "assets/$name.part-"
else
  cp "$file" "assets/$name"
fi

adding a service goes like this: import the image once with incus image import, add a table entry with image = "nxt-container" and a nic on the provisioning network, and apply. the instance boots and gets an address, then i push the service's own flake over ssh:

nixos-rebuild switch \
  --flake .#container \
  --target-host deploy@<provisioning-ip> \
  --sudo

declarative windows images#

on the tofu side a windows vm is just an instance entry with a disk. what goes on that disk is the hard part. for malbox i needed windows images i could rebuild exactly, so they're nix derivations too. there are two variants, windows 11 23h2 enterprise and windows 10 ltsc 2021, both built from pinned evaluation isos.

stage 0: the install#

the base install uses nix-windows-in-qemu, which runs an unattended windows setup inside qemu in the nix sandbox and outputs a qcow2. it's a non-flake input, and i patch it in a runCommand instead of forking it. upstream only ships windows 11 systems, so the patch drops a windows 10 systems file next to theirs and seds it into the module list. every edit is followed by a grep so the build fails loudly if upstream changes and a patch stops applying:

src = pkgs.runCommand "nix-windows-in-qemu-with-win10" { } ''
  cp -r --no-preserve=mode ${nix-windows-in-qemu} $out
  cp ${./upstream-systems/windows-10-22h2.nix} \
    $out/mkWindowsImage/systems/windows-10-22h2.nix
  sed -i 's|"windows-11-23h2"|&\n        "windows-10-22h2"|' \
    $out/mkWindowsImage/entry.nix
  grep -q '"windows-10-22h2"' $out/mkWindowsImage/entry.nix \
    || { echo "patch failed — enum edit"; exit 1; }
  ...
'';

two of the other patches fix hangs. upstream wraps the install and compress steps in a timing helper that uses bash process substitution. the subshell it spawns wasn't reliably reaped inside the nix sandbox, which left the build stuck after windows setup had already finished. the fix was to strip that wrapper out.

getting here took a while. my first version was a vendored and heavily rewritten copy of the upstream builder. booting the windows iso under uefi shows a "press any key to boot from cd" prompt, and i went through an ocr watcher on the vnc output, spamming keys over the qemu monitor socket, and re-mastering the iso with the efisys_noprompt.bin boot image. after that, setup ran but didn't produce a working boot configuration (bcd), and i spent a few days splicing and patching bcd templates. the later stages looked like they worked, but they were returning in under two minutes because windows never actually booted. in the end i switched to upstream's single-pass setup, went back to consuming upstream as an input, and kept only the patches above.

layered stages#

everything after the install is done in layers. each layer is a nix derivation that takes the previous qcow2, boots it once, runs a script, and outputs a new qcow2. the trick that makes this work without a network or autologon: stage 0 registers a scheduled task that runs as SYSTEM on every boot, looks for a stage.cmd on any cd drive, and runs it. a stage derivation then only has to build an iso with stage.cmd and its payloads, and boot the vm with it attached:

mkBootStage {
  name = "features-${osVersion}";
  inherit baseImage;
  final = false;
  timeoutMinutes = 60;
  payloads = {
    "featuresInstall.ps1" = ./scripts/featuresInstall.ps1;
    "sxs" = netfx3Sxs;
  };
  scriptLines = ''
    powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0featuresInstall.ps1"
  '';
}

inside the derivation, mkBootStage creates a qcow2 overlay on top of the base image, boots it with kvm until the guest shuts itself down (or the timeout hits), then converts the overlay into a standalone compressed qcow2. it declares requiredSystemFeatures = [ "kvm" "big-parallel" ] so nix only schedules it on a builder with kvm.

there are three stages:

  1. install. vanilla windows from the iso, plus the staging task.
  2. features. installs .net framework 3.5 offline with dism, from the sxs files on the install iso. this has to happen before windows update is disabled, and it's offline because the build has no real network. about 6 to 8 minutes.
  3. core. the malbox-specific setup: windows update and defender off, debloat, the guest agent, the kernel driver and its test-signing certificate, and the ca for the sandbox's tls proxy. this is the final stage, so its stage.cmd also deletes the staging task and its runner script, which means a production boot of the image doesn't run anything from an attached cd. about 15 minutes.

because each stage is a separate derivation, changing a script in the last stage only rebuilds the last stage. the install is cached unless the iso, the install config, or the patched upstream builder changes.

layered image build
  1. stage 0 · installlong · unmeasuredcached
    unattended setup in qemu + the staging task
    /nix/store/977c1nh-stage-install
    ↓base qcow2 hash → input of features
  2. features~6–8 mincached
    .net 3.5 offline via dism
    /nix/store/yxgxrw9-stage-features
    ↓features qcow2 hash → input of core
  3. core · final~15 mincached
    lockdown, agent, driver, certs; deletes the staging task
    /nix/store/pdkbn2k-stage-core
    ↳ offline verify · dissect, sha-256 · same derivation
next build
nothing
from scratch
install + ~21–23 min
saved
everything
serial trace (com1) shows up here during a build
click an input to edit it. a stage's hash covers its inputs and the previous stage's output, so an edit invalidates that stage and everything after it. durations are the post's rough numbers; the log is illustrative.

debugging a vm you can't see#

when a stage fails, you can't easily tell what happened inside the guest. mkBootStage wraps every line of stage.cmd with trace markers that go to a log file on the guest disk and to COM1. one generated step looks roughly like this:

>> C:\malbox-stage-%NAME%.log echo [%TIME%] step=3 begin
>> \\.\COM1 echo [%TIME%] step=3 begin
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0featuresInstall.ps1"
set "stage_exit=%ERRORLEVEL%"
>> \\.\COM1 echo [%TIME%] step=3 end exit=%stage_exit%
if not "%stage_exit%"=="0" if not "%stage_exit%"=="3010" goto stageFailed

qemu maps the serial port to a file on the host, and the builder tails it, so i see each step as it runs instead of mounting the disk after a several-minute convert step. exit code 3010 is windows' "success, reboot required", so it counts as success. if the trace is empty after the timeout, the build fails with a separate error, because that almost always means windows didn't boot or the staging task didn't fire.

one bug that came from this: the staging task sometimes didn't run in later stages. schtasks /create /sc onstart sets the task's start boundary to the current time and won't let you backdate it. on the first boot of a later stage, the vm's clock could be behind the time recorded during install, so the task sat in "ready, waiting" and never fired. the fix was registering the task with Register-ScheduledTask and pinning the start boundary to a date in the past:

$trig = New-ScheduledTaskTrigger -AtStartup
$trig.Delay = "PT0S"
$trig.StartBoundary = "2020-01-01T00:00:00"

verifying the output#

the last check runs outside the vm. a small python script opens the finished qcow2 with the dissect libraries, finds the ntfs volume with a System32 directory, and reads each baked file straight out of the filesystem. it compares sizes and sha-256 hashes against the nix store sources, and fails if the image still has a backing file:

qcow = QCow2(Path(image_path))
if qcow.auto_backing_file:
    raise RuntimeError("finished image still has a backing file")

disk = Disk(qcow.open())
for partition in disk.partitions:
    ntfs = NTFS(partition.open())
    ntfs.mft.get(r"Windows\System32")
    ...

this catches the case where a stage exits cleanly but a copy inside the guest silently failed. the in-guest check alone can't prove that, since it runs in the same environment that might be broken.

the result is that nix build .#malbox-windows-core-win11-23h2 produces a finished windows image from pinned inputs, with no manual steps.

ci, the git server, and the cache#

the ci above runs on my own forgejo at git.neels.dev, which is another nixos flake: forgejo with postgres, its package and oci registry, and an attic binary cache, plus a separate nixos vm for the actions runner. the runner is a vm rather than a container so jobs get a full kernel. forgejo and attic only listen on loopback, and a cloudflare tunnel routes the public hostnames to them.

the runner has a nix post-build-hook that pushes every build output to attic, so dependencies shared between flakes get built once. it uses attic push because attic doesn't implement the upload protocol nix copy --to uses (it returns a 405).

problems here:

  • incus's lxc runtime adds a systemd drop-in that clears LoadCredential= on every unit. that broke secret delivery in the nixos forgejo module, and i had to point forgejo's *__FILE settings straight at the secret files. this same drop-in has broken other services too, and nixos vm tests don't catch it because they run full vms, not lxc containers.
  • forgejo-runner v13 dropped the register command and needs the runner uuid inline in its config, with no file-based option. the config is rendered with a placeholder and a wrapper substitutes the real uuid from sops at start.
  • nix builds on the runner were getting oom-killed. it now has zram swap plus a swapfile as a backstop.
  • ci containers are firewalled off from private address ranges, so workflow code can't reach the internal networks.

most flake repos share one small workflow: set up the attic cache, build the default package, and run nix flake check. the tofu repo's ci only runs tofu fmt -check, tofu init -backend=false, and tofu validate.

secrets#

every flake uses sops-nix with the instance's ssh host key as its age identity, so an instance has to exist before its secrets can be encrypted to it:

ssh-keyscan -t ed25519 <provisioning-ip> | ssh-to-age
# add the printed key to .sops.yaml, then:
sops updatekeys secrets.yaml

secrets get per-service owners and are read at runtime from /run/secrets, so they never end up in the nix store:

sops = {
  defaultSopsFile = ../../secrets.yaml;
  age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];

  secrets."grafana/admin_password" = {
    owner = config.users.users.grafana.name;
    mode = "0400";
  };
};

monitoring#

the monitoring flake replaced the old docker compose setup with the nixos prometheus, loki, and grafana modules. prometheus scrapes each node's incus metrics endpoint (the core.metrics_address set in the tofu server config) with a tls client cert from sops, plus node exporter, and keeps 30 days. both scrape jobs are generated from one node list.

the client cert only exists after activation, so promtool's file checks fail at build time, and the config uses checkConfig = "syntax-only". grafana comes with the node exporter and incus dashboards provisioned.

what's still manual#

  • the node list exists twice, once in tofu and once in the monitoring flake.
  • port forwards also live in two places: a rule in the vpn gateway's flake and an allow rule in the tofu acls.
  • incus images are imported by hand. tofu only references the alias.
  • tofu apply runs by hand against local state. there's no remote backend, and ci doesn't plan.
  • every new instance needs the ssh-to-age and sops updatekeys step before its first deploy.
  • a few older instances still come from hand-made golden images instead of the template.

possible upgrades#

  • faster networking. 2.5 gbe would help the most. the micro and tiny cases don't have room for a normal pcie card, so on those it would be a usb adapter.
  • more ram in the optiplex 3090. 24 gib is low next to the other two.
  • an ssd instead of the 5400 rpm hdd. it's the slowest part of the cluster.
  • shared storage. with dir pools everything is node-local. something like ceph would allow real migration between nodes, but on three nodes with 1 gbe i don't think it's worth it yet.

questions or corrections? email me.