00 / Homelab as code

Spec sheet · single node

One node. Four environments. Zero click-ops.

I run my homelab like a small production platform. Proxmox, OpenTofu, Ansible, Docker Compose and SOPS, with Git as the source of truth. Every change goes through a PR, a plan and a human.

Read the decisions See the stack

Hypervisor
Proxmox VE 9 · single node
Source of truth
Git
Principle
Nothing destructive happens implicitly
Apply
Human, on a reviewed plan
Environments
4 platform / lab / prod / range
OpenTofu modules
5
Ansible roles
15
Compose stacks
10
Decision records
12
Merged PRs
~48
Automated applies
0 On purpose

01 / Stack

Each tool owns exactly one layer.

Five layers, five owners. Tools never fight over the same resource, and when something drifts I know which layer to look at and which tool puts it right.

Hardware is declared in OpenTofu. cloud-init does only what has to happen before anything can log in. Ansible owns the operating system and deploys the Docker Compose stacks. Secrets sit next to the code, encrypted with SOPS + age.

Why the host isn't in OpenTofu Managing bridges and users needs host-level privileges, and a token with those could reconfigure everything. Keeping Layer 0 as a reviewed script keeps the everyday automation token small.
Fig. 1: The stack, one tool per layer
  1. Layer 4: Applications

    Deploy and update application stacks

    Owned by Docker Compose Deployed by an Ansible role
  2. Layer 3: OS configuration

    Users, SSH, firewall, Docker, exporters, backups, NFS

    Owned by Ansible
  3. Layer 2: First boot

    Hostname, admin user and key, guest agent. Nothing else.

    Owned by cloud-init
  4. Layer 1: Virtual hardware

    VMs, LXCs, disks, NICs, images, pool membership

    Owned by OpenTofu + bpg/proxmox
  5. Layer 0: Host

    Install, storage, bridges, pools, roles, tokens

    Owned by Reviewed one-time scripts + runbooks Proxmox VE 9, single node
Fig. 2: Provisioning, from a Git entry to a running stack
  1. 01 tfvars entry A new guest is one entry in a reviewed file in Git L1
  2. 02 tofu plan Plan saved and encrypted L1
  3. 03 Human review I read the plan before anything changes Gate
  4. 04 Apply Wrapper script, saved plan only L1
  5. 05 Image + cloud-init Pinned, checksummed cloud image imported L2
  6. 06 VM boots Hostname, admin user and key, guest agent L2
  7. 07 Inventory generated Built from OpenTofu outputs, never by hand L1 → L3
  8. 08 Ansible site.yml base, ssh, hardening, docker, monitoring, backup L3
  9. 09 Compose stack Deployed by an Ansible role L4

Key point The Ansible inventory is generated from OpenTofu outputs, so the two tools can never disagree about which hosts exist.

02 / Environments

Four environments. Separate state, keys and inventory.

platform, lab, prod and range share one node and nothing else that matters. The roots are byte-identical apart from one tfvars file, and CI enforces it. That's why "tested in lab" actually means something.

Fig. 3: Environments, isolated by construction
Property platform VMID 1000s lab VMID 2000s prod VMID 3000s range VMID 4000s
Purpose Shared images and the management VM that holds the keysDisposable. Every change is rehearsed here first.Services the household relies onOffensive-security lab, intentionally vulnerable
Trust High Throwaway Trusted Hostile
Protection OnOffOnSealed
Own, per environment
  • OpenTofu root
  • State file
  • Pool-scoped API token
  • Ansible inventory
  • Secrets
  • OpenTofu root
  • State file
  • Pool-scoped API token
  • Ansible inventory
  • Secrets
  • OpenTofu root
  • State file
  • Pool-scoped API token
  • Ansible inventory
  • Secrets
  • OpenTofu root
  • State file
  • Pool-scoped API token
  • Ansible inventory
  • Secrets
  1. platform VMID 1000s

    Shared images and the management VM that holds the keys

    Trust
    High
    Protection
    On
  2. lab VMID 2000s

    Disposable. Every change is rehearsed here first.

    Trust
    Throwaway
    Protection
    Off
  3. prod VMID 3000s

    Services the household relies on

    Trust
    Trusted
    Protection
    On
  4. range VMID 4000s

    Offensive-security lab, intentionally vulnerable

    Trust
    Hostile
    Protection
    Sealed

