From dac1a980292500c009c765d779dd0bc7afa22657 Mon Sep 17 00:00:00 2001 From: kasun Date: Sat, 3 Oct 2026 00:17:14 +0200 Subject: [PATCH 1/9] chore: add shared Claude Code permissions and live-infra guard hook Live-infrastructure commands were pre-approved in a local allowlist. Deploys, cluster mutations and SSH now always prompt, and a PreToolUse hook catches the same commands when they are wrapped. --- .claude/hooks/guard-live-infra.sh | 41 +++++++++++++++++++ .claude/settings.json | 68 +++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100755 .claude/hooks/guard-live-infra.sh create mode 100644 .claude/settings.json diff --git a/.claude/hooks/guard-live-infra.sh b/.claude/hooks/guard-live-infra.sh new file mode 100755 index 0000000..471a17e --- /dev/null +++ b/.claude/hooks/guard-live-infra.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# PreToolUse hook for Bash: forces a permission prompt before any command that +# changes live infrastructure. The ask rules in .claude/settings.json match the +# command text as Claude usually writes it; this catches the same commands when +# they are wrapped (sh -c '...', env VAR=x ..., absolute paths). +set -euo pipefail + +input=$(cat) +cmd=$(jq -r '.tool_input.command // empty' <<<"$input") +cwd=$(jq -r '.cwd // empty' <<<"$input") + +[ -z "$cmd" ] && exit 0 + +# A subcommand must follow whitespace, so flags like `preview --refresh` don't match. +# It may be followed by a closing quote or paren when the command is wrapped. +end="([[:space:]\"')]|\$)" +pulumi_re="pulumi[[:space:]]+([^|;&]*[[:space:]])?(up|destroy|refresh|import|state|cancel)$end" +kubectl_re="kubectl[[:space:]]+([^|;&]*[[:space:]])?(apply|delete|patch|edit|replace|create|drain|cordon|uncordon|taint|scale|rollout|exec|annotate|label|set|cp)$end" +ssh_re='(^|[^[:alnum:]_./-])(ssh|scp)[[:space:]]' + +what="" +if [[ $cmd =~ $pulumi_re ]]; then + what="pulumi ${BASH_REMATCH[2]}" +elif [[ $cmd =~ $kubectl_re ]]; then + what="kubectl ${BASH_REMATCH[2]}" +elif [[ $cmd =~ $ssh_re ]]; then + what="${BASH_REMATCH[2]} to a node" +fi + +[ -z "$what" ] && exit 0 + +stack=$(grep -oE '0[1-5]-[a-z0-9-]+' <<<"$cmd $cwd" | head -n 1 || true) +reason="Live infrastructure: '$what'${stack:+ in $stack}. Approve only if you want Claude to run this instead of running it yourself." + +jq -n --arg reason "$reason" '{ + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "ask", + permissionDecisionReason: $reason + } +}' diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..a0829a6 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,68 @@ +{ + "permissions": { + "defaultMode": "plan", + "disableAutoMode": "disable", + "allow": [ + "Bash(pulumi preview *)", + "Bash(pulumi stack ls *)", + "Bash(pulumi whoami *)", + "Bash(pulumi version *)", + "Bash(npm ci)", + "Bash(npm install)", + "Bash(npm run typecheck *)", + "Bash(npx tsc *)", + "Bash(kubectl get *)", + "Bash(kubectl describe *)", + "Bash(kubectl logs *)", + "Bash(git add *)", + "Bash(git commit *)", + "Bash(git switch *)", + "WebFetch(domain:www.pulumi.com)", + "WebFetch(domain:github.com)", + "WebFetch(domain:raw.githubusercontent.com)", + "WebFetch(domain:kube-vip.io)", + "WebFetch(domain:longhorn.io)", + "WebFetch(domain:registry.terraform.io)" + ], + "ask": [ + "Bash(pulumi up *)", + "Bash(pulumi destroy *)", + "Bash(pulumi refresh *)", + "Bash(pulumi import *)", + "Bash(pulumi state *)", + "Bash(pulumi config set *)", + "Bash(pulumi config rm *)", + "Bash(pulumi stack output *)", + "Bash(kubectl get secret*)", + "Bash(kubectl apply *)", + "Bash(kubectl delete *)", + "Bash(kubectl patch *)", + "Bash(kubectl drain *)", + "Bash(kubectl exec *)", + "Bash(ssh *)", + "Bash(scp *)", + "Bash(curl *)", + "Bash(git push *)" + ], + "deny": [ + "Bash(env)", + "Bash(printenv *)", + "Bash(pulumi stack export *)", + "Read(**/.env)", + "Edit(**/Pulumi.dev.yaml)" + ] + }, + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-live-infra.sh" + } + ] + } + ] + } +} From c08f9df9afac9d0b898d20c66221e20be3a20550 Mon Sep 17 00:00:00 2001 From: kasun Date: Sat, 3 Oct 2026 00:17:14 +0200 Subject: [PATCH 2/9] chore: add typecheck script to every stack Gives Claude and CI a pass/fail check that does not need the Pulumi backend. --- 01-proxmox-infra/package.json | 3 +++ 02-k8s-bootstrap/package.json | 3 +++ 03-k8s-infra/package.json | 3 +++ 04-k8s-apps/package.json | 3 +++ 05-monitoring/package.json | 3 +++ 5 files changed, 15 insertions(+) diff --git a/01-proxmox-infra/package.json b/01-proxmox-infra/package.json index 97f1ba3..9a3526e 100644 --- a/01-proxmox-infra/package.json +++ b/01-proxmox-infra/package.json @@ -1,6 +1,9 @@ { "name": "proxmox-infra", "main": "index.ts", + "scripts": { + "typecheck": "tsc --noEmit" + }, "devDependencies": { "@types/node": "^24", "typescript": "^6.0.0" diff --git a/02-k8s-bootstrap/package.json b/02-k8s-bootstrap/package.json index c6c8b91..66cd2c0 100644 --- a/02-k8s-bootstrap/package.json +++ b/02-k8s-bootstrap/package.json @@ -1,6 +1,9 @@ { "name": "k8s-bootstrap", "main": "index.ts", + "scripts": { + "typecheck": "tsc --noEmit" + }, "devDependencies": { "@types/node": "^24.0.0", "typescript": "^6.0.0" diff --git a/03-k8s-infra/package.json b/03-k8s-infra/package.json index da2afa8..f0ca1cd 100644 --- a/03-k8s-infra/package.json +++ b/03-k8s-infra/package.json @@ -1,6 +1,9 @@ { "name": "k8s-infra", "main": "index.ts", + "scripts": { + "typecheck": "tsc --noEmit" + }, "devDependencies": { "@types/node": "^18", "typescript": "^5.0.0" diff --git a/04-k8s-apps/package.json b/04-k8s-apps/package.json index 0a44dca..9f2e907 100644 --- a/04-k8s-apps/package.json +++ b/04-k8s-apps/package.json @@ -1,6 +1,9 @@ { "name": "k8s-apps", "main": "index.ts", + "scripts": { + "typecheck": "tsc --noEmit" + }, "devDependencies": { "@types/node": "^24.0.0", "typescript": "^6.0.0" diff --git a/05-monitoring/package.json b/05-monitoring/package.json index 599a026..97de575 100644 --- a/05-monitoring/package.json +++ b/05-monitoring/package.json @@ -1,6 +1,9 @@ { "name": "monitoring", "main": "index.ts", + "scripts": { + "typecheck": "tsc --noEmit" + }, "devDependencies": { "@types/node": "^24.0.0", "typescript": "^6.0.0" From 812d1ba1c587ce055d29da5e7bef87b16d5742e8 Mon Sep 17 00:00:00 2001 From: kasun Date: Sat, 3 Oct 2026 00:17:14 +0200 Subject: [PATCH 3/9] docs: move setup runbooks and the control-plane VIP decision into docs The pfSense and TrueNAS procedures are for people, so they no longer load as Claude context. The stack CLAUDE.md files keep only what the code cannot show. --- 01-proxmox-infra/CLAUDE.md | 2 -- 02-k8s-bootstrap/CLAUDE.md | 34 ++++--------------- 03-k8s-infra/CLAUDE.md | 11 +----- 04-k8s-apps/CLAUDE.md | 2 -- 05-monitoring/CLAUDE.md | 2 -- ...1-control-plane-vip-via-pfsense-haproxy.md | 30 ++++++++++++++++ docs/runbooks/pfsense-control-plane-vip.md | 12 +++++++ docs/runbooks/truenas-nfs.md | 10 ++++++ 8 files changed, 60 insertions(+), 43 deletions(-) create mode 100644 docs/decisions/0001-control-plane-vip-via-pfsense-haproxy.md create mode 100644 docs/runbooks/pfsense-control-plane-vip.md create mode 100644 docs/runbooks/truenas-nfs.md diff --git a/01-proxmox-infra/CLAUDE.md b/01-proxmox-infra/CLAUDE.md index 6d10843..af5dac0 100644 --- a/01-proxmox-infra/CLAUDE.md +++ b/01-proxmox-infra/CLAUDE.md @@ -1,7 +1,5 @@ # proxmox-infra -This file provides guidance to Claude Code when working in `01-proxmox-infra`. See the [repo-root CLAUDE.md](../CLAUDE.md) for shared conventions, deployment order, and CI/CD. - ## Project Overview Pulumi TypeScript project provisioning VMs and LXC containers in Proxmox using the `@muhlba91/pulumi-proxmoxve` provider, plus pfSense DHCPv4 static mappings via a locally-bundled `@pulumi/pfsense` SDK. diff --git a/02-k8s-bootstrap/CLAUDE.md b/02-k8s-bootstrap/CLAUDE.md index 847b454..70efe34 100644 --- a/02-k8s-bootstrap/CLAUDE.md +++ b/02-k8s-bootstrap/CLAUDE.md @@ -1,20 +1,12 @@ # k8s-bootstrap -This file provides guidance to Claude Code when working in `02-k8s-bootstrap`. See the [repo-root CLAUDE.md](../CLAUDE.md) for shared conventions, deployment order, and CI/CD. +Bootstraps a k3s cluster on the Proxmox VMs created by `proxmox-infra`. Starts VMs via the Proxmox REST API, then provisions k3s over SSH using `@pulumi/command` `remote.Command`. Exports the secret stack output `kubeconfig`. -Bootstraps a k3s cluster on the Proxmox VMs created by `proxmox-infra`. Starts VMs via the Proxmox REST API, then provisions k3s over SSH using `@pulumi/command` `remote.Command`. +## Decisions the code doesn't explain -## How it works - -1. Starts all VMs via `POST /api2/json/nodes/{node}/qemu/{vmid}/status/start` -2. Waits for port 22 to open on each VM (bash `/dev/tcp`), installs k3s on `k3s-master-1` with `--cluster-init --tls-san --tls-san ` -3. Waits for `https://:6443/healthz` to respond before anyone else joins, since every subsequent join uses the VIP, not `master1Ip`. The VIP itself is a pfSense IP Alias Virtual IP with HAProxy TCP-load-balancing 6443 across all three masters — set up manually, not managed by any Pulumi stack (see "pfSense one-time setup" below). This is deliberately *not* a second kube-vip/ARP-based VIP: `03-k8s-infra`'s existing kube-vip DaemonSet already handles Service/LoadBalancer VIPs (e.g. Traefik) separately, entirely inside the cluster, and API access is too critical to depend on the same ARP-failover mechanism -4. Joins `k3s-master-2` and `k3s-master-3` as embedded etcd nodes via `--server https://:6443` -5. Joins `k3s-worker-1`, `k3s-worker-2`, and `k3s-worker-3` as agent nodes via `K3S_URL=https://:6443` -6. Formats the workers' dedicated `scsi1` disk (ext4, if not already formatted) and mounts it at `/mnt/longhorn-extra` (via `/etc/fstab`) — this is the disk `03-k8s-infra` later registers as an extra Longhorn disk, to keep Longhorn off the root filesystem and avoid `DiskPressure` -7. Reads `/etc/rancher/k3s/k3s.yaml` from master-1 via SSH, patches the server URL to `controlPlaneVipAddress`, and exports it as the secret stack output `kubeconfig` - -VM IDs and the CI runner SSH private key are read automatically from the `proxmox-infra` stack output via StackReference — no manual setup needed for those. +- **Everything goes through `controlPlaneVipAddress` except master-1's own install.** master-1 is installed with `--cluster-init` and a `--tls-san` for both `master1Ip` and the VIP. The stack then waits for `https://:6443/healthz` before anyone joins, because master-2, master-3 and the workers all join via the VIP, and the exported `kubeconfig` points at it. +- **The VIP is pfSense + HAProxy, set up by hand, not kube-vip.** `03-k8s-infra`'s kube-vip DaemonSet only handles Service/LoadBalancer VIPs. Don't propose kube-vip `cp_enable` for API access: it was considered and rejected, see [the decision record](../docs/decisions/0001-control-plane-vip-via-pfsense-haproxy.md). The manual pfSense steps are in [the runbook](../docs/runbooks/pfsense-control-plane-vip.md). +- **Workers get a dedicated Longhorn disk.** The `scsi1` disk is formatted ext4 (if not already) and mounted at `/mnt/longhorn-extra` via `/etc/fstab`. `03-k8s-infra` later registers it as an extra Longhorn disk, which keeps Longhorn off the root filesystem and avoids `DiskPressure`. ## Required Pulumi config @@ -31,28 +23,16 @@ pulumi config set worker2Ip "192.168.1.x" pulumi config set worker3Ip "192.168.1.x" # Control-plane VIP — floating IP for API server access, fronted by pfSense -# + HAProxy (see "pfSense one-time setup" below). Must be a free address -# outside the router's DHCP pool. +# + HAProxy. Must be a free address outside the router's DHCP pool. pulumi config set --secret controlPlaneVipAddress "192.168.1.147" ``` -Proxmox credentials (`pve1Endpoint`, `pve1ApiToken`, `pve2Endpoint`, `pve2ApiToken`, `pve3Endpoint`, `pve3ApiToken`) are read automatically from `proxmox-infra` via StackReference — do **not** set them here. +VM IDs, the CI runner SSH private key, and Proxmox credentials (`pve1Endpoint`, `pve1ApiToken`, `pve2Endpoint`, `pve2ApiToken`, `pve3Endpoint`, `pve3ApiToken`) are read automatically from `proxmox-infra` via StackReference — do **not** set them here. ## Prerequisites `proxmox-infra` must be deployed first. On its first `pulumi up` it generates an ed25519 SSH keypair via `@pulumi/tls`, writes the public key into every VM's cloud-init, and exports the private key as a secret stack output. VMs must be re-provisioned (or have the public key manually added to `~/.ssh/authorized_keys`) before this stack can SSH in. -## pfSense one-time setup (before deploying) - -The `@pulumi/pfsense` provider used by `01-proxmox-infra` doesn't expose Virtual IP or HAProxy resources (only DHCP static mappings, DNS overrides, and firewall aliases), so this is manual, not Pulumi-managed: - -1. Confirm `controlPlaneVipAddress` falls outside the DHCP pool (Services → DHCP Server → Range). -2. Firewall → Virtual IPs → Add: Type = `IP Alias`, Interface = `LAN`, Address = `/32`. -3. System → Package Manager → install `haproxy` if not already installed. -4. Services → HAProxy → Backend: add a pool (e.g. `k3s-apiservers`), mode `TCP`, health check `TCP check` (or `ssl-hello-chk`), servers = `:6443`, `:6443`, `:6443`. -5. Services → HAProxy → Frontend: add a frontend listening on `:6443`, type `TCP` (not HTTP — this must stay an opaque passthrough so clients validate k3s's own TLS cert, not one terminated at pfSense), default backend = the pool from step 4. -6. Services → HAProxy → Settings: enable HAProxy, apply. - ## CI/CD Workflow: `../.gitea/workflows/02-deploy-k8s-bootstrap.yaml`. Secret: `K8S_BOOTSTRAP_PULUMI_DEV_YAML`. Deploy is manual (`workflow_dispatch`) — re-running this stack restarts the bootstrap sequence against live VMs. diff --git a/03-k8s-infra/CLAUDE.md b/03-k8s-infra/CLAUDE.md index 0c0235d..4a437d6 100644 --- a/03-k8s-infra/CLAUDE.md +++ b/03-k8s-infra/CLAUDE.md @@ -1,7 +1,5 @@ # k8s-infra -This file provides guidance to Claude Code when working in `03-k8s-infra`. See the [repo-root CLAUDE.md](../CLAUDE.md) for shared conventions, deployment order, and CI/CD. - Cluster-level infrastructure for the k3s homelab cluster, deployed via Helm and `@pulumi/kubernetes`. Reads `kubeconfig` from `k8s-bootstrap` via StackReference. ## Common Commands @@ -41,14 +39,7 @@ pulumi config set kubeVipInterface `kubeconfig` is read automatically via StackReference — do not set it here. -## TrueNAS one-time setup (before deploying) - -1. Create dataset `pool/k8s` -2. Add an NFS share for that dataset: - - ACL type: POSIX/generic Unix permissions (not SMB/NFSv4 ACLs) on TrueNAS SCALE - - Maproot User / Group: `root` / `root` - - Allowed Hosts/Networks: restrict to the k3s node IPs/CIDR -3. In Network → Allowed Networks, permit your LAN subnet (e.g. `192.168.1.0/24`) +The TrueNAS dataset and NFS share must exist before deploying; they are created by hand, see [the runbook](../docs/runbooks/truenas-nfs.md). ## CI/CD diff --git a/04-k8s-apps/CLAUDE.md b/04-k8s-apps/CLAUDE.md index f61881a..115a435 100644 --- a/04-k8s-apps/CLAUDE.md +++ b/04-k8s-apps/CLAUDE.md @@ -1,7 +1,5 @@ # k8s-apps -This file provides guidance to Claude Code when working in `04-k8s-apps`. See the [repo-root CLAUDE.md](../CLAUDE.md) for shared conventions, deployment order, and CI/CD. - Application workloads for the k3s homelab cluster. Reads `kubeconfig` from `k8s-bootstrap` via StackReference. ## Common Commands diff --git a/05-monitoring/CLAUDE.md b/05-monitoring/CLAUDE.md index 5a12ed6..97371d8 100644 --- a/05-monitoring/CLAUDE.md +++ b/05-monitoring/CLAUDE.md @@ -1,7 +1,5 @@ # monitoring -This file provides guidance to Claude Code when working in `05-monitoring`. See the [repo-root CLAUDE.md](../CLAUDE.md) for shared conventions, deployment order, and CI/CD. - Monitoring stack (Prometheus + Grafana) via the `kube-prometheus-stack` Helm chart. Reads `kubeconfig` from `k8s-bootstrap` and `domain` from `k8s-apps`, both via StackReference. ## Common Commands diff --git a/docs/decisions/0001-control-plane-vip-via-pfsense-haproxy.md b/docs/decisions/0001-control-plane-vip-via-pfsense-haproxy.md new file mode 100644 index 0000000..12794b2 --- /dev/null +++ b/docs/decisions/0001-control-plane-vip-via-pfsense-haproxy.md @@ -0,0 +1,30 @@ +# 0001: Control-plane VIP via pfSense + HAProxy, not kube-vip + +Status: accepted (September 2026) + +## Context + +The kubeconfig exported by `02-k8s-bootstrap` pointed at `master1Ip` only, and the other nodes joined through it. Losing master-1 therefore broke API access even though the cluster runs three embedded-etcd masters. + +The fix needs one address that reaches any healthy API server. kube-vip documents a control-plane mode (`cp_enable`) for exactly this on k3s, and kube-vip already runs in this cluster as the DaemonSet that announces the Traefik LoadBalancer VIP. + +## Decision + +The control-plane VIP is a pfSense IP Alias Virtual IP with HAProxy load-balancing TCP 6443 across the three masters, as an opaque passthrough. It is not a second kube-vip instance. + +In `02-k8s-bootstrap`: + +- master-1 is installed with a `--tls-san` for both `master1Ip` and `controlPlaneVipAddress`. +- master-2, master-3 and all workers join through the VIP. +- The exported `kubeconfig` points at the VIP. + +## Why not kube-vip control-plane mode + +When this was decided, the existing kube-vip VIP for Traefik had an unresolved ARP-failover problem: a drained node kept announcing the VIP because drain does not evict DaemonSet pods. Putting API access behind a second ARP-announced VIP would have made the most critical endpoint depend on the same unproven failure mode. A VIP held by the router, outside the cluster, fails independently of it. + +## Consequences + +- The pfSense side is manual. The `marshallford/pfsense` provider has no Virtual IP or HAProxy resources. Steps: [runbook](../runbooks/pfsense-control-plane-vip.md). +- pfSense becomes a dependency for API access. +- Existing masters need the extra TLS SAN before the VIP works for them; a fresh bootstrap gets it from the code. +- If API-server HA comes up again, kube-vip `cp_enable` was considered and rejected for the reason above. Revisit only if the ARP-failover behaviour is understood and fixed. diff --git a/docs/runbooks/pfsense-control-plane-vip.md b/docs/runbooks/pfsense-control-plane-vip.md new file mode 100644 index 0000000..ad2f9d7 --- /dev/null +++ b/docs/runbooks/pfsense-control-plane-vip.md @@ -0,0 +1,12 @@ +# pfSense: control-plane VIP and HAProxy (one-time setup) + +Do this once, before deploying `02-k8s-bootstrap`. It creates the address that `controlPlaneVipAddress` points at. + +The `@pulumi/pfsense` provider used by `01-proxmox-infra` doesn't expose Virtual IP or HAProxy resources (only DHCP static mappings, DNS overrides, and firewall aliases), so this is manual, not Pulumi-managed. For why the VIP lives on pfSense at all, see [the decision record](../decisions/0001-control-plane-vip-via-pfsense-haproxy.md). + +1. Confirm `controlPlaneVipAddress` falls outside the DHCP pool (Services → DHCP Server → Range). +2. Firewall → Virtual IPs → Add: Type = `IP Alias`, Interface = `LAN`, Address = `/32`. +3. System → Package Manager → install `haproxy` if not already installed. +4. Services → HAProxy → Backend: add a pool (e.g. `k3s-apiservers`), mode `TCP`, health check `TCP check` (or `ssl-hello-chk`), servers = `:6443`, `:6443`, `:6443`. +5. Services → HAProxy → Frontend: add a frontend listening on `:6443`, type `TCP` (not HTTP — this must stay an opaque passthrough so clients validate k3s's own TLS cert, not one terminated at pfSense), default backend = the pool from step 4. +6. Services → HAProxy → Settings: enable HAProxy, apply. diff --git a/docs/runbooks/truenas-nfs.md b/docs/runbooks/truenas-nfs.md new file mode 100644 index 0000000..bc40d09 --- /dev/null +++ b/docs/runbooks/truenas-nfs.md @@ -0,0 +1,10 @@ +# TrueNAS: NFS share for the `truenas-nfs` StorageClass (one-time setup) + +Do this once, before deploying `03-k8s-infra`. The share is what `truenasHost` and `truenasNfsPath` point at. + +1. Create dataset `pool/k8s` +2. Add an NFS share for that dataset: + - ACL type: POSIX/generic Unix permissions (not SMB/NFSv4 ACLs) on TrueNAS SCALE + - Maproot User / Group: `root` / `root` + - Allowed Hosts/Networks: restrict to the k3s node IPs/CIDR +3. In Network → Allowed Networks, permit your LAN subnet (e.g. `192.168.1.0/24`) From 9a884acc227d176deda69c9e1015628207d10173 Mon Sep 17 00:00:00 2001 From: kasun Date: Sat, 3 Oct 2026 00:17:14 +0200 Subject: [PATCH 4/9] chore: add stack-review and explain-diff skills --- .claude/skills/explain-diff/SKILL.md | 29 +++++++++++++++++++++ .claude/skills/stack-review/SKILL.md | 39 ++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 .claude/skills/explain-diff/SKILL.md create mode 100644 .claude/skills/stack-review/SKILL.md diff --git a/.claude/skills/explain-diff/SKILL.md b/.claude/skills/explain-diff/SKILL.md new file mode 100644 index 0000000..25c33db --- /dev/null +++ b/.claude/skills/explain-diff/SKILL.md @@ -0,0 +1,29 @@ +--- +name: explain-diff +description: Walk through the current uncommitted git diff hunk by hunk, explain what each change does to the Pulumi resources, then quiz the author before they commit. +argument-hint: [optional path or git ref range] +disable-model-invocation: true +--- + +Explain the changes in `git diff HEAD` (or in `$ARGUMENTS` if a path or ref range was given) to the person who is about to commit them. They want to understand the change well enough to defend it, not to be reassured. Make no edits. + +## Steps + +1. Get the diff. If it is empty, say so and stop. +2. For each hunk, in file order: + - **What changed**, in one or two sentences, with a `file:line` link. + - **Why this way**: the reason for the approach, and one alternative that was available and why it was not used. If the reason is not visible in the code or the conversation, say that instead of inventing one. + - **Effect on resources**: which Pulumi resources this would create, update in place, or replace. Call out any replace of a VM, a PVC, or a resource adopted with `import`. If you cannot tell without `pulumi preview`, say so. + - **What could break**, and how it would show up. +3. Link the official documentation for any provider argument or Kubernetes field the diff introduces. +4. State what you did not verify. + +## Then quiz + +Ask three questions, one at a time, and wait for each answer: + +1. A prediction: what will `pulumi preview` show for this change (creates, updates, replaces)? +2. A "why": pick the least obvious line in the diff and ask what it is for. +3. A failure: ask what happens to the running cluster if this change is applied and one specific thing goes wrong. + +After each answer, say what was right, correct what was not, and point to the line or the doc that settles it. Do not grade or praise. If an answer shows the change is misunderstood, recommend not committing yet and say what to read first. diff --git a/.claude/skills/stack-review/SKILL.md b/.claude/skills/stack-review/SKILL.md new file mode 100644 index 0000000..ce74f67 --- /dev/null +++ b/.claude/skills/stack-review/SKILL.md @@ -0,0 +1,39 @@ +--- +name: stack-review +description: Read-only review of one Pulumi stack in this repo against Pulumi best practices. Reports ranked findings with doc links and makes no edits. +argument-hint: +disable-model-invocation: true +--- + +Review the stack in `$ARGUMENTS`. If no stack was given, ask which one. Review one stack per run. + +This is a review for someone who wants to understand their own code better, and who will decide what to change. Do not edit any file, and do not run anything against the cluster or the Pulumi backend. + +## Steps + +1. Read the stack's `CLAUDE.md`, `index.ts`, `package.json`, `tsconfig.json` and `Pulumi.yaml`, plus its workflow in `.gitea/workflows/`. +2. Load the `pulumi:pulumi-best-practices` skill and check the code against it. +3. Run `npm run typecheck` in the stack directory and include the result. +4. Check each candidate finding against the code before reporting it. Drop anything you cannot point to a line for. + +## What to look for + +- Correctness: `Output` misuse, missing `dependsOn` or `parent`, resources that would be replaced by a rename, secrets that lose their secret marking. +- Changes that are dangerous to apply here: anything that forces a replace of a VM, a PVC, or a resource adopted with `import`. +- Repetition that hides differences (near-identical blocks that differ in one argument). +- Drift between the stack's `CLAUDE.md` and what the code does. +- Dependency versions that lag the other stacks. + +Skip style preferences and anything the compiler already enforces. + +## Report format + +Rank findings by consequence, most serious first, and stop at eight. For each: + +- **What**: one sentence, with a `file:line` link. +- **Why it matters here**: the concrete consequence in this homelab, not the general rule. +- **Source**: a link to the official Pulumi, Kubernetes or provider documentation that supports it. If you have no source, say it is your own judgement. +- **Confidence**: high, medium or low, and what would raise it. +- **Size of fix**: one line, a small refactor, or a change that touches live resources. + +End with the two findings you would start with and why. Do not offer to implement them. From 7c2a37abdbe31887853b2cbdec6b6b5d1dae178a Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 20 Nov 2026 20:06:11 +0100 Subject: [PATCH 5/9] docs: add live-infra rule and verification steps to CLAUDE.md The guard hook only sees shell commands, so file edits to live systems (like the local kubeconfig) need a written rule. --- CLAUDE.md | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index dbc8201..630bb05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # CLAUDE.md -This file provides guidance to Claude Code when working anywhere in this repository. Each stack directory (`01-proxmox-infra`, `02-k8s-bootstrap`, etc.) has its own `CLAUDE.md` with stack-specific commands and architecture — Claude Code loads both this file and the stack's file automatically when working inside a stack directory. +Repository-wide instructions. Each stack directory has its own `CLAUDE.md` with stack-specific commands and architecture. ## Project overview @@ -36,21 +36,37 @@ A stack's outputs must exist (i.e. it must have been deployed) before any downst - **Secrets**: read via `config.requireSecret()`, never via environment variables or hardcoded values. - **`Pulumi.dev.yaml`**: gitignored (contains the encryption salt) — never delete it or secrets become unrecoverable. Encrypted with `PULUMI_CONFIG_PASSPHRASE`. - **Backend**: self-hosted Postgres state backend, set via `PULUMI_BACKEND_URL`. -- Don't add a co-author when committing to git. + +## Git conventions + +Branch names, commit messages and PR titles follow @CONVENTIONS.md. Don't add a co-author when committing to git. + +## Live infrastructure + +- Don't change live systems (cluster, pfSense, Proxmox, VMs, my local kubeconfig) on your own initiative, even for small or reversible changes. Give me the exact steps and let me decide who runs them. +- Code edits in the repo are fine without asking. +- Never recreate VMs to apply a change. Write code for a clean fresh install, plus separate manual steps for the running cluster. + +## Verifying changes + +After editing a stack, run `npm run typecheck` in that stack's directory, then `pulumi preview`, and show the output of both. A passing typecheck only proves the code compiles; the preview is what shows which resources would be created, updated or replaced. ## Common commands (run from a stack directory) ```bash npm install +npm run typecheck pulumi preview -pulumi up --yes -pulumi destroy +pulumi up --yes # run by the user or CI +pulumi destroy # run by the user pulumi stack output pulumi config ``` Requires `PULUMI_BACKEND_URL` and `PULUMI_CONFIG_PASSPHRASE` in the environment (or `pulumi login`). +Start Claude Code sessions from the repository root: the permission rules and the live-infra hook in `.claude/settings.json` only load from there. + ## CI/CD (Gitea Actions) One workflow per stack: `.gitea/workflows/0N-deploy-.yaml`, scoped to changes under that stack's directory. From 098c1c93c2d0ec3c16560d17310d610845a04285 Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 20 Nov 2026 21:21:40 +0100 Subject: [PATCH 6/9] chore: add PR access, typecheck stop hook and commit-msg hook Rules in CLAUDE.md can be forgotten; hooks can't. Reads are now free, live changes still ask, and PRs go through the claude-bot account since gh doesn't work with Gitea. --- .claude/hooks/check-on-stop.sh | 37 ++++++++++++++++++++++ .claude/scripts/gitea.sh | 57 ++++++++++++++++++++++++++++++++++ .claude/settings.json | 34 ++++++++++++++++++-- .githooks/commit-msg | 38 +++++++++++++++++++++++ CLAUDE.md | 11 +++++++ CONVENTIONS.md | 2 +- 6 files changed, 175 insertions(+), 4 deletions(-) create mode 100755 .claude/hooks/check-on-stop.sh create mode 100755 .claude/scripts/gitea.sh create mode 100755 .githooks/commit-msg diff --git a/.claude/hooks/check-on-stop.sh b/.claude/hooks/check-on-stop.sh new file mode 100755 index 0000000..2d7f61f --- /dev/null +++ b/.claude/hooks/check-on-stop.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Stop hook: makes Claude fix TypeScript errors before it can finish a reply. +# +# Why: CLAUDE.md tells Claude to run `npm run typecheck` after editing a stack, +# but an instruction can be forgotten. A hook can't: Claude Code runs it itself. +# +# When: "Stop" is the Claude Code event that fires every time Claude finishes a +# reply. It has nothing to do with Gitea issues or tickets. +# +# What: for every stack (01-..05-) with uncommitted .ts changes, run +# `npm run typecheck`. If one fails, exit 2 sends the errors back to Claude and +# it has to keep working. If nothing changed, it does nothing. +# +# Not included: `pulumi preview`. It's slow and needs credentials, so it stays a +# manual step (see "Verifying changes" in CLAUDE.md). +# +# Idea taken from the deverenz repo (.claude/hooks/check-on-stop.sh). +input=$(cat) +# Set when Claude is already continuing because of this hook; stopping here +# prevents an endless loop if it can't fix the error. +[[ "$(jq -r '.stop_hook_active // false' <<<"$input")" == "true" ]] && exit 0 +cd "$CLAUDE_PROJECT_DIR" || exit 0 + +# -uall lists files inside new folders, not just the folder. +stacks=$(git status --porcelain -uall | grep -oE '0[1-5]-[a-z0-9-]+/.*\.ts$' | cut -d/ -f1 | sort -u) + +failed=0 +for stack in $stacks; do + [[ -f "$stack/package.json" && -d "$stack/node_modules" ]] || continue + if ! out=$(npm run --silent --prefix "$stack" typecheck 2>&1); then + echo "typecheck failed in $stack, fix before finishing:" >&2 + tail -n 30 <<<"$out" >&2 + failed=1 + fi +done +[[ $failed -eq 1 ]] && exit 2 +exit 0 diff --git a/.claude/scripts/gitea.sh b/.claude/scripts/gitea.sh new file mode 100755 index 0000000..efa6b74 --- /dev/null +++ b/.claude/scripts/gitea.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Gitea API helper so Claude Code can work with pull requests. +# +# Why: the remote is a self-hosted Gitea, so the GitHub CLI `gh` doesn't work. +# This script calls the Gitea API instead, as the claude-bot account, so PRs +# show up as the bot's work and it only has the rights you gave it. +# +# Scope: used for PRs only (list, open, check CI status, merge after your OK). +# Technically it can call any endpoint; CLAUDE.md limits its use to PRs. +# In .claude/settings.json, GET runs without a prompt; POST, PATCH, PUT and +# DELETE (anything that changes something) always ask first. +# +# Usage: gitea.sh METHOD PATH [BODY] +# METHOD GET | POST | PATCH | PUT | DELETE +# PATH path below /api/v1, e.g. /repos/kasun/homelab-infrastructure-as-code/pulls?state=open +# BODY JSON string, or @file to send a file +# +# Config (outside the repo, never committed): +# ${XDG_CONFIG_HOME:-~/.config}/homelab-agent/url e.g. http://192.168.1.208:3000 +# ${XDG_CONFIG_HOME:-~/.config}/homelab-agent/token chmod 600 +# Token: Site Administration → Identity & Access → User Accounts → claude-bot → generate +# (write:repository, write:issue). claude-bot is a collaborator with Write on the repo. +# +# Adapted from the deverenz repo (.claude/scripts/gitea.sh). +set -euo pipefail + +method=${1:?usage: gitea.sh METHOD PATH [BODY]} +path=${2:?usage: gitea.sh METHOD PATH [BODY]} +body=${3:-} + +case "$method" in + GET | POST | PATCH | PUT | DELETE) ;; + *) echo "unsupported method: $method" >&2; exit 2 ;; +esac + +config=${XDG_CONFIG_HOME:-$HOME/.config}/homelab-agent +for f in url token; do + [[ -s "$config/$f" ]] || { echo "missing $config/$f" >&2; exit 2; } +done +url=$(<"$config/url") +token=$(<"$config/token") + +args=(-sS --fail-with-body -X "$method" -H "Accept: application/json") +# The token header is read from stdin so it never shows up in the process list. +args+=(-H @-) +if [[ -n "$body" ]]; then + [[ "$body" == "@-" ]] && { echo "BODY from stdin is not supported, use @file" >&2; exit 2; } + args+=(-H "Content-Type: application/json" --data-binary "$body") +fi + +out=$(curl "${args[@]}" "${url%/}/api/v1${path}" <<<"Authorization: token $token") \ + || { echo "$out" >&2; exit 1; } +if command -v jq >/dev/null && [[ -n "$out" ]]; then + jq . <<<"$out" 2>/dev/null || echo "$out" +else + echo "$out" +fi diff --git a/.claude/settings.json b/.claude/settings.json index a0829a6..466058f 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -7,6 +7,10 @@ "Bash(pulumi stack ls *)", "Bash(pulumi whoami *)", "Bash(pulumi version *)", + "Bash(pulumi stack output *)", + "Bash(pulumi stack history *)", + "Bash(pulumi config)", + "Bash(pulumi config get *)", "Bash(npm ci)", "Bash(npm install)", "Bash(npm run typecheck *)", @@ -14,9 +18,12 @@ "Bash(kubectl get *)", "Bash(kubectl describe *)", "Bash(kubectl logs *)", + "Bash(kubectl top *)", + "Bash(kubectl config get-contexts *)", "Bash(git add *)", "Bash(git commit *)", "Bash(git switch *)", + "Bash(.claude/scripts/gitea.sh GET *)", "WebFetch(domain:www.pulumi.com)", "WebFetch(domain:github.com)", "WebFetch(domain:raw.githubusercontent.com)", @@ -32,7 +39,6 @@ "Bash(pulumi state *)", "Bash(pulumi config set *)", "Bash(pulumi config rm *)", - "Bash(pulumi stack output *)", "Bash(kubectl get secret*)", "Bash(kubectl apply *)", "Bash(kubectl delete *)", @@ -42,16 +48,27 @@ "Bash(ssh *)", "Bash(scp *)", "Bash(curl *)", - "Bash(git push *)" + "Bash(git push *)", + "Bash(.claude/scripts/gitea.sh POST *)", + "Bash(.claude/scripts/gitea.sh PATCH *)", + "Bash(.claude/scripts/gitea.sh PUT *)", + "Bash(.claude/scripts/gitea.sh DELETE *)" ], "deny": [ "Bash(env)", "Bash(printenv *)", "Bash(pulumi stack export *)", + "Bash(pulumi *--show-secrets*)", "Read(**/.env)", - "Edit(**/Pulumi.dev.yaml)" + "Edit(**/Pulumi.dev.yaml)", + "Read(~/.config/homelab-agent/token)", + "Bash(*homelab-agent/token*)" ] }, + "attribution": { + "commit": "", + "pr": "" + }, "hooks": { "PreToolUse": [ { @@ -63,6 +80,17 @@ } ] } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-on-stop.sh", + "timeout": 300 + } + ] + } ] } } diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..3083d6a --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Git commit-msg hook: rejects commit messages that don't follow CONVENTIONS.md. +# +# Why: CONVENTIONS.md and CLAUDE.md only describe the format; nothing checked it, +# so older commits ("added node constants", "refactor code") drifted. Git runs +# this hook on every commit, from Claude or from you, and aborts the commit if +# the message is wrong. Your message is kept in .git/COMMIT_EDITMSG to fix up. +# +# Checks: +# - first line is `(): ` with a type and optional scope +# from CONVENTIONS.md, and no period at the end +# - no AI attribution lines (Co-Authored-By: Claude, "Generated with Claude") +# +# Activate once per clone: git config core.hooksPath .githooks +# Skip in an emergency: git commit --no-verify +# +# Idea taken from the deverenz repo (.githooks/commit-msg). +msg_file="$1" +first_line=$(grep -v '^#' "$msg_file" | head -n1) + +# Let git's own merge/revert/fixup messages through. +[[ "$first_line" =~ ^(Merge|Revert|fixup!|squash!) ]] && exit 0 + +types='feature|bug|enhancement|chore|docs' +scopes='proxmox-infra|k8s-bootstrap|k8s-infra|k8s-apps|monitoring|ci' +pattern="^($types)(\(($scopes)\))?: .*[^.]$" +if ! [[ "$first_line" =~ $pattern ]]; then + echo "commit-msg: '$first_line'" >&2 + echo " expected '(): ' with no trailing period (see CONVENTIONS.md)" >&2 + echo " types: ${types//|/ }" >&2 + echo " scopes: ${scopes//|/ } (optional)" >&2 + exit 1 +fi + +if grep -qiE '^(Co-Authored-By:.*(claude|anthropic)|.*Generated with \[?Claude)' "$msg_file"; then + echo "commit-msg: no AI attribution lines (see CLAUDE.md)" >&2 + exit 1 +fi diff --git a/CLAUDE.md b/CLAUDE.md index 630bb05..a02c0d1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,19 +41,30 @@ A stack's outputs must exist (i.e. it must have been deployed) before any downst Branch names, commit messages and PR titles follow @CONVENTIONS.md. Don't add a co-author when committing to git. +The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI status use `.claude/scripts/gitea.sh` (acts as `claude-bot`), e.g. `.claude/scripts/gitea.sh GET '/repos/kasun/homelab-infrastructure-as-code/pulls?state=open'`. Use it for PRs only, and ask before opening or merging one. + ## Live infrastructure - Don't change live systems (cluster, pfSense, Proxmox, VMs, my local kubeconfig) on your own initiative, even for small or reversible changes. Give me the exact steps and let me decide who runs them. - Code edits in the repo are fine without asking. - Never recreate VMs to apply a change. Write code for a clean fresh install, plus separate manual steps for the running cluster. +## Looking things up + +- Reading is free: files in this repo, git history, read-only kubectl and pulumi commands. +- Search targeted. If two or three searches don't find it, stop and ask me where it is instead of searching the whole filesystem. +- Stay inside this repo unless I point you somewhere else. + ## Verifying changes After editing a stack, run `npm run typecheck` in that stack's directory, then `pulumi preview`, and show the output of both. A passing typecheck only proves the code compiles; the preview is what shows which resources would be created, updated or replaced. +Don't silence a check to make it pass (`@ts-ignore`, `as any`, `git commit --no-verify`) without a stated reason and my OK. + ## Common commands (run from a stack directory) ```bash +git config core.hooksPath .githooks # once per clone, from the repo root: enforces CONVENTIONS.md npm install npm run typecheck pulumi preview diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 92944b5..58dd3ba 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -31,7 +31,7 @@ ``` - **Type** — same list as branch types above (`feature`, `bug`, `enhancement`, `chore`, `docs`) -- **Scope is optional** and, if used, should be one of the stack directories this repo is organized into — `proxmox-infra`, `k8s-bootstrap`, `k8s-infra`, `k8s-apps`, `monitoring` — or `ci` for `.gitea/workflows` changes: `fix(k8s-infra): ...` +- **Scope is optional** and, if used, should be one of the stack directories this repo is organized into — `proxmox-infra`, `k8s-bootstrap`, `k8s-infra`, `k8s-apps`, `monitoring` — or `ci` for `.gitea/workflows` changes: `bug(k8s-infra): ...` - **Summary** — imperative mood ("add", not "added" or "adds"); no period at the end - **Body** — only when the reasoning isn't obvious from the diff (a constraint, a workaround for a Proxmox/k3s quirk, a decision between StackReference outputs). Skip it for simple/self-explanatory changes. From 5cd50c31ff06cd95d69288668bb57b8d84279556 Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 20 Nov 2026 21:48:14 +0100 Subject: [PATCH 7/9] chore: require approval for commits and guard the kubeconfig Claude committed after a yes that was only meant for an edit, and once edited the local kubeconfig on its own. Commits now prompt, and kubeconfig/token edits are denied or prompt instead of relying on CLAUDE.md alone. --- .claude/settings.json | 8 +++++++- CLAUDE.md | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.claude/settings.json b/.claude/settings.json index 466058f..3e37d41 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -21,7 +21,6 @@ "Bash(kubectl top *)", "Bash(kubectl config get-contexts *)", "Bash(git add *)", - "Bash(git commit *)", "Bash(git switch *)", "Bash(.claude/scripts/gitea.sh GET *)", "WebFetch(domain:www.pulumi.com)", @@ -40,6 +39,10 @@ "Bash(pulumi config set *)", "Bash(pulumi config rm *)", "Bash(kubectl get secret*)", + "Bash(kubectl config set*)", + "Bash(kubectl config use-context *)", + "Bash(kubectl config delete*)", + "Bash(kubectl config rename-context *)", "Bash(kubectl apply *)", "Bash(kubectl delete *)", "Bash(kubectl patch *)", @@ -48,6 +51,7 @@ "Bash(ssh *)", "Bash(scp *)", "Bash(curl *)", + "Bash(git commit *)", "Bash(git push *)", "Bash(.claude/scripts/gitea.sh POST *)", "Bash(.claude/scripts/gitea.sh PATCH *)", @@ -61,6 +65,8 @@ "Bash(pulumi *--show-secrets*)", "Read(**/.env)", "Edit(**/Pulumi.dev.yaml)", + "Edit(~/.kube/**)", + "Edit(~/.config/homelab-agent/**)", "Read(~/.config/homelab-agent/token)", "Bash(*homelab-agent/token*)" ] diff --git a/CLAUDE.md b/CLAUDE.md index a02c0d1..ce61fb0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,6 +41,8 @@ A stack's outputs must exist (i.e. it must have been deployed) before any downst Branch names, commit messages and PR titles follow @CONVENTIONS.md. Don't add a co-author when committing to git. +Only commit when I explicitly say "commit" for that change. A yes to a question that also mentioned committing is not enough; when unsure, ask. + The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI status use `.claude/scripts/gitea.sh` (acts as `claude-bot`), e.g. `.claude/scripts/gitea.sh GET '/repos/kasun/homelab-infrastructure-as-code/pulls?state=open'`. Use it for PRs only, and ask before opening or merging one. ## Live infrastructure From 897813a91605d197b4b8e4ed67294187d05c592d Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 20 Nov 2026 21:48:20 +0100 Subject: [PATCH 8/9] docs: trim CLAUDE.md files to what the code doesn't show Following the Claude Code memory docs: drop architecture lists, generic commands and CI details Claude can read from the code, keep the reasons behind decisions, and fix the outdated provider and pfSense SDK statements. --- 01-proxmox-infra/CLAUDE.md | 28 ++-------------- 02-k8s-bootstrap/CLAUDE.md | 31 ++---------------- 03-k8s-infra/CLAUDE.md | 48 +++------------------------ 04-k8s-apps/CLAUDE.md | 30 ++--------------- 05-monitoring/CLAUDE.md | 31 +----------------- CLAUDE.md | 66 ++++++++------------------------------ 6 files changed, 26 insertions(+), 208 deletions(-) diff --git a/01-proxmox-infra/CLAUDE.md b/01-proxmox-infra/CLAUDE.md index af5dac0..57c88ae 100644 --- a/01-proxmox-infra/CLAUDE.md +++ b/01-proxmox-infra/CLAUDE.md @@ -1,28 +1,4 @@ # proxmox-infra -## Project Overview - -Pulumi TypeScript project provisioning VMs and LXC containers in Proxmox using the `@muhlba91/pulumi-proxmoxve` provider, plus pfSense DHCPv4 static mappings via a locally-bundled `@pulumi/pfsense` SDK. - -## Common Commands - -```bash -# Install deps and compile the bundled pfSense SDK -npm install - -# Sync Pulumi state with actual Proxmox state — run before `up` if VMs were -# changed manually in the Proxmox GUI -pulumi refresh --yes - -pulumi refresh --yes && pulumi up --yes -``` - -## Architecture - -- **Entry point**: `index.ts` — all resources declared here. -- **Providers**: two `@muhlba91/pulumi-proxmoxve` providers — `pveProvider` (node `pve`) and `pveBckpProvider` (node `pve-bckp`). Always pass the correct provider when adding resources. -- pfSense SDK lives in `sdks/pfsense/` (gitignored, regenerated by `npm install` / CI via `pulumi package add terraform-provider marshallford/pfsense 0.22.0`). - -## CI/CD - -Workflow: `../.gitea/workflows/01-deploy-proxmox-infra.yaml`. Secret: `PROXMOX_INFRA_PULUMI_DEV_YAML`. In addition to the shared pattern, this workflow regenerates the pfSense SDK (`pulumi package add terraform-provider marshallford/pfsense 0.22.0`) before preview/deploy. +- The pfSense SDK in `sdks/pfsense/` is gitignored and generated by `pulumi package add terraform-provider marshallford/pfsense 0.22.0` (CI runs it; locally, run it before `npm install` if the folder is missing). Don't edit it by hand. +- VMs are sometimes changed by hand in the Proxmox GUI. Before planning an `up`, suggest `pulumi refresh` so state matches reality. diff --git a/02-k8s-bootstrap/CLAUDE.md b/02-k8s-bootstrap/CLAUDE.md index 70efe34..0e9bafc 100644 --- a/02-k8s-bootstrap/CLAUDE.md +++ b/02-k8s-bootstrap/CLAUDE.md @@ -1,38 +1,13 @@ # k8s-bootstrap -Bootstraps a k3s cluster on the Proxmox VMs created by `proxmox-infra`. Starts VMs via the Proxmox REST API, then provisions k3s over SSH using `@pulumi/command` `remote.Command`. Exports the secret stack output `kubeconfig`. - ## Decisions the code doesn't explain - **Everything goes through `controlPlaneVipAddress` except master-1's own install.** master-1 is installed with `--cluster-init` and a `--tls-san` for both `master1Ip` and the VIP. The stack then waits for `https://:6443/healthz` before anyone joins, because master-2, master-3 and the workers all join via the VIP, and the exported `kubeconfig` points at it. - **The VIP is pfSense + HAProxy, set up by hand, not kube-vip.** `03-k8s-infra`'s kube-vip DaemonSet only handles Service/LoadBalancer VIPs. Don't propose kube-vip `cp_enable` for API access: it was considered and rejected, see [the decision record](../docs/decisions/0001-control-plane-vip-via-pfsense-haproxy.md). The manual pfSense steps are in [the runbook](../docs/runbooks/pfsense-control-plane-vip.md). - **Workers get a dedicated Longhorn disk.** The `scsi1` disk is formatted ext4 (if not already) and mounted at `/mnt/longhorn-extra` via `/etc/fstab`. `03-k8s-infra` later registers it as an extra Longhorn disk, which keeps Longhorn off the root filesystem and avoids `DiskPressure`. -## Required Pulumi config +## Running against live VMs -```bash -# Pre-shared k3s token — any strong random string -pulumi config set --secret k3sToken "$(openssl rand -hex 32)" +Re-running this stack restarts the bootstrap sequence against already-provisioned VMs. That's why it only deploys via manual dispatch. For changes to the running cluster, write the code for a fresh bootstrap and give separate manual steps. -# Node IPs — static DHCP leases from the router (not secrets) -pulumi config set master1Ip "192.168.1.x" -pulumi config set master2Ip "192.168.1.x" -pulumi config set master3Ip "192.168.1.x" -pulumi config set worker1Ip "192.168.1.x" -pulumi config set worker2Ip "192.168.1.x" -pulumi config set worker3Ip "192.168.1.x" - -# Control-plane VIP — floating IP for API server access, fronted by pfSense -# + HAProxy. Must be a free address outside the router's DHCP pool. -pulumi config set --secret controlPlaneVipAddress "192.168.1.147" -``` - -VM IDs, the CI runner SSH private key, and Proxmox credentials (`pve1Endpoint`, `pve1ApiToken`, `pve2Endpoint`, `pve2ApiToken`, `pve3Endpoint`, `pve3ApiToken`) are read automatically from `proxmox-infra` via StackReference — do **not** set them here. - -## Prerequisites - -`proxmox-infra` must be deployed first. On its first `pulumi up` it generates an ed25519 SSH keypair via `@pulumi/tls`, writes the public key into every VM's cloud-init, and exports the private key as a secret stack output. VMs must be re-provisioned (or have the public key manually added to `~/.ssh/authorized_keys`) before this stack can SSH in. - -## CI/CD - -Workflow: `../.gitea/workflows/02-deploy-k8s-bootstrap.yaml`. Secret: `K8S_BOOTSTRAP_PULUMI_DEV_YAML`. Deploy is manual (`workflow_dispatch`) — re-running this stack restarts the bootstrap sequence against live VMs. +The SSH key comes from `proxmox-infra`'s first `pulumi up`. VMs created before that need the public key added to `~/.ssh/authorized_keys` by hand. diff --git a/03-k8s-infra/CLAUDE.md b/03-k8s-infra/CLAUDE.md index 4a437d6..ef433ae 100644 --- a/03-k8s-infra/CLAUDE.md +++ b/03-k8s-infra/CLAUDE.md @@ -1,46 +1,6 @@ # k8s-infra -Cluster-level infrastructure for the k3s homelab cluster, deployed via Helm and `@pulumi/kubernetes`. Reads `kubeconfig` from `k8s-bootstrap` via StackReference. - -## Common Commands - -```bash -npm install -pulumi refresh --yes && pulumi up --yes -``` - -CI installs the `helm` CLI (`azure/setup-helm`) before running Pulumi. - -## Architecture - -| Component | What it does | -| --- | --- | -| NFS CSI Driver | `csi-driver-nfs` Helm chart — enables NFS-backed PVCs | -| `truenas-nfs` StorageClass | Backed by an NFS share on TrueNAS (`Retain` reclaim policy) | -| cert-manager | Certificate lifecycle management | -| `letsencrypt-prod` ClusterIssuer | DNS-01 via Cloudflare, issues Let's Encrypt TLS certs | -| Longhorn | Default block storage (`longhorn` StorageClass, 2 replicas) — used by app/monitoring PVCs. Worker nodes get an extra `longhorn-extra` disk at `/mnt/longhorn-extra` (a dedicated mount set up by `k8s-bootstrap`, patched onto the Longhorn `Node` CR here) so Longhorn data stays off the root disk and doesn't cause `DiskPressure`. `nodeDownPodDeletionPolicy` deletes both the StatefulSet and Deployment pod on node-down so stateful workloads reschedule automatically | -| kube-vip | DaemonSet that ARP-announces a virtual IP for LoadBalancer Services | -| kube-vip-cloud-provider | Allocates LoadBalancer IPs from a single-address pool (`kubeVipAddress`) — k3s's built-in ServiceLB is not used | -| `traefik` ServicePatch | Pins Traefik's LoadBalancer IP to `kubeVipAddress` | - -**Export**: `nfsStorageClass = "truenas-nfs"`. - -## Required Pulumi config - -```bash -pulumi config set --secret truenasHost -pulumi config set --secret truenasNfsPath /mnt/pool/k8s -pulumi config set --secret cloudflareApiToken -pulumi config set --secret letsencryptEmail -pulumi config set --secret kubeVipAddress -pulumi config set kubeVipInterface -``` - -`kubeconfig` is read automatically via StackReference — do not set it here. - -The TrueNAS dataset and NFS share must exist before deploying; they are created by hand, see [the runbook](../docs/runbooks/truenas-nfs.md). - -## CI/CD - -Workflow: `../.gitea/workflows/03-deploy-k8s-infra.yaml`. Secret: `K8S_INFRA_PULUMI_DEV_YAML`. +- **k3s's built-in ServiceLB is not used.** kube-vip ARP-announces LoadBalancer VIPs, and kube-vip-cloud-provider allocates them from a single-address pool (`kubeVipAddress`). Traefik's LoadBalancer IP is pinned to that address. +- **Longhorn stays off the root disk.** Worker nodes get an extra `longhorn-extra` disk at `/mnt/longhorn-extra` (mounted by `k8s-bootstrap`, registered on the Longhorn `Node` CR here) to avoid `DiskPressure`. `nodeDownPodDeletionPolicy` deletes StatefulSet and Deployment pods on node-down so stateful workloads reschedule. +- The TrueNAS dataset and NFS share are created by hand before deploying, see [the runbook](../docs/runbooks/truenas-nfs.md). +- Needs the `helm` CLI; CI installs it with `azure/setup-helm`. diff --git a/04-k8s-apps/CLAUDE.md b/04-k8s-apps/CLAUDE.md index 115a435..1e3964b 100644 --- a/04-k8s-apps/CLAUDE.md +++ b/04-k8s-apps/CLAUDE.md @@ -1,30 +1,4 @@ # k8s-apps -Application workloads for the k3s homelab cluster. Reads `kubeconfig` from `k8s-bootstrap` via StackReference. - -## Common Commands - -```bash -npm install -pulumi up --yes -``` - -## Architecture - -- **heimdall** — application dashboard (`lscr.io/linuxserver/heimdall`), namespace `heimdall` - - PVC `heimdall-config` (50Mi, `longhorn` StorageClass) - - Deployment + ClusterIP Service - - Ingress (`traefik` class, `cert-manager.io/cluster-issuer: letsencrypt-prod`) at `heimdall.` - - deployed with one replica because heimdall is not able to work with multiple replicas. Works with node failure detection and automatic rescheduling. - -**Export**: `domain` (secret) — consumed by `monitoring` via StackReference for its own ingress hostnames. - -## Required Pulumi config - -```bash -pulumi config set --secret domain -``` - -## CI/CD - -Workflow: `../.gitea/workflows/04-deploy-k8s-apps.yaml`. Secret: `K8S_APPS_PULUMI_DEV_YAML`. +- heimdall runs with one replica on purpose: it can't run with more than one. Node-failure recovery relies on rescheduling, not replicas. +- The `domain` output is consumed by `monitoring` for its ingress hostnames. Renaming or removing it breaks that stack. diff --git a/05-monitoring/CLAUDE.md b/05-monitoring/CLAUDE.md index 97371d8..4b46e67 100644 --- a/05-monitoring/CLAUDE.md +++ b/05-monitoring/CLAUDE.md @@ -1,32 +1,3 @@ # monitoring -Monitoring stack (Prometheus + Grafana) via the `kube-prometheus-stack` Helm chart. Reads `kubeconfig` from `k8s-bootstrap` and `domain` from `k8s-apps`, both via StackReference. - -## Common Commands - -```bash -npm install -pulumi up --yes -``` - -## Architecture - -- Namespace `monitoring` -- `kube-prometheus-stack` Helm release (chart v86.2.0) - - Grafana: ingress at `grafana.` (`traefik`, `letsencrypt-prod`), `longhorn` PVC (2Gi) - - Prometheus: `longhorn` PVC (20Gi) via `volumeClaimTemplate` - - Alertmanager disabled - -## Key Notes - -- The `monitoring` namespace and the Helm release both use the Pulumi `import` resource option (`monitoring`, `monitoring/kube-prometheus-stack`) — they were adopted from pre-existing cluster resources rather than created fresh. Be careful with renames or changes that would force a replace. - -## Required Pulumi config - -```bash -pulumi config set --secret grafanaAdminPassword -``` - -## CI/CD - -Workflow: `../.gitea/workflows/05-deploy-monitoring.yaml`. Secret: `MONITORING_PULUMI_DEV_YAML`. +- The `monitoring` namespace and the `kube-prometheus-stack` Helm release were adopted from existing cluster resources via the Pulumi `import` option. Be careful with renames or changes that would force a replace. diff --git a/CLAUDE.md b/CLAUDE.md index ce61fb0..d0e5844 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,20 +1,12 @@ # CLAUDE.md -Repository-wide instructions. Each stack directory has its own `CLAUDE.md` with stack-specific commands and architecture. + -## Project overview - -Pulumi (TypeScript) IaC for a Proxmox-based k3s homelab. Independent Pulumi projects ("stacks"), each with its own `Pulumi.yaml`/`package.json`, deployed in order and linked via `pulumi.StackReference`: - -| # | Directory | Pulumi stack | Purpose | -| --- | --- | --- | --- | -| 1 | `01-proxmox-infra` | `proxmox-infra` | Provisions k3s VMs + DHCP on Proxmox/pfSense | -| 2 | `02-k8s-bootstrap` | `k8s-bootstrap` | Installs k3s on the VMs over SSH | -| 3 | `03-k8s-infra` | `k8s-infra` | Cluster infra: storage, cert-manager, kube-vip | -| 4 | `04-k8s-apps` | `k8s-apps` | Application workloads (e.g. heimdall) | -| 5 | `05-monitoring` | `monitoring` | kube-prometheus-stack (Prometheus + Grafana) | - -All stacks use the Pulumi stack name `dev`. +Pulumi (TypeScript) IaC for a Proxmox-based k3s homelab. Each `0N-*` directory is an independent Pulumi project ("stack"), all using the Pulumi stack name `dev`. ## Deployment order & StackReferences @@ -23,23 +15,22 @@ proxmox-infra → k8s-bootstrap → k8s-infra ↘ k8s-apps → monitoring ``` -- `k8s-bootstrap` reads VM IDs, Proxmox credentials, and the SSH private key from `proxmox-infra` via StackReference. -- `k8s-infra`, `k8s-apps`, and `monitoring` all read `kubeconfig` from `k8s-bootstrap` via StackReference (`requireOutput("kubeconfig")`) — never set `kubeconfig` as Pulumi config in these stacks. -- `monitoring` additionally reads `domain` from `k8s-apps` via StackReference. +- `k8s-bootstrap` reads VM IDs, node IPs, Proxmox credentials, and the SSH private key from `proxmox-infra`. +- `k8s-infra`, `k8s-apps`, and `monitoring` read `kubeconfig` from `k8s-bootstrap` (`requireOutput("kubeconfig")`). Never set `kubeconfig` as Pulumi config in these stacks. +- `monitoring` additionally reads `domain` from `k8s-apps`. - StackReference format: `${pulumi.getOrganization()}//dev`. - -A stack's outputs must exist (i.e. it must have been deployed) before any downstream stack referencing it will succeed. +- A stack's outputs must exist (it must have been deployed) before a downstream stack referencing it will succeed. ## Shared conventions -- **TypeScript**: `strict: true`, `target: es2024`, `module`/`moduleResolution: nodenext`, `noImplicitReturns`, `noFallthroughCasesInSwitch` — functions need explicit return types where TS can't infer them. - **Secrets**: read via `config.requireSecret()`, never via environment variables or hardcoded values. -- **`Pulumi.dev.yaml`**: gitignored (contains the encryption salt) — never delete it or secrets become unrecoverable. Encrypted with `PULUMI_CONFIG_PASSPHRASE`. -- **Backend**: self-hosted Postgres state backend, set via `PULUMI_BACKEND_URL`. +- **`Pulumi.dev.yaml`**: gitignored (contains the encryption salt). Never delete it or secrets become unrecoverable. CI restores it from a base64 Gitea secret `_PULUMI_DEV_YAML`; after changing local config, remind me to update that secret. +- **Environment**: `PULUMI_BACKEND_URL` (self-hosted Postgres backend) and `PULUMI_CONFIG_PASSPHRASE` must be set. +- **CI**: PRs run `pulumi preview`. `03`–`05` deploy on push to `main`; `01`/`02` deploy only via manual dispatch. ## Git conventions -Branch names, commit messages and PR titles follow @CONVENTIONS.md. Don't add a co-author when committing to git. +Branch names, commit messages and PR titles follow @CONVENTIONS.md. The commit-msg hook needs `git config core.hooksPath .githooks` once per clone. Only commit when I explicitly say "commit" for that change. A yes to a question that also mentioned committing is not enough; when unsure, ask. @@ -62,32 +53,3 @@ The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI st After editing a stack, run `npm run typecheck` in that stack's directory, then `pulumi preview`, and show the output of both. A passing typecheck only proves the code compiles; the preview is what shows which resources would be created, updated or replaced. Don't silence a check to make it pass (`@ts-ignore`, `as any`, `git commit --no-verify`) without a stated reason and my OK. - -## Common commands (run from a stack directory) - -```bash -git config core.hooksPath .githooks # once per clone, from the repo root: enforces CONVENTIONS.md -npm install -npm run typecheck -pulumi preview -pulumi up --yes # run by the user or CI -pulumi destroy # run by the user -pulumi stack output -pulumi config -``` - -Requires `PULUMI_BACKEND_URL` and `PULUMI_CONFIG_PASSPHRASE` in the environment (or `pulumi login`). - -Start Claude Code sessions from the repository root: the permission rules and the live-infra hook in `.claude/settings.json` only load from there. - -## CI/CD (Gitea Actions) - -One workflow per stack: `.gitea/workflows/0N-deploy-.yaml`, scoped to changes under that stack's directory. - -- **Pull request → `main`**: `pulumi preview` only. -- `01`/`02` (VM provisioning / cluster bootstrap — riskier to automate): deploy only via manual `workflow_dispatch`. -- `03`–`05`: deploy on push to `main` *or* `workflow_dispatch` — `pulumi refresh` then `pulumi up`. -- Each workflow restores `Pulumi.dev.yaml` from a base64-encoded Gitea secret (`_PULUMI_DEV_YAML`). After changing local config, re-encode and update the secret: - ```bash - base64 -w 0 0N-/Pulumi.dev.yaml - ``` From 739e0ff1115a5cecaf941ff69f7db8c09bf3869c Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 20 Nov 2026 21:48:24 +0100 Subject: [PATCH 9/9] docs: correct cluster size, Longhorn replicas and config keys in README --- README.md | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a916c44..664cb7c 100644 --- a/README.md +++ b/README.md @@ -38,15 +38,16 @@ proxmox-infra → k8s-bootstrap → k8s-infra ### 1. proxmox-infra -Provisions a 5-node k3s cluster across two Proxmox hosts, each VM a clone of an Ubuntu Noble (24.04) cloud-image template: +Provisions a 6-node k3s cluster across three Proxmox hosts, each VM a clone of an Ubuntu Noble (24.04) cloud-image template: -| VM | Role | -| --- | --- | -| k3s-master-1 | master | -| k3s-master-2 | master | -| k3s-worker-1 | worker | -| k3s-master-3 | master | -| k3s-worker-2 | worker | +| VM | Role | Proxmox host | +| --- | --- | --- | +| k3s-master-1 | master | pve-b550 | +| k3s-worker-1 | worker | pve-b550 | +| k3s-master-2 | master | pve-esprimo | +| k3s-worker-3 | worker | pve-esprimo | +| k3s-master-3 | master | pve-optiplex | +| k3s-worker-2 | worker | pve-optiplex | It also generates an ED25519 SSH keypair (stored in Pulumi state, public key injected via cloud-init) and registers each VM's MAC address as a DHCPv4 static mapping in pfSense. @@ -54,7 +55,7 @@ It also generates an ED25519 SSH keypair (stored in Pulumi state, public key inj ### 2. k8s-bootstrap -Starts the VMs via the Proxmox API and installs k3s over SSH: `k3s-master-1` initializes the cluster (`--cluster-init`, embedded etcd), `k3s-master-2`/`k3s-master-3` join as additional etcd nodes, and the two workers join as agents. Exports the cluster's `kubeconfig` as a secret for downstream stacks. +Starts the VMs via the Proxmox API and installs k3s over SSH: `k3s-master-1` initializes the cluster (`--cluster-init`, embedded etcd), `k3s-master-2`/`k3s-master-3` join as additional etcd nodes, and the three workers join as agents. Exports the cluster's `kubeconfig` as a secret for downstream stacks. ### 3. k8s-infra @@ -63,7 +64,7 @@ Cluster-level infrastructure via Helm and `@pulumi/kubernetes`: | Component | What it does | | --- | --- | | NFS CSI Driver + `truenas-nfs` StorageClass | Dynamic NFS-backed PVCs from a TrueNAS share | -| Longhorn | Default block storage (`longhorn` StorageClass, 3 replicas) | +| Longhorn | Default block storage (`longhorn` StorageClass, 2 replicas) | | cert-manager + `letsencrypt-prod` ClusterIssuer | TLS certs via Let's Encrypt, DNS-01 through Cloudflare | | kube-vip + kube-vip-cloud-provider | Announces a virtual IP and allocates it to LoadBalancer Services (e.g. Traefik) | @@ -107,8 +108,8 @@ pulumi up --yes Stack-specific notes: 1. **proxmox-infra** — set Proxmox API tokens, pfSense credentials, VM credentials/SSH public key, and a static IP per node. -2. **k8s-bootstrap** — set `k3sToken` (e.g. `openssl rand -hex 32`) and a static IP per node. Proxmox credentials and the SSH key come automatically from `proxmox-infra`. -3. **k8s-infra** — before deploying, create an NFS dataset/share on TrueNAS (POSIX ACLs, `root`/`root` maproot, restricted to your k3s nodes). Set the TrueNAS, Cloudflare, and `kubeVipAddress`/`kubeVipInterface` config. +2. **k8s-bootstrap** — set `k3sToken` (e.g. `openssl rand -hex 32`) and `controlPlaneVipAddress` (secret; a free IP outside the DHCP pool, fronted by pfSense + HAProxy, see [the runbook](docs/runbooks/pfsense-control-plane-vip.md)). Node IPs, Proxmox credentials and the SSH key come automatically from `proxmox-infra`. +3. **k8s-infra** — before deploying, create an NFS dataset/share on TrueNAS (POSIX ACLs, `root`/`root` maproot, restricted to your k3s nodes). Set `truenasHost`, `truenasNfsPath`, `cloudflareApiToken`, `letsencryptEmail`, `kubeVipAddress` (all secrets) and `kubeVipInterface`. 4. **k8s-apps** — set `domain`, the base domain used for ingress hostnames. 5. **monitoring** — set `grafanaAdminPassword`.