Each has its own root, state, token, inventory and secrets.

Read the environment from the ID

Each environment has its own VMID band: 1000s, 2000s, 3000s, 4000s. A guest's number tells you where it belongs before you look anything up.

Why not workspaces?

tofu workspace select prod is one typo away from applying to the wrong environment. Separate directories give separate credentials, separate state, and a visible path in every command.

03 / Decisions

Twelve decisions, written down.

Every significant choice has an Architecture Decision Record: context, decision, why, and what it costs. Open any row for the reasoning, or the full record for more.

ADR-001 OpenTofu with the bpg/proxmox provider Declare virtual hardware in OpenTofu, using the most complete Proxmox provider.
Context
Every VM, LXC, disk, NIC and image on the node needs to be declared in Git, reviewed as a diff and reproducible from scratch.
Decision
Layer 1 (virtual hardware) is OpenTofu with the bpg/proxmox provider. Nothing else creates guests.
Why
bpg/proxmox is the most complete, actively maintained Proxmox provider. OpenTofu is open source and has native state encryption, which the local-state decision (ADR-004) depends on.
Trade-off
The provider is pre-1.0, so breaking changes are possible. Versions are pinned exactly and every upgrade is rehearsed in lab first.
Full record for ADR-001
ADR-002 A separate root per environment, not workspaces Four directories, four state files, four tokens. Applying to the wrong environment takes more than one typo.
Context
Four environments (platform, lab, prod, range) share one node and one toolchain.
Decision
Each environment has its own OpenTofu root, state file, pool-scoped API token, Ansible inventory and secrets. The roots are byte-identical apart from one tfvars file, and CI enforces that.
Why
tofu workspace select prod is one typo away from applying to the wrong environment. Separate directories give separate credentials, separate state, and a visible path in every command.
Trade-off
Four copies of the root have to stay identical. Doing that by hand would be risky, so an env-drift check in CI fails any PR that lets them diverge.
Full record for ADR-002
ADR-003 Cloud images and direct import, not golden templates Every rebuild starts from a pinned, checksummed image, with no hand-built template to drift.
Context
Every guest needs a base operating system, and rebuilds have to be repeatable.
Decision
Guests boot from upstream cloud images that are pinned, checksum-verified and imported directly by OpenTofu. There are no hand-built golden templates.
Why
A hand-built template is a snowflake. Nobody remembers exactly what went into it, and it drifts. A pinned, checksummed image is the same every time.
Trade-off · Revisit when
First boot is slower, because configuration happens after boot rather than being baked in. When first-boot time starts to matter. Packer images can replace the import step without changing the module interface.
Full record for ADR-003
ADR-004 Local encrypted state, no remote backend A disaster-recovery tool shouldn't depend on a service that has to be running first.
Context
OpenTofu state has to live somewhere. There is one operator and one node.
Decision
State stays local and is encrypted client-side by OpenTofu (PBKDF2 → AES-GCM). Saved plans are encrypted the same way. There's no remote backend.
Why
A remote backend is a service that has to be up before you can repair anything. That's a bad dependency for the tool you use to recover from failures.
Trade-off · Revisit when
No state locking and no shared access. That's fine with a single operator, and wrong as soon as there are two. When a second operator appears, or if CI ever applies.
Full record for ADR-004
ADR-005 cloud-init does the minimum, Ansible owns configuration Run-once tools get run-once jobs. Everything that can drift goes to something idempotent.
Context
Both cloud-init and Ansible can configure a guest. If both do, they fight over the same files.
Decision
cloud-init sets the hostname, creates the admin user with its key, and installs the guest agent. Nothing else. Ansible owns all OS configuration.
Why
cloud-init runs once and can't safely be re-applied. Ansible is idempotent, so drift is fixed by running it again.
Trade-off
A freshly booted guest isn't useful until Ansible has run against it.
Full record for ADR-005
ADR-006 Compose stacks deployed by Ansible; Portainer is read-mostly One deployment path, with diffs you can review and secrets kept out of Git.
Context
Containers can be deployed from a UI, from CI or from configuration management.
Decision
Docker Compose stacks are deployed by an Ansible role. Portainer is there for looking, not for changing things.
Why
Changes show up as reviewable diffs, secrets are templated in at deploy time rather than committed in plaintext, and there's exactly one way a stack gets deployed.
Trade-off
A quick fix in a UI would be faster in the moment, but it would also be invisible to Git and overwritten by the next deploy.
Full record for ADR-006
ADR-007 SOPS + age instead of Vault or Ansible Vault Secrets are versioned with the code, with no secrets server to keep running.
Context
Credentials and passwords have to reach OpenTofu, Ansible and Compose without ever being committed in plaintext.
Decision
Secrets are committed to Git encrypted with SOPS + age, with three recipients, including an offline recovery key.
Why
Secrets are versioned alongside the code that uses them, diffs show which key changed, and no secrets server needs to be running before I can deploy or recover.
Trade-off
Access is controlled by who holds a key, not by a policy engine, so there's no fine-grained audit log of who read what. Rejected HashiCorp Vault · Ansible Vault
Full record for ADR-007
ADR-008 Least-privilege, pool-scoped API tokens The automation token can manage guests in one pool, and nothing else.
Context
Automation needs an API token. A token that can change the host can change everything.
Decision
Each environment's token is bound to a custom role, scoped to that environment's pool, with no Sys.Modify, Permissions.Modify or User.Modify.
Why
A leaked lab token can't touch prod, and no automation token can reconfigure the host, create users or grant itself more access.
Trade-off
Some jobs can't be done by the token at all. Host-level work stays in reviewed Layer 0 scripts, and some hypervisor features (see ADR-011) had to be designed around.
Full record for ADR-008
ADR-009 Humans apply; CI only validates and plans "Never auto-apply" is built into the structure, so nobody has to remember it.
Context
Pipelines that apply on merge are convenient, and they also turn a bad merge into a bad change in production.
Decision
CI validates every PR and produces plans on a self-hosted runner behind GitHub Environment approvals. Applying is always a human running a wrapper script on a saved, reviewed plan.
Why
CI has no credentials or code path that can apply, so the rule can't be broken by accident.
Trade-off · Revisit when
Changes are slower, and nothing ships while I'm away. Together with ADR-004, if a second operator or CI apply ever appears.
Full record for ADR-009
ADR-010 Two backup layers Whole-guest images for fast restores, plus file-level history that survives a corrupted image.
Context
Restoring a whole machine and recovering one file are different problems with different time pressure.
Decision
Whole-guest vzdump backups for fast machine restores, plus restic for per-file, versioned, encrypted history. Both go to a NAS that holds backups only.
Why
vzdump gets a whole VM back quickly. restic keeps file history that survives a corrupted VM image, because it doesn't depend on that image.
Trade-off
Two systems to schedule, monitor and drill.
Full record for ADR-010
ADR-011 No hypervisor tags on guests Proxmox checks tag permissions without pool context, so I identify environments by pool instead.
Context
Tags looked like the obvious way to mark which environment a guest belongs to.
Decision
Guests carry no hypervisor tags. The environment is identified by pool membership (and readable from the VMID band).
Why
Pool-scoped tokens were refused when setting tags. Reading the hypervisor's source showed why. Tag permissions are checked without pool context, so a pool-scoped token can never pass. The only fix would have been widening the token, which undoes ADR-008.
Trade-off
The environment isn't visible as a tag in the hypervisor UI. You read it from the pool or the ID band.
Full record for ADR-011
ADR-012 OPNsense on a reflashed end-of-life Sophos appliance The vendor firmware is EOL. OPNsense is maintained and has an API, so firewall rules can live in Git too.
Context
The edge firewall is a Sophos SG 210 whose vendor firmware is end-of-life and no longer gets security updates.
Decision
Reflash the appliance to OPNsense.
Why
OPNsense is free, updated often, and has a REST API and Ansible collections, so firewall rules can be managed in Git like everything else.
Trade-off
Running third-party firmware on vendor hardware is outside any vendor support. Rejected pfSense CE · Sophos Home Edition · Keeping UTM 9
Full record for ADR-012

04 / Safety

Nothing destructive happens implicitly.

A change has to pass nine checkpoints before it touches anything real. Most are enforced by structure: the safe path is the only path, so none of it depends on me remembering a rule.

  1. Branch, PR, CI

    Every change starts on a branch and goes through a pull request. CI validates; it never applies.

    • fmt
    • validate
    • module tests
    • tflint
    • Trivy
    • ansible-lint
    • yamllint
    • Compose policy
    • gitleaks
    • SOPS-encryption check
    • shellcheck
    • env-drift check
  2. Plan behind an approval

    Plans against the real hypervisor run on a self-hosted runner, gated by GitHub Environment approvals.

  3. A human applies

    Apply is always me, running a wrapper script on a saved plan that has already been reviewed.

  4. Destruction needs a typed confirmation

    Any plan that deletes or replaces something makes me type the environment name, and for prod the resource count too. The wrapper refuses destroy outright.

  5. Protection flag on prod

    Prod guests carry the hypervisor's protection flag, so a stray delete fails at the hypervisor too.

  6. Tokens scoped to one pool

    Each environment's API token is limited to that environment's pool and has no host, user or permission privileges. A leaked lab token can't touch prod.

  7. The edge tunnel is unreachable

    One critical guest, the edge tunnel, is in no pool, state file or inventory, and CI fails if anything references it. It's protected because the automation can't reach it, not because someone has to remember not to touch it.

  8. State and plans encrypted

    OpenTofu state and saved plans are encrypted client-side (PBKDF2 → AES-GCM).

  9. Rules for AI assistants

    AI coding assistants work under written hard rules. They may run read-only commands only, and nothing changes on live systems without my explicit approval of that specific action.

Illustrative · sanitised output
./apply.sh prod
saved plan: prod.tfplan (reviewed)

  ~ vm["vm-app-01"]   update in-place
      memory: 4096 → 8192
-/+ vm["vm-app-02"]   replace
      disk size forces replacement

Plan: 1 to add, 1 to change, 1 to destroy.

! This plan replaces 1 resource in prod.
  Type the environment name: prod
  Type the number of resources to destroy: 1
Confirmed. Applying saved plan…
Apply complete. 1 added, 1 changed, 1 destroyed.

./apply.sh prod destroy
✗ refused: this wrapper never runs destroy

Checkpoint 04 in practice: the wrapper only applies a saved plan, asks for the environment name before anything is replaced, and refuses destroy outright.

05 / Cyber range

A hostile network on the same host as prod.

A sealed offensive-security lab: two internal bridges with no physical uplink, one gateway VM as the only way in or out, and a policy that assumes everything inside is compromised.

Cyber range network Internet connects to OPNsense, which carries the range uplink VLAN (seal two). Below it, the gateway VM is the only range guest on the outside bridge; its nftables policy is seal one. Traffic from the gateway to the home LAN is dropped. The gateway routes two internal bridges with no physical uplink: an ops bridge with the red-team box and the blue-team SIEM, and an AD bridge with Windows Server 2025 domain controllers. Logs flow one way from the gateway to the SIEM. ops and AD can reach each other; that is the attack path. INTERNET OPNSENSE SEAL 2 Range VLAN blocked from private nets outside bridge GATEWAY VM SEAL 1 nftables: single enforcement Suricata IDS, passive HOME LAN private nets OPS · NO UPLINK AD · NO UPLINK logs, one-way RED TEAM Parrot Security BLUE TEAM Wazuh SIEM internet via NAT DOMAIN CTRLS Windows Server 2025 no internet (drop) ← attack path (allowed) allowed path one-way logs dropped independent seal
Fig. 4: The range seal. All traffic between segments is routed and filtered by the gateway.

Gateway policy matrix

Range policy: rows are the source segment, columns the destination
From InternetopsADHome LAN / privateGateway SSH
ops Allow NAT same segment Allow attack path Drop Drop
AD Drop by requirement Allow attack path same segment Drop Drop

Any range segment to the home LAN or any private range is dropped. The gateway is managed from outside only, so SSH to it from inside the range is dropped too.

Two independent seals The gateway's nftables policy is the single enforcement point inside the range. Its uplink sits in a dedicated VLAN that OPNsense also blocks from every private network. Getting out means defeating both.

Blue team

Suricata, then Wazuh, one way

Suricata runs as a passive IDS on the gateway with ET Open rules. Logs are pushed one way to a Wazuh SIEM. There's deliberately no Wazuh agent on the gateway: a manager can push active responses to its agents, so a compromised SIEM could rewrite the seal.

Red team

Parrot Security, reset by snapshot

Booted from a checksum-pinned ISO and rolled back to a clean snapshot between exercises.

Active Directory

Windows Server 2025, hands-off

Domain controllers are built with autounattend and a first-boot script, then managed by Ansible over OpenSSH. Server 2025 ships OpenSSH, which matters because the AD segment has no internet. Passwords come from SOPS.

Honest caveat The hypervisor itself is the trust boundary. This is software isolation, not an air gap. Isolation is verified against a written checklist before any target VM is attached.

06 / Network

From a flat LAN to segments, one console session at a time.

VLAN layout OPNsense routes five VLANs (MGMT, SERVICES, LAB, DMZ and the range uplink) over a single trunk to a Cisco SG200 managed switch. The management VM has already moved to the MGMT VLAN. OPNSENSE routes every VLAN EX-SOPHOS SG 210 one 802.1Q trunk CISCO SG200 · MANAGED SWITCH MGMT mgmt VM moved SERVICES LAB DMZ RANGE uplink only
Fig. 5: Target segmentation. Filled = migrated.
Routing
OPNsense routes MGMT, SERVICES, LAB, DMZ and the range uplink over one trunk to a Cisco SG200.
Migration
Phased and console-attended, so a mistake never cuts off my only way back in. The management VM is already on MGMT.
Never public
Hypervisor API, SSH, Portainer and Prometheus are never published to the internet.
Public path
One outbound tunnel (Pangolin). It needs no port forwards.
Host firewall
Rules live in code, with a dead-man timer: if a change locks me out and I can't confirm it, the old rules come back on their own.

07 / Storage & recovery

A backup you haven't restored is a hope, not a backup.

Guests live on ZFS, backups live somewhere else, and restores are rehearsed on a schedule: monthly and quarterly drills, recorded in a log.

Guest pool
3× 2 TB in ZFS RAIDZ1. The OS disk is kept separate.
Backup target
A NAS that holds backups only, because backups must not live on the machine they protect.
Layers
vzdump for whole guests, restic for versioned, encrypted files (ADR-010).
Consistency
Pre/post hooks: pg_dump, Nextcloud maintenance mode.
3-2-1
That's the target. The off-site copy is still on the roadmap, not done.
Pool layouts compared · 3× 2 TB, approximate
LayoutUsableSurvivesRandom IOPS
Stripe~6 TB0 disks~3× one disk
RAIDZ1 chosen~4 TB1 disk~1× one disk
3-way mirror~2 TB2 disksReads ~3×, writes ~1×
Recovery objectives
ScenarioRPORTO
One file or app config ≤ 24 h Minutes
One VM broken ≤ 24 h 15–30 min
Rebuild VM from code + restic ≤ 24 h 30–60 min
Management VM lost 0 (Git) / ≤ 24 h (state) 1 h
Host dead ≤ 24 h Half a day

08 / Hardening

The baseline every guest gets.

SSH
Key-only. Modern key exchange, including post-quantum hybrid ML-KEM.
Firewall
UFW, default deny.
Brute force
fail2ban.
Updates
Unattended security updates. Docker is excluded and upgraded on purpose.
Kernel
sysctl hardening.
Logs
journald capped, so logs can't fill the disk.
Supply chain
Pinned image tags, checksum-verified downloads, gitleaks in pre-commit and CI.
The gotcha Docker bypasses UFW. A published port skips the host firewall entirely. So every published port must bind an explicit address, and CI enforces it on every Compose file.

09 / Services

Grouped by blast radius.

Applications are grouped into VMs by blast radius and resource profile. Planned and rolling out.

Fig. 6: How many VMs?
  1. One VM per app Too much overhead on a single node.
  2. Grouped by blast radius A bad upgrade takes down one group, not everything.
  3. One VM for everything One bad upgrade would take it all down.
DNS
Pi-hole
Monitoring
Prometheus, Grafana, Alertmanager, Uptime Kuma
LAN TLS
Caddy
Security
CrowdSec
Management
Portainer (read-mostly)
Automation
n8n
Files
Nextcloud
Media
Jellyfin, *arr
Games
Minecraft
Docker in VMs, not LXCs Nested Docker in LXC breaks on hypervisor upgrades and shares the host kernel. A VM costs a little more and keeps containers off the host kernel.

10 / Lessons

Things that broke, and what I changed.

  1. #01 Access control

    Tag permissions ignore pools

    Symptom
    Pool-scoped tokens were refused when OpenTofu set tags on guests.
    Cause
    Proxmox checks tag permissions without pool context, so a pool-scoped grant can never satisfy the check.
    Fix
    Redesigned around pools and dropped tags (ADR-011), instead of widening the token.
  2. #02 Backups

    vzdump, unprivileged LXCs and NFS

    Symptom
    Backups of unprivileged containers to the NFS share failed.
    Cause
    UID mapping. The temporary directory vzdump writes to was on the share, where the mapped IDs had no rights.
    Fix
    Moved vzdump's tmpdir off the share.
  3. #03 Idempotency

    The second run wasn't changed=0

    Symptom
    On a fresh VM, the second Ansible run still reported changes.
    Cause
    Docker's first start reloads network sysctls, undoing what the hardening role had set.
    Fix
    Found it, documented it, and put the fix on the backlog. An honest changed=1 is better than a hidden one.
  4. #04 Range

    Zeek deferred

    Symptom
    Zeek isn't packaged for Debian 13.
    Cause
    Getting it would have meant adding a third-party package repository to the gateway, the most security-critical machine in the range.
    Fix
    Deferred Zeek. Suricata covers detection for now. A smaller attack surface on the seal mattered more.
  5. #05 Range

    No SIEM agent on the gateway

    Symptom
    The obvious design put a Wazuh agent on the gateway.
    Cause
    A Wazuh manager can push active responses to its agents. A compromised SIEM could then rewrite the gateway's firewall, which is the seal itself.
    Fix
    Logs are pushed one way from the gateway to the SIEM. Think about what your security tooling can do, not only what it can see.
  6. #06 Network

    DHCP pool overlapped static addresses

    Symptom
    A duplicate-IP incident on the LAN.
    Cause
    The router's DHCP pool overlapped addresses that had been assigned statically.
    Fix
    Fixed the addressing plan.

11 / Status

What's live, and what isn't yet.

Live 8

  • IaC foundation
  • Four isolated environments
  • Least-privilege API access
  • Management VM running all automation
  • ZFS RAIDZ1 guest pool
  • Backups to NAS
  • Host firewall as code
  • End-to-end test: VM → Ansible → Compose

In progress 3

  • VLAN migration
  • Cyber range build-out
  • Services rollout

Planned 7

  • Off-site backups
  • Proxmox Backup Server
  • Packer images
  • SSO (Authentik / Pocket ID)
  • Renovate
  • Molecule tests
  • ACME certificates