Compare commits

...
Author SHA1 Message Date
kasun 3320f11e4b enhancement(k8s-bootstrap): verify Proxmox TLS and hide bootstrap tokens
Deploy k8s Bootstrap / Bootstrap k3s Cluster (pull_request) Skipped
Deploy k8s Bootstrap / Pulumi Preview (pull_request) Successful in 45s
Secret Scan / Betterleaks (pull_request) Successful in 6s
The Proxmox API token has admin rights but was sent with TLS verification off and, like the k3s token, was visible in process arguments. Verify each host against its public CA in certs/ and pass both tokens outside the command line.

Fetch the k3s installer from the pinned release tag so the script cannot change independently of the version. The new environment and stdin inputs are ignored so they do not re-run commands on live nodes.
2026-11-23 01:47:20 +01:00
claude-bot Bot 39dbfafe1c Merge pull request 'Bug: Stop kubeconfig address change from replacing k8s resources' (#57) from bug/stop-k8s-provider-replacement into main
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Apps / Pulumi Preview (push) Skipped
Deploy Monitoring / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Deploy (push) Successful in 53s
Deploy k8s Apps / Pulumi Deploy (push) Successful in 47s
Deploy Monitoring / Pulumi Deploy (push) Successful in 53s
Secret Scan / Betterleaks (push) Successful in 7s
2026-11-23 01:05:49 +01:00
kasun 356f5b7ad4 bug: stop kubeconfig address change from replacing k8s resources
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Apps / Pulumi Deploy (pull_request) Skipped
Deploy Monitoring / Pulumi Deploy (pull_request) Skipped
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 45s
Deploy k8s Apps / Pulumi Preview (pull_request) Successful in 39s
Deploy Monitoring / Pulumi Preview (pull_request) Successful in 43s
Secret Scan / Betterleaks (pull_request) Successful in 7s
k8s-bootstrap now exports the control-plane VIP while these stacks have master-1 stored in state. Pulumi treats the new server address as a different cluster and plans to replace the provider and every resource under it, including Longhorn and PVCs. Ignore kubeconfig changes on the provider so the stacks keep their stored connection.
2026-11-23 01:03:05 +01:00
claude-bot Bot 6647d55050 Merge pull request 'Enhancement: Harden k8s-bootstrap commands against silent failures' (#56) from enhancement/harden-k8s-bootstrap into main
Secret Scan / Betterleaks (push) Successful in 6s
2026-11-23 00:40:14 +01:00
kasun 13330ef3fb enhancement(k8s-bootstrap): harden bootstrap commands against silent failures
Deploy k8s Bootstrap / Bootstrap k3s Cluster (pull_request) Skipped
Deploy k8s Bootstrap / Pulumi Preview (pull_request) Successful in 39s
Secret Scan / Betterleaks (pull_request) Successful in 7s
A changed node IP or SSH key could re-run the unpinned k3s installer on live nodes, so ignore connection changes and pin k3s to the version the cluster runs.

Several steps reported success without reaching the desired state: a failed Longhorn mount fell through to the root disk, any HTTP error passed the VIP check, and VM start errors were swallowed. Each step now checks its outcome. mkfs only runs when blkid reports an empty disk, and package installs wait for cloud-init.
2026-11-23 00:38:52 +01:00
claude-bot Bot 855d1cce85 Merge pull request 'Chore: Add Betterleaks secret scanning to commits and CI' (#55) from chore/add-secret-scanning into main
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Apps / Pulumi Preview (push) Skipped
Deploy Monitoring / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Deploy (push) Successful in 46s
Deploy Monitoring / Pulumi Deploy (push) Successful in 42s
Deploy k8s Apps / Pulumi Deploy (push) Successful in 41s
Secret Scan / Betterleaks (push) Successful in 5s
2026-11-23 00:16:16 +01:00
kasun 9b388ff8e2 chore(ci): scan full Git history for secrets
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Apps / Pulumi Deploy (pull_request) Skipped
Deploy Monitoring / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 53s
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 42s
Deploy k8s Apps / Pulumi Preview (pull_request) Successful in 38s
Deploy Monitoring / Pulumi Preview (pull_request) Successful in 38s
Secret Scan / Betterleaks (pull_request) Successful in 6s
Covers commits that never ran the local hook, such as edits made in the
Gitea web editor.
2026-11-23 00:12:57 +01:00
kasun 0d5f49591a chore: block secrets in commits with a Betterleaks hook
The ignore file covers one old Gitea token in deleted .env.local, which
was confirmed revoked (API returned 401).
2026-11-23 00:12:55 +01:00
kasun 12400b4c83 chore(ci): deploy stacks only on their own workflow changes
Any file under .gitea/workflows triggered pulumi up on 03, 04 and 05, so
adding an unrelated workflow would deploy all three. PR previews still
watch the whole folder.
2026-11-23 00:12:53 +01:00
claude-bot Bot 05bec1a5ff Merge pull request 'Chore: Upgrade pfSense provider bridge to 1.5.1' (#54) from chore/upgrade-pfsense-provider-bridge into main
Deploy Proxmox Infra / Pulumi Deploy (push) Successful in 46s
Deploy Proxmox Infra / Pulumi Preview (push) Skipped
2026-11-22 20:02:15 +01:00
kasun f6f74d9977 chore(proxmox-infra): upgrade pfSense provider bridge to 1.5.1
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 50s
Pin the bridge and pfSense provider versions so local SDK generation
matches the deployed state. The regenerated SDK requires a newer
@pulumi/pulumi, which updates the lockfile.
2026-11-22 20:00:59 +01:00
claude-bot Bot f2b8704914 Merge pull request 'Docs: Update deploy triggers for automatic Proxmox deploys' (#53) from docs/update-deploy-triggers into main 2026-11-22 19:34:00 +01:00
kasun be09d7592f docs: update deploy triggers now that proxmox-infra deploys on merge 2026-11-22 19:31:45 +01:00
claude-bot Bot abac1bf532 Merge pull request 'Chore: Add read-only CI wait to the Gitea helper' (#52) from chore/add-ci-wait-command into main 2026-11-22 19:29:37 +01:00
kasun 282e1c5236 chore: add read-only CI wait to the Gitea helper
Polling CI with a shell loop triggered a permission prompt during /merge.
A dedicated WAIT command can be allowlisted on its own.
2026-11-22 19:27:04 +01:00
claude-bot Bot 339dcdd214 Merge pull request 'Enhancement: Deploy Proxmox infra automatically on merge' (#51) from enhancement/auto-deploy-proxmox-infra into main
Deploy Proxmox Infra / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Apps / Pulumi Preview (push) Skipped
Deploy Monitoring / Pulumi Preview (push) Skipped
Deploy Proxmox Infra / Pulumi Deploy (push) Successful in 1m46s
Deploy k8s Infra / Pulumi Deploy (push) Successful in 48s
Deploy Monitoring / Pulumi Deploy (push) Successful in 44s
Deploy k8s Apps / Pulumi Deploy (push) Successful in 38s
2026-11-22 19:21:35 +01:00
kasun 9b15ea5d33 enhancement(ci): deploy proxmox-infra on merge to main
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Apps / Pulumi Deploy (pull_request) Skipped
Deploy Monitoring / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 1m1s
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 54s
Deploy k8s Apps / Pulumi Preview (pull_request) Successful in 34s
Deploy Monitoring / Pulumi Preview (pull_request) Successful in 43s
Skip the refresh on automatic deploys. A refresh that finds a VM missing
drops it from state, and the following up would create a blank replacement.
2026-11-22 18:42:30 +01:00
kasun 344f748b84 enhancement(proxmox-infra): protect resources and stop update reboots
Prepare the stack for deploying on merge. Protect templates, DHCP mappings
and the Ansible container, and stop in-place updates from rebooting k3s VMs.
2026-11-22 18:42:30 +01:00
claude-bot Bot 84cf39e7d9 Merge pull request 'Chore: Add merge skill for the commit-to-merge workflow' (#50) from chore/add-merge-skill into main 2026-11-22 18:29:07 +01:00
kasun afc9fd36d7 chore: add merge skill for the commit-to-merge workflow 2026-11-22 18:26:42 +01:00
claude-bot Bot 3e6c8188da Merge pull request 'Chore: Allow common read-only commands in Claude settings' (#49) from chore/allow-readonly-commands into main 2026-11-22 18:26:28 +01:00
claude-bot Bot 4c3a2b4226 Merge pull request 'Feature: Add Ansible control node LXC' (#48) from feature/add-ansible-control-node into main 2026-11-22 18:26:16 +01:00
kasun c40fc0caac chore: allow common read-only commands in Claude settings 2026-11-22 18:18:43 +01:00
kasun 49fd2ba307 feature(proxmox-infra): add Ansible control node LXC
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 1m1s
Fix the container's MAC so its pfSense DHCP reservation exists before
first boot. Otherwise the first lease could come from the dynamic pool.
2026-11-22 18:08:02 +01:00
claude-bot Bot 85ce271fd6 Merge pull request 'Enhancement: Protect VM templates from deletion' (#47) from enhancement/protect-vm-templates into main 2026-11-22 03:26:42 +01:00
kasun 7548402542 enhancement(proxmox-infra): protect VM templates from deletion
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 1m7s
2026-11-22 03:25:16 +01:00
claude-bot Bot 9e0ce35712 Merge pull request 'Enhancement: Protect k3s VMs from accidental replacement' (#46) from enhancement/protect-k3s-vms into main 2026-11-22 03:10:09 +01:00
kasun c1e409780d enhancement(proxmox-infra): protect k3s VMs from replacement
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 1m0s
A stale state can make Pulumi plan new VMs for machines that already exist. Protection makes such an update fail instead of being applied.
2026-11-22 03:08:44 +01:00
claude-bot Bot 5a2d32ea84 Merge pull request 'Bug: Stop bootstrap from re-running k3s install on live nodes' (#45) from bug/stop-bootstrap-reruns into main 2026-11-22 02:59:35 +01:00
kasun e3fab0e151 bug(k8s-bootstrap): stop re-running install commands on live nodes
Deploy k8s Bootstrap / Bootstrap k3s Cluster (pull_request) Skipped
Deploy k8s Bootstrap / Pulumi Preview (pull_request) Successful in 40s
Bootstrap commands used VM IDs as triggers, so renumbering VMs would re-run the unpinned k3s installer on every node and append duplicate fstab entries. Treat them as run-once and re-run them explicitly after recreating a VM. Also start master-2 through pve-esprimo, where it now lives.
2026-11-22 02:58:30 +01:00
claude-bot Bot a1867b18c8 Merge pull request 'Bug: Stop permanent disk speed diffs on k3s VMs' (#43) from bug/ignore-disk-speed-diff into main 2026-11-22 02:27:45 +01:00
kasun 71b0f3ce7d bug(proxmox-infra): ignore permanent disk speed diff
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 1m2s
The Pulumi bridge applies the provider's internal default for the disk speed block, but Proxmox stores nothing when no limit is set, so every preview shows a change that can never settle. Ignore the field per disk because the wildcard form is reported not to work with this provider.
2026-11-22 02:25:59 +01:00
claude-bot Bot d0600b9153 Merge pull request 'Chore: Let Claude Code commit, push and open PRs without a prompt' (#40) from chore/allow-git-write-commands into main 2026-11-21 15:57:10 +01:00
kasun 7acf83e68d chore: keep the permission prompt for merging PRs 2026-11-21 15:56:49 +01:00
kasun 088cb5add1 chore: allow Claude Code to commit, push and open PRs without a prompt
CLAUDE.md already requires an explicit request before committing or opening a PR, so the extra permission prompt only repeated that approval.
2026-11-21 15:54:45 +01:00
kasun b04ab52fd2 Merge pull request 'Bug: Prevent Longhorn disks filling up after node outages' (#39) from bug/longhorn-storage-exhaustion into main
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Deploy (push) Successful in 1m4s
Reviewed-on: #39
2026-11-21 15:52:36 +01:00
kasun ff2b565677 bug(k8s-infra): prevent Longhorn disks filling up after node outages
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 51s
Orphaned replica data and a large snapshot left no room for a second Prometheus replica, so the volume faulted when its only replica failed. Clean up orphans and system snapshots, trim volumes daily, and lower the free-space reserve to 10% because longhorn-extra is a dedicated disk. Align the UI default with the StorageClass at 3 replicas so volumes keep two copies during a node reboot.
2026-11-21 15:49:07 +01:00
claude-bot Bot 4b22f4ad11 Feature: Expose the Longhorn UI at longhorn.<domain> behind basic auth
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Deploy (push) Successful in 48s
2026-11-21 02:41:43 +01:00
kasun 020b277a04 feature(k8s-infra): expose the Longhorn UI behind Traefik basic auth
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 47s
The Longhorn UI has no login of its own and can delete volumes, so it is only reachable through a Traefik basicAuth middleware. Credentials come from the new longhornUiUser/longhornUiPassword config secrets; the hostname uses the new domain config.
2026-11-21 02:26:44 +01:00
claude-bot Bot ba53cbc465 Merge pull request 'Bug: Fail heimdall over to another worker within ~2 minutes of node loss' (#37) from bug/heimdall-failover into main
Deploy k8s Apps / Pulumi Preview (push) Skipped
Deploy k8s Apps / Pulumi Deploy (push) Successful in 43s
2026-11-20 23:40:05 +01:00
kasun b4d27c6546 bug(k8s-apps): fail heimdall over within ~30s of node loss
Deploy k8s Apps / Pulumi Deploy (pull_request) Skipped
Deploy k8s Apps / Pulumi Preview (pull_request) Successful in 47s
Default 300s not-ready/unreachable tolerations kept the pod bound to a dead node for ~5 min. Lower both to 30s, and switch to Recreate so a single-replica RWO pod never waits on a Multi-Attach during rollouts. Verified by stopping worker-2: pod running on worker-3 ~2 min later.

The existing Deployment's defaulted rollingUpdate block was removed once with kubectl patch so the API server accepts Recreate.
2026-11-20 23:37:37 +01:00
claude-bot Bot 481ff9e7ac Merge pull request 'Chore: Overhaul Claude Code setup and join k3s nodes via the control-plane VIP' (#35) from chore/overhaul-claude-code-setup into main
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Apps / Pulumi Preview (push) Skipped
Deploy Monitoring / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Deploy (push) Successful in 49s
Deploy k8s Apps / Pulumi Deploy (push) Successful in 46s
Deploy Monitoring / Pulumi Deploy (push) Successful in 46s
2026-11-20 22:14:58 +01:00
claude-bot Bot 5865c38ea7 Merge pull request 'Bug: Pin cert-manager to the deployed chart version' (#36) from bug/pin-cert-manager into main
Deploy k8s Infra / Pulumi Preview (push) Skipped
Deploy k8s Infra / Pulumi Deploy (push) Successful in 47s
2026-11-20 22:06:11 +01:00
kasun 4f90febc89 bug(k8s-infra): pin cert-manager to the deployed chart version
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 42s
Without a version every pulumi up installed the newest chart, so any merge touching 03-k8s-infra silently upgraded cert-manager. Pinned to v1.21.1, the version running in the cluster; upgrades now happen on purpose.
2026-11-20 22:04:01 +01:00
kasun 739e0ff111 docs: correct cluster size, Longhorn replicas and config keys in README
Deploy Proxmox Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Bootstrap / Bootstrap k3s Cluster (pull_request) Skipped
Deploy k8s Infra / Pulumi Deploy (pull_request) Skipped
Deploy k8s Apps / Pulumi Deploy (pull_request) Skipped
Deploy Monitoring / Pulumi Deploy (pull_request) Skipped
Deploy Proxmox Infra / Pulumi Preview (pull_request) Successful in 2m15s
Deploy k8s Bootstrap / Pulumi Preview (pull_request) Successful in 37s
Deploy k8s Infra / Pulumi Preview (pull_request) Successful in 48s
Deploy k8s Apps / Pulumi Preview (pull_request) Successful in 39s
Deploy Monitoring / Pulumi Preview (pull_request) Successful in 39s
2026-11-20 21:48:24 +01:00
kasun 897813a916 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.
2026-11-20 21:48:20 +01:00
kasun 5cd50c31ff 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.
2026-11-20 21:48:14 +01:00
kasun 098c1c93c2 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.
2026-11-20 21:21:40 +01:00
kasun 7c2a37abdb 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.
2026-11-20 20:06:11 +01:00
kasun 9a884acc22 chore: add stack-review and explain-diff skills 2026-10-03 00:17:14 +02:00
kasun 812d1ba1c5 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.
2026-10-03 00:17:14 +02:00
kasun c08f9df9af chore: add typecheck script to every stack
Gives Claude and CI a pass/fail check that does not need the Pulumi backend.
2026-10-03 00:17:14 +02:00
kasun dac1a98029 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.
2026-10-03 00:17:14 +02:00
42 changed files with 1520 additions and 1975 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Old Gitea token in deleted .env.local. Confirmed revoked (API returned 401) on 2026-11-22.
8c69ec772ab5f0df73fa2614e5b8b22adb9bbd15:.env.local:gitea-access-token:2
+37
View File
@@ -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
+41
View File
@@ -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
}
}'
+84
View File
@@ -0,0 +1,84 @@
#!/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 and POST (e.g. opening a PR) run without a
# prompt. Merging a PR (POST .../merge), PATCH, PUT and DELETE 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
#
# Read-only CI wait: gitea.sh WAIT /repos/OWNER/REPO/commits/SHA/status
# Polls until checks finish. Exit 0: passed or no CI ran. 1: a check failed.
# 2: bad usage. 3: timed out after 15 minutes.
#
# 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:-}
if [[ "$method" == "WAIT" ]]; then
[[ "$path" =~ ^/repos/[^/]+/[^/]+/commits/[0-9a-f]{40}/status$ ]] \
|| { echo "WAIT only accepts /repos/OWNER/REPO/commits/SHA/status" >&2; exit 2; }
for ((i = 1; i <= 45; i++)); do
status=$("$0" GET "$path") || status='{}'
total=$(jq '.statuses // [] | length' <<<"$status")
running=$(jq '[.statuses // [] | .[] | select(.status == "pending" or .status == "running")] | length' <<<"$status")
# Give checks time to register. Path-filtered workflows may never start any.
if (( total == 0 && i >= 7 )); then
echo "no CI ran"
exit 0
fi
if (( total > 0 && running == 0 && i >= 4 )); then
jq -r '.statuses[] | "\(.context): \(.status) \(.target_url)"' <<<"$status"
jq -e '[.statuses[].status] | any(. == "failure" or . == "error") | not' <<<"$status" >/dev/null || exit 1
exit 0
fi
sleep 20
done
echo "timed out waiting for CI" >&2
exit 3
fi
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
+143
View File
@@ -0,0 +1,143 @@
{
"permissions": {
"defaultMode": "plan",
"disableAutoMode": "disable",
"allow": [
"Bash(pulumi preview *)",
"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 *)",
"Bash(npx tsc *)",
"Bash(kubectl get *)",
"Bash(kubectl describe *)",
"Bash(kubectl logs *)",
"Bash(kubectl top *)",
"Bash(kubectl config get-contexts *)",
"Bash(git log *)",
"Bash(git status *)",
"Bash(git diff *)",
"Bash(git show *)",
"Bash(git grep *)",
"Bash(git blame *)",
"Bash(git ls-files *)",
"Bash(git ls-tree *)",
"Bash(git rev-parse *)",
"Bash(git describe *)",
"Bash(git shortlog *)",
"Bash(git merge-base *)",
"Bash(git reflog show *)",
"Bash(git stash list *)",
"Bash(git branch --list *)",
"Bash(git branch -a *)",
"Bash(git branch -v *)",
"Bash(git tag --list *)",
"Bash(git remote -v)",
"Bash(git fetch *)",
"Bash(pulumi about *)",
"Bash(pulumi plugin ls *)",
"Bash(kubectl api-resources *)",
"Bash(kubectl api-versions *)",
"Bash(kubectl explain *)",
"Bash(kubectl version *)",
"Bash(kubectl events *)",
"Bash(kubectl cluster-info)",
"Bash(kubectl auth can-i *)",
"Bash(kubectl rollout status *)",
"Bash(kubectl rollout history *)",
"Bash(kubectl config current-context *)",
"Bash(npm ls *)",
"Bash(npm outdated *)",
"Bash(ls *)",
"Bash(pwd)",
"Bash(wc *)",
"Bash(which *)",
"Bash(jq *)",
"Bash(git add *)",
"Bash(git switch *)",
"Bash(.claude/scripts/gitea.sh GET *)",
"Bash(.claude/scripts/gitea.sh WAIT *)",
"Bash(.claude/scripts/gitea.sh POST *)",
"Bash(git commit *)",
"Bash(git push *)",
"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(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 *)",
"Bash(kubectl drain *)",
"Bash(kubectl exec *)",
"Bash(ssh *)",
"Bash(scp *)",
"Bash(curl *)",
"Bash(.claude/scripts/gitea.sh POST */merge*)",
"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(~/.kube/**)",
"Edit(~/.config/homelab-agent/**)",
"Read(~/.config/homelab-agent/token)",
"Bash(*homelab-agent/token*)"
]
},
"attribution": {
"commit": "",
"pr": ""
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-live-infra.sh"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-on-stop.sh",
"timeout": 300
}
]
}
]
}
}
+29
View File
@@ -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.
+96
View File
@@ -0,0 +1,96 @@
---
name: merge
description: Commit the staged and unstaged changes that fit the branch with meaningful messages, push a branch, open a Gitea PR, wait for CI, and merge it, without stopping for confirmation.
argument-hint: [optional note on intent, or paths to limit the merge to]
disable-model-invocation: true
---
Take the working tree changes through commit, push, PR and merge in one run. If `$ARGUMENTS` names paths, include only those. If it describes intent, use it for the commit messages and PR.
Typing `/merge` is the user's explicit instruction to commit, push, open a PR and merge these changes. It satisfies the "commit" and "ask before opening or merging" rules in `CLAUDE.md` for this run. Do not ask for confirmation, and do not pause to show drafts. Stop only for a condition under "Stop conditions".
## Rules
- Follow `CONVENTIONS.md` for branch names, commit messages and PR titles.
- Add no AI attribution to commits or PRs.
- Never use `--no-verify`, force push, or commit directly to `main`.
- Use `.claude/scripts/gitea.sh` for PR calls, because `gh` does not work here. `$REPO` below means `/repos/kasun/homelab-infrastructure-as-code`, and must be written out in full in each command.
- Never stage `Pulumi.dev.yaml`, `.env` files, keys, credentials, `.claude/settings.local.json`, or anything in `sdks/`. Leave them out, carry on, and mention them in the report.
- Write commit messages and JSON bodies to files in the scratchpad directory with the Write tool.
- Run each command on its own, in the exact forms below, from the repo root. `cd` prefixes, pipes, loops and redirects cause permission prompts.
## Stop conditions
Stop and report only if:
- HEAD is detached, or a merge or rebase is in progress.
- There are no changes and no unpushed commits.
- Typecheck or `pulumi preview` fails.
- The preview shows a replace or delete of a VM, a PVC, or an imported resource.
- A file that looks like a secret is the only change.
- A commit hook, push or API call fails after one corrected retry of a message-format error.
- CI fails, or the PR is not mergeable.
Leave the branch and PR in place when stopping after they exist, and say what is needed to continue.
## 1. Inspect
1. Run `git status`, `git diff --staged`, `git diff`, and `git log --oneline -5`. Read any untracked files that would be included.
2. Run `git fetch origin main`.
3. On a non-`main` branch, run `.claude/scripts/gitea.sh GET $REPO/pulls?state=open`. If this branch has an open PR, reuse it only for changes that serve its purpose. If all remaining changes are unrelated to it, take that PR through steps 6 and 7 first, which returns you to `main`, then continue with the remaining changes as new work.
## 2. Group into commits
Split by reason for the change, and decide without asking. Each commit should make sense and be revertable alone.
- First decide the PR's purpose from `$ARGUMENTS`, the conversation, the branch name, or else the largest change.
- On the first `/merge`, leave out any change that does not serve that purpose, such as an unrelated `.claude/settings.json` edit. Keep it uncommitted and untouched, do not ask, and list it in the report.
- On a repeat `/merge`, meaning an earlier run this session left changes out or its PR is still open, handle all remaining changes in this run. Give each separate purpose its own branch and PR, and take them one at a time through steps 3 to 7, so each is merged and you are back on `main` before the next starts. If `$ARGUMENTS` names paths, handle only those.
- Use one commit when the remaining changes serve one purpose, and several when they are distinct steps toward it.
- Group whole files. If one file mixes purposes, put it in the commit for its main change.
- Scope is the stack (`01-proxmox-infra/` is `proxmox-infra`), or `ci` for `.gitea/workflows/`. Omit the scope for repo-wide or `.claude/` changes.
- Add a body only when the diff shows a reason that is not obvious. Never invent a reason.
## 3. Verify
For each stack with changed code, run:
- `npm run typecheck --prefix <stack-dir>`
- `pulumi preview --cwd <stack-dir> --stack dev`
## 4. Commit and push
1. If on `main`, run `git switch -c <type>/<short-kebab-description>`. This carries the changes across.
2. For each commit, run `git add -- <paths>`, then `git commit -F <message file> -- <paths>`. Naming the paths commits only those files, whatever else is staged.
3. Run `git status` to confirm only intentionally excluded files remain.
4. Run `git push -u origin <branch>`.
## 5. Open the PR
Unless one exists, run `.claude/scripts/gitea.sh POST $REPO/pulls @<json file>` with `title`, `body`, `head` and `base: "main"`. The body says what changed, why, and the preview result for each stack.
## 6. Wait for CI
Get the SHA with `git rev-parse HEAD`, then run `.claude/scripts/gitea.sh WAIT $REPO/commits/<sha>/status` as a background command. Do not write a polling loop, because that causes a permission prompt.
- Exit 0: checks passed, or it printed `no CI ran` because workflows are path-filtered. Continue.
- Exit 1: stop, and report the failing check and its `target_url`.
- Exit 3: CI timed out. Stop and report it.
Then run `.claude/scripts/gitea.sh GET $REPO/pulls/<number>` and confirm `mergeable` is true.
## 7. Merge
1. Run `.claude/scripts/gitea.sh POST $REPO/pulls/<number>/merge @<json file>` with `{"Do":"merge","head_commit_id":"<sha>"}`, so only the commit CI checked can merge.
2. Run `git fetch origin main:main`, then `git switch main`.
## 8. Report
Keep it short:
- PR link and commits.
- What the merge deploys, from the `on.push.paths` in `.gitea/workflows/`. `01`, `03`, `04` and `05` deploy on merge. A change under `.gitea/workflows/` can deploy `03`, `04` and `05`, and a change to `01`'s own workflow deploys `01`.
- For `02` changes, say that they are not live until someone runs the manual workflow.
- Anything left uncommitted, and a reminder to update `<STACK>_PULUMI_DEV_YAML` if local Pulumi config changed.
Do not delete the branch, dispatch a workflow, or change a live system.
+39
View File
@@ -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: <stack directory, e.g. 03-k8s-infra>
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<T>` 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.
+11 -1
View File
@@ -3,6 +3,13 @@ name: Deploy Proxmox Infra
on: on:
workflow_dispatch: workflow_dispatch:
push:
branches:
- main
paths:
- "01-proxmox-infra/**"
- ".gitea/workflows/01-deploy-proxmox-infra.yaml"
pull_request: pull_request:
branches: branches:
- main - main
@@ -51,7 +58,7 @@ jobs:
deploy: deploy:
name: Pulumi Deploy name: Pulumi Deploy
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch' if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
steps: steps:
- name: Checkout Code - name: Checkout Code
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -75,7 +82,10 @@ jobs:
run: pulumi package add terraform-provider marshallford/pfsense 0.22.0 run: pulumi package add terraform-provider marshallford/pfsense 0.22.0
working-directory: 01-proxmox-infra working-directory: 01-proxmox-infra
# Manual runs only: a refresh that finds a VM missing drops it from state,
# and `up` would then create a blank replacement without review.
- name: Refresh State - name: Refresh State
if: github.event_name == 'workflow_dispatch'
run: | run: |
pulumi login "$PULUMI_BACKEND_URL" pulumi login "$PULUMI_BACKEND_URL"
pulumi refresh --yes --stack dev \ pulumi refresh --yes --stack dev \
+1 -1
View File
@@ -7,7 +7,7 @@ on:
- main - main
paths: paths:
- "03-k8s-infra/**" - "03-k8s-infra/**"
- ".gitea/workflows/**" - ".gitea/workflows/03-deploy-k8s-infra.yaml"
pull_request: pull_request:
branches: branches:
- main - main
+1 -1
View File
@@ -7,7 +7,7 @@ on:
- main - main
paths: paths:
- "04-k8s-apps/**" - "04-k8s-apps/**"
- ".gitea/workflows/**" - ".gitea/workflows/04-deploy-k8s-apps.yaml"
pull_request: pull_request:
branches: branches:
- main - main
+1 -1
View File
@@ -7,7 +7,7 @@ on:
- main - main
paths: paths:
- "05-monitoring/**" - "05-monitoring/**"
- ".gitea/workflows/**" - ".gitea/workflows/05-deploy-monitoring.yaml"
pull_request: pull_request:
branches: branches:
- main - main
+34
View File
@@ -0,0 +1,34 @@
name: Secret Scan
on:
workflow_dispatch:
push:
branches:
- main
pull_request:
branches:
- main
env:
BETTERLEAKS_VERSION: "1.10.1"
BETTERLEAKS_SHA256: c174b42d7aa60caf58c0c3e555c0e4bed01fe6b0d99a412bce777b5af4ce913e
jobs:
scan:
name: Betterleaks
runs-on: ubuntu-latest
steps:
- name: Checkout Full History
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Betterleaks
run: |
curl -fsSL -o /tmp/betterleaks.tar.gz \
"https://github.com/betterleaks/betterleaks/releases/download/v${BETTERLEAKS_VERSION}/betterleaks_${BETTERLEAKS_VERSION}_linux_x64.tar.gz"
echo "${BETTERLEAKS_SHA256} /tmp/betterleaks.tar.gz" | sha256sum -c -
tar -xzf /tmp/betterleaks.tar.gz -C /tmp betterleaks
- name: Scan Git History
run: /tmp/betterleaks git . --redact --verbose --no-banner --no-color --log-opts="--all -m -p -U0"
+38
View File
@@ -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 `<type>(<scope>): <summary>` 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 '<type>(<scope>): <summary>' 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
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Git pre-commit hook: blocks a commit if its staged changes contain a secret.
#
# Activate once per clone: git config core.hooksPath .githooks
# Skip in an emergency: git commit --no-verify
if ! command -v betterleaks >/dev/null 2>&1; then
echo "pre-commit: betterleaks is not installed, so staged changes can't be scanned" >&2
exit 1
fi
exec betterleaks git --pre-commit --staged --redact --no-banner --no-color .
+2
View File
@@ -6,3 +6,5 @@ bin/
Pulumi.dev.yaml Pulumi.dev.yaml
sdks/ sdks/
.env .env
.env.*
!.env.example
+2 -28
View File
@@ -1,30 +1,4 @@
# proxmox-infra # 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. - 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.
## 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.
+2 -1
View File
@@ -11,6 +11,7 @@ config:
packages: packages:
pfsense: pfsense:
source: terraform-provider source: terraform-provider
version: 1.1.3 version: 1.5.1
parameters: parameters:
- marshallford/pfsense - marshallford/pfsense
- 0.22.0
+90 -4
View File
@@ -25,6 +25,8 @@ const worker1Ip = config.requireSecret("worker1Ip");
const worker2Ip = config.requireSecret("worker2Ip"); const worker2Ip = config.requireSecret("worker2Ip");
const worker3Ip = config.requireSecret("worker3Ip"); const worker3Ip = config.requireSecret("worker3Ip");
const ansibleIp = config.requireSecret("ansibleIp");
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// VM templates — one per node, cloned from the downloaded cloud image. // VM templates — one per node, cloned from the downloaded cloud image.
// Templates are not started and have no cloud-init config; that is applied // Templates are not started and have no cloud-init config; that is applied
@@ -33,7 +35,9 @@ const worker3Ip = config.requireSecret("worker3Ip");
const templateSettings = { const templateSettings = {
template: true, template: true,
protection: true,
started: false, started: false,
operatingSystem: { type: "l26" },
stopOnDestroy: true, stopOnDestroy: true,
scsiHardware: "virtio-scsi-pci", scsiHardware: "virtio-scsi-pci",
cdrom: { fileId: "none" }, cdrom: { fileId: "none" },
@@ -137,7 +141,7 @@ const pveNodes = pveNodeSeeds
}, },
], ],
}, },
{ provider: n.provider, ignoreChanges: ["disks"] }, { provider: n.provider, protect: true, ignoreChanges: ["disks"] },
), ),
})); }));
@@ -287,12 +291,20 @@ const k3sVms = nodeConfigs.map(
agent: { enabled: true, timeout: "30s" }, agent: { enabled: true, timeout: "30s" },
cdrom: { fileId: "none" }, cdrom: { fileId: "none" },
started: false, started: false,
stopOnDestroy: true, rebootAfterUpdate: false,
}, },
{ {
provider: node.host.provider, provider: node.host.provider,
retainOnDelete: true, retainOnDelete: true,
ignoreChanges: ["clone", "started"], protect: true,
ignoreChanges: [
"clone",
"started",
// Pulumi bridge bug: unset disk speed always shows a diff.
// https://github.com/muhlba91/pulumi-proxmoxve/issues/664
"disks[0].speed",
...(node.longhornDiskSize == null ? [] : ["disks[1].speed"]),
],
}, },
), ),
); );
@@ -310,10 +322,84 @@ k3sVms.forEach((vmResource, i) => {
ipAddress: nodeConfigs[i].ip, ipAddress: nodeConfigs[i].ip,
hostname: nodeConfigs[i].name, hostname: nodeConfigs[i].name,
}, },
{ dependsOn: vmResource, provider: pfSenseProvider }, { dependsOn: vmResource, provider: pfSenseProvider, protect: true },
); );
}); });
// ---------------------------------------------------------------------------
// Ansible control node — unprivileged LXC with a pfSense DHCP reservation.
// The MAC is fixed so the reservation can exist before the container's first
// boot; otherwise its first DHCP lease could come from the dynamic pool.
// ---------------------------------------------------------------------------
const ansibleHost = hostFor("pve-b550");
const ansibleMac = "02:A5:1B:00:01:54";
const ansibleTemplate = new proxmox.download.File(
"ubuntu-resolute-lxc-pve-b550",
{
nodeName: ansibleHost.nodeName,
datastoreId: ansibleHost.isoStore,
contentType: "vztmpl",
fileName: "ubuntu-26.04-standard_26.04-1_amd64.tar.zst",
url: "https://download.proxmox.com/images/system/ubuntu-26.04-standard_26.04-1_amd64.tar.zst",
overwrite: false,
overwriteUnmanaged: true,
},
{ provider: ansibleHost.provider },
);
const ansibleDhcp = new pfsense.Dhcpv4Staticmapping(
"ansible-dhcp",
{
interface: "lan",
macAddress: ansibleMac,
ipAddress: ansibleIp,
hostname: "ansible",
},
{ provider: pfSenseProvider, protect: true },
);
new proxmox.ContainerLegacy( // NOSONAR typescript:S1848
"ansible",
{
nodeName: ansibleHost.nodeName,
description: "Ansible control node — managed by Pulumi",
tags: ["ansible"],
unprivileged: true,
features: { nesting: true },
operatingSystem: {
templateFileId: ansibleTemplate.id,
type: "ubuntu",
},
cpu: { cores: 1 },
memory: { dedicated: 1024, swap: 0 },
disk: { datastoreId: ansibleHost.dataStore, size: 8 },
networkInterfaces: [
{ name: "eth0", bridge: "vmbr0", macAddress: ansibleMac },
],
initialization: {
hostname: "ansible",
ipConfigs: [{ ipv4: { address: "dhcp" } }],
userAccount: {
keys: [
pve1SshPublicKey.apply((k) => k.trim()),
pve2SshPublicKey.apply((k) => k.trim()),
pve3SshPublicKey.apply((k) => k.trim()),
],
},
},
started: true,
startOnBoot: true,
},
{
provider: ansibleHost.provider,
dependsOn: ansibleDhcp,
retainOnDelete: true,
protect: true,
},
);
export const vmIds = { export const vmIds = {
master1: k3sVms[0].vmId, master1: k3sVms[0].vmId,
master2: k3sVms[1].vmId, master2: k3sVms[1].vmId,
+365 -1691
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -1,6 +1,9 @@
{ {
"name": "proxmox-infra", "name": "proxmox-infra",
"main": "index.ts", "main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": { "devDependencies": {
"@types/node": "^24", "@types/node": "^24",
"typescript": "^6.0.0" "typescript": "^6.0.0"
+7 -52
View File
@@ -1,58 +1,13 @@
# k8s-bootstrap # 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. ## Decisions the code doesn't explain
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`. - **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://<controlPlaneVipAddress>: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`.
## How it works ## Running against live VMs
1. Starts all VMs via `POST /api2/json/nodes/{node}/qemu/{vmid}/status/start` 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.
2. Waits for port 22 to open on each VM (bash `/dev/tcp`), installs k3s on `k3s-master-1` with `--cluster-init --tls-san <master1Ip> --tls-san <controlPlaneVipAddress>`
3. Waits for `https://<controlPlaneVipAddress>: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://<controlPlaneVipAddress>:6443`
5. Joins `k3s-worker-1`, `k3s-worker-2`, and `k3s-worker-3` as agent nodes via `K3S_URL=https://<controlPlaneVipAddress>: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. 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.
## Required Pulumi config
```bash
# Pre-shared k3s token — any strong random string
pulumi config set --secret k3sToken "$(openssl rand -hex 32)"
# 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 (see "pfSense one-time setup" below). 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.
## 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 = `<controlPlaneVipAddress>/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 = `<master1Ip>:6443`, `<master2Ip>:6443`, `<master3Ip>:6443`.
5. Services → HAProxy → Frontend: add a frontend listening on `<controlPlaneVipAddress>: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.
+34
View File
@@ -0,0 +1,34 @@
-----BEGIN CERTIFICATE-----
MIIF3TCCA8WgAwIBAgIUDXajbsIFjkrtUM/HEOAMI06xHjEwDQYJKoZIhvcNAQEL
BQAwdjEkMCIGA1UEAwwbUHJveG1veCBWaXJ0dWFsIEVudmlyb25tZW50MS0wKwYD
VQQLDCRiYTk0ZDJhZC0wOTc2LTRmZjAtODQ1Mi1kMjM1OGMxZGM3OGIxHzAdBgNV
BAoMFlBWRSBDbHVzdGVyIE1hbmFnZXIgQ0EwHhcNMjYxMTAzMDAwODM5WhcNMzYx
MDMxMDAwODM5WjB2MSQwIgYDVQQDDBtQcm94bW94IFZpcnR1YWwgRW52aXJvbm1l
bnQxLTArBgNVBAsMJGJhOTRkMmFkLTA5NzYtNGZmMC04NDUyLWQyMzU4YzFkYzc4
YjEfMB0GA1UECgwWUFZFIENsdXN0ZXIgTWFuYWdlciBDQTCCAiIwDQYJKoZIhvcN
AQEBBQADggIPADCCAgoCggIBAM1OPRmaMGdkrgVQikVCOFAF7eXL0H7lUfognG4A
Xi/D85bLKGJYF106PQFlmkvw+CvNIHCeeqvgDJc2AoV22PnKjPlP34b3j4AAoEm3
sMvKHke+N3kSfhG7hxZ8JfnV+EIZO1ZAI0X2z0ixmmn3gzIVjdtO9VycL7Nj2JJV
O+Ws+yc3j3swhVA87bIikc+sD0YT8F8dK41DQfgM01wWhieGLCk4g8DSbOt1Ypgv
hAwlKziUtUdw/teC8vmE0GwUMas/uwFVXzBEd/4ancI1SkPH/Mtu568HCVzcCBjE
wFAhdMZ90g7UXC58m5cFqs2PafDsAYv2rmSCic8yO2aZCO5nbQOtU9rN2b1e9KGs
xfDksugSJ2ZsIZ4YsG9Eao6WXkZIohANEhUkGK3yI4REiJO96/pmqf1QtNRvUZWW
YIxa56i2KrjB2RdGe9eirNlshTPA3DpJbLHmcsw1agPEI5mN4uQJ3DrSGrFwXHkB
QYW9NmgwLHUlOYdvUUq7AIY3RqCBWWkBW0vlg78W2fiaq1Gp6Mx/9HeVdriB2FGa
UlAE6CAzDI+JqQPQkmzo6QmFB3hFa9m1aPctLZo0bOKCeoyREBaPmmZfn6VaI1Xk
+mUIw6NLstdG0lS/qThNYbG5LWdRIyHdLcjsg19pFfmj9YUMphoMD7k2IG4Cu9nP
mwqlAgMBAAGjYzBhMB0GA1UdDgQWBBTKcVA3Li/Qe4f/vEsHFHc/VNVFHzAfBgNV
HSMEGDAWgBTKcVA3Li/Qe4f/vEsHFHc/VNVFHzAPBgNVHRMBAf8EBTADAQH/MA4G
A1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAMLrQvbGlgpqxSaxQKb4N
wmmRQqgWvJ7/s9UhHE5BNfkUzJ+3ktAwfbswuNc4yfREjPqRBWzd/mz/WhlsDOzR
KT+ECQpNbnlR3JBJMYOiLDwKydnYWgiTiINxtc7p74NoGe/fu8dGKiGYtsk+bmps
yP1FOp3YQ2UM1NjQoalk2sZYOCRUL1HbgfaSHEwFXskJMKprUEEjJjXLxyJey14U
u6gSvUb2T8bbycW8Ilibo5Dn/DxLFBNT154M7GHQyVSdWLoEAVVzkrlJJ9b0RYnb
PQXOySSuIvrQx8QqG6X/4AfPrm2L1O8CAAwpNi3xa6jvVX6DWT1+HOhN8MfjtYJE
9KxbG6MNxnE8A39m46O2iYfwW+zTej842N1Fq6eA7i2nMuzHB3jqNVdvxaLCNK2a
FCAilpl2iuqO5eOWZG2Gd9qcPQSslRrhJid6GV/pTeh/ZpZyf/OG4XXata+IB2aq
0ggaQgGn5dFiCklLeFsnX0k0pydz/ZVA1v5C/sVk3q07JrPJo0IKs0SuS0lsHH9n
hPIdbUH3AsG850vDTIsKYgmZdssnG13bsGwZtC8x3MS1c868PRgG/ZycdT6BGk6Q
qX9ogoFrdUy3XYSRVDb2L+Z8NEI8grFOTDRXAlp5B4BHAbvXoIeeYjGtjtOunYCo
f3Em5SShmS4B2U/jTPyDeZ0=
-----END CERTIFICATE-----
+34
View File
@@ -0,0 +1,34 @@
-----BEGIN CERTIFICATE-----
MIIF3TCCA8WgAwIBAgIUUfheavZDUF4EvmQ6q8upF7dd74UwDQYJKoZIhvcNAQEL
BQAwdjEkMCIGA1UEAwwbUHJveG1veCBWaXJ0dWFsIEVudmlyb25tZW50MS0wKwYD
VQQLDCQxZWQ0Nzc1Yi1hMjc1LTQ3ZDktYTA1Mi1kM2M1MThhYjE2MzIxHzAdBgNV
BAoMFlBWRSBDbHVzdGVyIE1hbmFnZXIgQ0EwHhcNMjYxMTAyMDMzMDIxWhcNMzYx
MDMwMDMzMDIxWjB2MSQwIgYDVQQDDBtQcm94bW94IFZpcnR1YWwgRW52aXJvbm1l
bnQxLTArBgNVBAsMJDFlZDQ3NzViLWEyNzUtNDdkOS1hMDUyLWQzYzUxOGFiMTYz
MjEfMB0GA1UECgwWUFZFIENsdXN0ZXIgTWFuYWdlciBDQTCCAiIwDQYJKoZIhvcN
AQEBBQADggIPADCCAgoCggIBAK3vi3/3+0trXhEkDXoSrOFWTuXc7x7vPmORzQ6R
V/sg1X6KTbguzSPg71B/8Qu1vRYTkS6Pf5YclpE0P+z45hCV+G8B40cAL3D1Xpbo
JTznI2gaO00XDTei1MdDTC/mwUzoNBa7osXEmMwgz7Oid7WHJbIQegwq2LEMRbqQ
UtAXsAone1eq+N2vQys57MlnXnSbMFFlY1VNfUJIinjyLZgE9klFkvVFSqy9CkUs
4Yq9M6YSgvNA77tPSH/yc0605N1462x/VRHUkY4nufrWqI8oUlcGrK8mNieCtPK7
FOr3PZXq5K0I3LsSlbp7M43Bbumnuscg0ustyf/eCM7tdMQm9E5yfQsMH+Ao390x
nBrlpVqA6RSWGAeDhspuB6Sj+InVfzoLKvhqwzlGV5S+WT+uDN4VhRdGlet/kVC8
Xn5GIRgeGR/x5zs93Xxz9OEyVhSxPB6+NP/NJ4z7OD21Oiar7GUFzPbaMpWnSChW
5Vsp2i8HUikjUyiGb8nYZfVEHwj/w3JEs+m4eTwUroT4YgLRMwahye5gJTcq19oA
xFUzStAXEGglv5AVf0ngU3KTkwFP2ROLry/FIk6ZQSedJtnBpq0+CcMZe+vKSVD7
acFZ6k/bFh4jMeD9i1/Zx+mRf8XvZEeaImxYc0P9vnxfl2XP7QiroEP7PkuFZ6As
69rpAgMBAAGjYzBhMB0GA1UdDgQWBBSex+vVqEdCLAk0eKJiSfYltlTaKTAfBgNV
HSMEGDAWgBSex+vVqEdCLAk0eKJiSfYltlTaKTAPBgNVHRMBAf8EBTADAQH/MA4G
A1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAkeVBiV4Zs+yoXKTcdy0A
Y7cEAGUY+zWQeg/eZnbNMWqG5x4UKWpA+9LZDOhAu7lBwkWoTlYLw6foDuy47uzQ
LBxqxI5gXkUi/CvIlOZ8AjuNdVU02wdDoib8O5mJDpvEMIOQawbRno84mlYdzhRs
BHeBugNdiORBk1JbqZjsvAmtlbjDaDNV0oxm9C5Np4F9sbA9lChkz+bv/KJxYexB
P91nonJfmyajDkWqrCaFIyjliNjfmff1CM2EpNDlngwXo6XjSgWjFuEVtHE2xl3t
J21a0WSxuIkQUNWJMcyr9j9LLAnZG06XCNEy6g2R8vMFmm3xGM76NkABkCsFT5PZ
lEmrAVmVDWKx2heAlVmVQ1wFrlGVYnlVxTWWcIHrHRCJJfc12tCwczbumBDxO45u
iJ5d4GI5HBSYz3kdMzzpBhLIH5l5h/AzmGebkhbSAK7I/V0kPOQvOVVrtCYr/Ec4
gU1AV6bjiu3USOeiAqkxW791Xp0IFkP+8e4FYohyG6QyS5jHtf0Vtl8/xJSKU9mj
idc4dwZSWu0V9LaNcMbk8kyRTvX/LwKuLOYp++a0/vxUMvgsv0yqeElvWAJB33xe
Ih/rsFCIC247ccQZ1g4JGHRJqRTAIQT4VsDqSRh+0KwarPvgJPEsluDB9bholfZ9
LoZqoymHgYm95H7LaDTdytA=
-----END CERTIFICATE-----
+34
View File
@@ -0,0 +1,34 @@
-----BEGIN CERTIFICATE-----
MIIFzTCCA7WgAwIBAgIUHFXkUXk2cmTrkKJxLSTvxhg5lfowDQYJKoZIhvcNAQEL
BQAwdjEkMCIGA1UEAwwbUHJveG1veCBWaXJ0dWFsIEVudmlyb25tZW50MS0wKwYD
VQQLDCQ4NzNhNGYzMS05YWQ2LTQ3MDYtYTg5MS0xZmU2NDIzNzgyYzQxHzAdBgNV
BAoMFlBWRSBDbHVzdGVyIE1hbmFnZXIgQ0EwHhcNMjUwODI5MjIzNjU5WhcNMzUw
ODI3MjIzNjU5WjB2MSQwIgYDVQQDDBtQcm94bW94IFZpcnR1YWwgRW52aXJvbm1l
bnQxLTArBgNVBAsMJDg3M2E0ZjMxLTlhZDYtNDcwNi1hODkxLTFmZTY0MjM3ODJj
NDEfMB0GA1UECgwWUFZFIENsdXN0ZXIgTWFuYWdlciBDQTCCAiIwDQYJKoZIhvcN
AQEBBQADggIPADCCAgoCggIBAL3iGXWp8BkVcXIpfVybY0slRl36bQp3OkswgTc9
awdsN62wWkN6NIa4yZsItzjHnCyte6Nac9qCmu25Pwhw4QEc7XRWuh4sVPvw4ica
0JgDw7yJbn8IM3C7qm9+g5iXoGcOdY41xsKJz7+cWgySh4EBPWYEuKOxtWuvTRzV
Q3b/o+LT8X/Q5qR7EehgLVy5KtWZCDjV/6862hh9zEiA87zosULHtVYAa1lWtL48
9q0flbQsIIFmaeio/iEJR66YHXTF7AlKaIrXLVCMRdRV6oef/b4SqECwnZVQnE28
I1uwnOV88MIfr9sINhdW7ogxSvlGFptkDkRVXnqfIOwLJjjPRuIifFg98KYR1gLp
vGMeRY96mJvJ98NUSeVZOQMVs8vnEXHlpPewsklQty23KQJTr42R5zIKXSguZZUU
NjNgDTPdUu45jNDu8nzU8guK3AcTkLbtmbL5uUCGZo860ScUFQUtuibou6plYVjx
Yca+mH3QoZI/lfnB/f2aNL9JP+DlTUfwTMgSAKiilOOqWvsHLjXvZjZupoAW0Xh4
CREKf0n5T9ldy6goRzbmWE475uc0UPtmLdlVrqt0F89YH8wZAlPu91a6pvomWUYX
pokkimWvPf3C+YgRDJIkolAQ1l+egnS/KR2tgLVEKktfXm4nRk2VotWOcsBDme40
Hwz3AgMBAAGjUzBRMB0GA1UdDgQWBBTK4krmBcFK3+fphDn5+DuknRdz4TAfBgNV
HSMEGDAWgBTK4krmBcFK3+fphDn5+DuknRdz4TAPBgNVHRMBAf8EBTADAQH/MA0G
CSqGSIb3DQEBCwUAA4ICAQCFW1DCfMOMTy/MvbYT8KKhwLujjjQvdKsgnRaktRzq
j66dohxWHiN0jDDgIeT1DkB/guh5pqcDnwVaiVZAagEJ/NvigTPRodTcijhomCzz
p9GCaMnl21YX2D5Ckg69iJ+AVekwNTHWqAVwbXZj1dpxs3SBceps9NQvzfNUI823
jDNpgYo9E4kymBIe8ibXNXiGbrZb171aqWzdJEdXIGmvbruXiIOwkkynJHViMo1Y
8RiUQx+NwGJw5NTTuHuCI0zYTxrqObPvtfwvyYEpaOf1fs246fRHDo8okffxLuMR
AbEVJuU4GCh3JhO5M1BUWEKllx4wZW8/ygtHc8TkKwxMQS86/bEptSoMn0TJ0XeC
YnnhML0XD0aRtcoqRhmfBjMntNeiHaAkXusLyc8LNyynhqWv3ldTw05JSfVSlhjC
paJNzLYYFa2VC/EG++1Kv6nvZjNZHzV34fkBw9dS6cJbhp5WK7WQgoZgIUF6kJN3
nEm0DzRUR6R4KjNgYJxmhXxHvKOeYyp52muiNkehFZ0d1/RdftgUvjh8pR7KEfSH
JaO5K0BWMy7infAcAOHb6krEMwfkr3NXUfF4pbuqNGQx5MHYfXkPiIdPy6q6ZqmO
ittFd5xKjL7J0QaDkAcxmJFJ2FdtQhoV14eKESBUdQV0NCSKXQgebkV5a8ik0mJU
GA==
-----END CERTIFICATE-----
+106 -19
View File
@@ -3,6 +3,27 @@ import * as command from "@pulumi/command";
const config = new pulumi.Config(); const config = new pulumi.Config();
// Bootstrap commands run once, on a fresh install. Without this, a changed VM
// ID, node IP, SSH key or command would re-run the k3s installer on the live
// cluster. After recreating a VM, re-run its commands explicitly with
// --target-replace.
pulumi.runtime.registerResourceTransform((args) =>
args.type.startsWith("command:")
? {
props: args.props,
opts: pulumi.mergeOptions(args.opts, {
ignoreChanges: [
"create",
"triggers",
"connection",
"environment",
"stdin",
],
}),
}
: undefined,
);
const infraRef = new pulumi.StackReference( const infraRef = new pulumi.StackReference(
`${pulumi.getOrganization()}/proxmox-infra/dev`, `${pulumi.getOrganization()}/proxmox-infra/dev`,
); );
@@ -37,6 +58,19 @@ const worker3Ip = infraRef.requireOutput("worker3Ip");
// Pre-shared k3s cluster token // Pre-shared k3s cluster token
const k3sToken = config.requireSecret("k3sToken"); const k3sToken = config.requireSecret("k3sToken");
// Version for fresh installs. Changing it does not upgrade the live cluster.
const k3sVersion = "v1.36.2+k3s1";
const k3sInstallerUrl = `https://raw.githubusercontent.com/k3s-io/k3s/${encodeURIComponent(k3sVersion)}/install.sh`;
// Runs the pinned installer. The token arrives on stdin and travels in the
// environment, so it never appears in process arguments.
function k3sInstallScript(
installEnv: pulumi.Input<string>,
installArgs: pulumi.Input<string>,
): pulumi.Output<string> {
return pulumi.interpolate`set -euo pipefail; IFS= read -r K3S_TOKEN || true; export K3S_TOKEN; curl -sfL ${k3sInstallerUrl} | sudo --preserve-env=K3S_TOKEN INSTALL_K3S_VERSION='${k3sVersion}' ${installEnv} sh -s - ${installArgs}`;
}
// Control-plane VIP — floating IP for API server access, ARP-announced by // Control-plane VIP — floating IP for API server access, ARP-announced by
// kube-vip on whichever master is alive. Added as a TLS SAN on master-1's // kube-vip on whichever master is alive. Added as a TLS SAN on master-1's
// cert below, then used (instead of master1Ip) for every other node's join // cert below, then used (instead of master1Ip) for every other node's join
@@ -67,37 +101,56 @@ function conn(
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Step 1: Start all VMs (fire-and-forget — VMs are owned by proxmox-infra) // Step 1: Start all VMs (VMs are owned by proxmox-infra)
// triggers: vmId — forces re-run when VMs are deleted and recreated
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Succeeds if the VM is already running, or reaches running after a start.
// TLS is verified against the host's Proxmox CA in certs/. The API token comes
// from PVE_API_TOKEN and reaches curl on stdin, keeping it out of process
// arguments.
function startVmScript(
endpoint: pulumi.Input<string>,
caName: string,
nodeName: string,
vmId: pulumi.Input<string>,
): pulumi.Output<string> {
return pulumi.interpolate`base="${endpoint}/api2/json/nodes/${nodeName}/qemu/${vmId}/status"; ca="certs/${caName}-ca.pem"; auth() { printf 'header = "Authorization: PVEAPIToken=%s"
' "$PVE_API_TOKEN"; }; is_running() { auth | curl -sf -K - --cacert "$ca" "$base/current" | grep -Eq '"status" *: *"running"'; }; is_running && exit 0; auth | curl -sf -K - --cacert "$ca" -X POST "$base/start" >/dev/null || exit 1; for i in $(seq 1 30); do is_running && exit 0; sleep 2; done; exit 1`;
}
const startMaster1 = new command.local.Command("start-master-1", { const startMaster1 = new command.local.Command("start-master-1", {
create: pulumi.interpolate`curl -sf -k -X POST -H "Authorization: PVEAPIToken=${pve1ApiToken}" "${pve1Endpoint}/api2/json/nodes/pve/qemu/${master1VmId}/status/start" 2>/dev/null || true`, create: startVmScript(pve1Endpoint, "pve1", "pve", master1VmId),
environment: { PVE_API_TOKEN: pve1ApiToken },
triggers: [master1VmId], triggers: [master1VmId],
interpreter: ["/bin/bash", "-c"], interpreter: ["/bin/bash", "-c"],
}); });
const startMaster2 = new command.local.Command("start-master-2", { const startMaster2 = new command.local.Command("start-master-2", {
create: pulumi.interpolate`curl -sf -k -X POST -H "Authorization: PVEAPIToken=${pve1ApiToken}" "${pve1Endpoint}/api2/json/nodes/pve/qemu/${master2VmId}/status/start" 2>/dev/null || true`, create: startVmScript(pve3Endpoint, "pve3", "pve", master2VmId),
environment: { PVE_API_TOKEN: pve3ApiToken },
triggers: [master2VmId], triggers: [master2VmId],
interpreter: ["/bin/bash", "-c"], interpreter: ["/bin/bash", "-c"],
}); });
const startWorker1 = new command.local.Command("start-worker-1", { const startWorker1 = new command.local.Command("start-worker-1", {
create: pulumi.interpolate`curl -sf -k -X POST -H "Authorization: PVEAPIToken=${pve1ApiToken}" "${pve1Endpoint}/api2/json/nodes/pve/qemu/${worker1VmId}/status/start" 2>/dev/null || true`, create: startVmScript(pve1Endpoint, "pve1", "pve", worker1VmId),
environment: { PVE_API_TOKEN: pve1ApiToken },
triggers: [worker1VmId], triggers: [worker1VmId],
interpreter: ["/bin/bash", "-c"], interpreter: ["/bin/bash", "-c"],
}); });
const startMaster3 = new command.local.Command("start-master-3", { const startMaster3 = new command.local.Command("start-master-3", {
create: pulumi.interpolate`curl -sf -k -X POST -H "Authorization: PVEAPIToken=${pve2ApiToken}" "${pve2Endpoint}/api2/json/nodes/pve-bckp/qemu/${master3VmId}/status/start" 2>/dev/null || true`, create: startVmScript(pve2Endpoint, "pve2", "pve-bckp", master3VmId),
environment: { PVE_API_TOKEN: pve2ApiToken },
triggers: [master3VmId], triggers: [master3VmId],
interpreter: ["/bin/bash", "-c"], interpreter: ["/bin/bash", "-c"],
}); });
const startWorker2 = new command.local.Command("start-worker-2", { const startWorker2 = new command.local.Command("start-worker-2", {
create: pulumi.interpolate`curl -sf -k -X POST -H "Authorization: PVEAPIToken=${pve2ApiToken}" "${pve2Endpoint}/api2/json/nodes/pve-bckp/qemu/${worker2VmId}/status/start" 2>/dev/null || true`, create: startVmScript(pve2Endpoint, "pve2", "pve-bckp", worker2VmId),
environment: { PVE_API_TOKEN: pve2ApiToken },
triggers: [worker2VmId], triggers: [worker2VmId],
interpreter: ["/bin/bash", "-c"], interpreter: ["/bin/bash", "-c"],
}); });
const startWorker3 = new command.local.Command("start-worker-3", { const startWorker3 = new command.local.Command("start-worker-3", {
create: pulumi.interpolate`curl -sf -k -X POST -H "Authorization: PVEAPIToken=${pve3ApiToken}" "${pve3Endpoint}/api2/json/nodes/pve/qemu/${worker3VmId}/status/start" 2>/dev/null || true`, create: startVmScript(pve3Endpoint, "pve3", "pve", worker3VmId),
environment: { PVE_API_TOKEN: pve3ApiToken },
triggers: [worker3VmId], triggers: [worker3VmId],
interpreter: ["/bin/bash", "-c"], interpreter: ["/bin/bash", "-c"],
}); });
@@ -129,7 +182,11 @@ const installMaster1 = new command.remote.Command(
"install-k3s-master-1", "install-k3s-master-1",
{ {
connection: conn(master1Ip), connection: conn(master1Ip),
create: pulumi.interpolate`curl -sfL https://get.k3s.io | sudo K3S_TOKEN='${k3sToken}' sh -s - server --cluster-init --tls-san ${master1Ip} --tls-san ${controlPlaneVipAddress} --disable servicelb --node-name k3s-master-1`, create: k3sInstallScript(
"",
pulumi.interpolate`server --cluster-init --tls-san ${master1Ip} --tls-san ${controlPlaneVipAddress} --disable servicelb --node-name k3s-master-1`,
),
stdin: k3sToken,
triggers: [master1VmId], triggers: [master1VmId],
}, },
{ dependsOn: [waitMaster1Ssh] }, { dependsOn: [waitMaster1Ssh] },
@@ -162,7 +219,9 @@ const waitControlPlaneVipReady = new command.remote.Command(
"wait-control-plane-vip-ready", "wait-control-plane-vip-ready",
{ {
connection: conn(master1Ip), connection: conn(master1Ip),
create: pulumi.interpolate`for i in $(seq 1 60); do curl -sk --max-time 3 https://${controlPlaneVipAddress}:6443/healthz && exit 0; sleep 5; done; exit 1`, // 401/403 still prove the API server answered through the VIP: the request
// is anonymous, and some clusters reject anonymous health checks.
create: pulumi.interpolate`for i in $(seq 1 60); do code=$(curl -sk --max-time 3 -o /dev/null -w '%{http_code}' https://${controlPlaneVipAddress}:6443/healthz); case "$code" in 200|401|403) exit 0;; esac; sleep 5; done; exit 1`,
triggers: [master1VmId], triggers: [master1VmId],
}, },
{ dependsOn: [waitK3sMaster1Ready] }, { dependsOn: [waitK3sMaster1Ready] },
@@ -196,7 +255,11 @@ const joinMaster2 = new command.remote.Command(
"join-k3s-master-2", "join-k3s-master-2",
{ {
connection: conn(master2Ip), connection: conn(master2Ip),
create: pulumi.interpolate`curl -sfL https://get.k3s.io | sudo K3S_TOKEN='${k3sToken}' sh -s - server --server https://${controlPlaneVipAddress}:6443 --disable servicelb --node-name k3s-master-2`, create: k3sInstallScript(
"",
pulumi.interpolate`server --server https://${controlPlaneVipAddress}:6443 --disable servicelb --node-name k3s-master-2`,
),
stdin: k3sToken,
triggers: [master2VmId], triggers: [master2VmId],
}, },
{ dependsOn: [waitMaster2Ssh, waitControlPlaneVipReady] }, { dependsOn: [waitMaster2Ssh, waitControlPlaneVipReady] },
@@ -206,7 +269,11 @@ const joinMaster3 = new command.remote.Command(
"join-k3s-master-3", "join-k3s-master-3",
{ {
connection: conn(master3Ip), connection: conn(master3Ip),
create: pulumi.interpolate`curl -sfL https://get.k3s.io | sudo K3S_TOKEN='${k3sToken}' sh -s - server --server https://${controlPlaneVipAddress}:6443 --disable servicelb --node-name k3s-master-3`, create: k3sInstallScript(
"",
pulumi.interpolate`server --server https://${controlPlaneVipAddress}:6443 --disable servicelb --node-name k3s-master-3`,
),
stdin: k3sToken,
triggers: [master3VmId], triggers: [master3VmId],
}, },
{ dependsOn: [waitMaster3Ssh, waitControlPlaneVipReady, joinMaster2] }, { dependsOn: [waitMaster3Ssh, waitControlPlaneVipReady, joinMaster2] },
@@ -250,7 +317,11 @@ const joinWorker1 = new command.remote.Command(
"join-k3s-worker-1", "join-k3s-worker-1",
{ {
connection: conn(worker1Ip), connection: conn(worker1Ip),
create: pulumi.interpolate`curl -sfL https://get.k3s.io | sudo K3S_URL=https://${controlPlaneVipAddress}:6443 K3S_TOKEN='${k3sToken}' sh -s - --node-name k3s-worker-1`, create: k3sInstallScript(
pulumi.interpolate`K3S_URL=https://${controlPlaneVipAddress}:6443`,
"--node-name k3s-worker-1",
),
stdin: k3sToken,
triggers: [worker1VmId], triggers: [worker1VmId],
}, },
{ dependsOn: [waitWorker1Ssh] }, { dependsOn: [waitWorker1Ssh] },
@@ -260,7 +331,11 @@ const joinWorker2 = new command.remote.Command(
"join-k3s-worker-2", "join-k3s-worker-2",
{ {
connection: conn(worker2Ip), connection: conn(worker2Ip),
create: pulumi.interpolate`curl -sfL https://get.k3s.io | sudo K3S_URL=https://${controlPlaneVipAddress}:6443 K3S_TOKEN='${k3sToken}' sh -s - --node-name k3s-worker-2`, create: k3sInstallScript(
pulumi.interpolate`K3S_URL=https://${controlPlaneVipAddress}:6443`,
"--node-name k3s-worker-2",
),
stdin: k3sToken,
triggers: [worker2VmId], triggers: [worker2VmId],
}, },
{ dependsOn: [waitWorker2Ssh] }, { dependsOn: [waitWorker2Ssh] },
@@ -270,7 +345,11 @@ const joinWorker3 = new command.remote.Command(
"join-k3s-worker-3", "join-k3s-worker-3",
{ {
connection: conn(worker3Ip), connection: conn(worker3Ip),
create: pulumi.interpolate`curl -sfL https://get.k3s.io | sudo K3S_URL=https://${controlPlaneVipAddress}:6443 K3S_TOKEN='${k3sToken}' sh -s - --node-name k3s-worker-3`, create: k3sInstallScript(
pulumi.interpolate`K3S_URL=https://${controlPlaneVipAddress}:6443`,
"--node-name k3s-worker-3",
),
stdin: k3sToken,
triggers: [worker3VmId], triggers: [worker3VmId],
}, },
{ dependsOn: [waitWorker3Ssh] }, { dependsOn: [waitWorker3Ssh] },
@@ -290,11 +369,15 @@ workers.forEach((worker, i) => {
connection: conn(worker), connection: conn(worker),
create: `set -euo pipefail; create: `set -euo pipefail;
DISK_ID=$(ls /dev/disk/by-id/ | grep 'scsi1'); DISK_ID=$(ls /dev/disk/by-id/ | grep 'scsi1');
[ "$(echo "$DISK_ID" | wc -l)" -eq 1 ];
DISK_PATH="/dev/disk/by-id/$DISK_ID"; DISK_PATH="/dev/disk/by-id/$DISK_ID";
sudo blkid "$DISK_PATH" >/dev/null 2>&1 || sudo mkfs.ext4 "$DISK_PATH"; BLKID_RC=0;
sudo blkid -p "$DISK_PATH" >/dev/null 2>&1 || BLKID_RC=$?;
if [ "$BLKID_RC" -eq 2 ]; then sudo mkfs.ext4 "$DISK_PATH"; elif [ "$BLKID_RC" -ne 0 ]; then exit "$BLKID_RC"; fi;
sudo mkdir -p /mnt/longhorn-extra; sudo mkdir -p /mnt/longhorn-extra;
echo ""$DISK_PATH" /mnt/longhorn-extra ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab; grep -qs " /mnt/longhorn-extra " /etc/fstab || echo "$DISK_PATH /mnt/longhorn-extra ext4 defaults,nofail 0 2" | sudo tee -a /etc/fstab;
sudo mount -a; sudo mount -a;
mountpoint -q /mnt/longhorn-extra;
df -h /mnt/longhorn-extra`, df -h /mnt/longhorn-extra`,
}, },
{ dependsOn: workerSshReader[i] }, { dependsOn: workerSshReader[i] },
@@ -312,7 +395,10 @@ const getKubeconfig = new command.remote.Command(
create: `sudo cat /etc/rancher/k3s/k3s.yaml`, create: `sudo cat /etc/rancher/k3s/k3s.yaml`,
triggers: [master1VmId], triggers: [master1VmId],
}, },
{ dependsOn: [joinWorker1, joinWorker2, joinWorker3] }, {
dependsOn: [joinWorker1, joinWorker2, joinWorker3],
additionalSecretOutputs: ["stdout"],
},
); );
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -363,7 +449,8 @@ allVms.forEach(({ id, ip, name, readiness }) => {
`install-packages-${name}`, `install-packages-${name}`,
{ {
connection: conn(ip), connection: conn(ip),
create: pulumi.interpolate`sudo apt update && sudo apt install -y qemu-guest-agent && sudo systemctl enable --now qemu-guest-agent`, // cloud-init exit code 2 means it finished with recoverable errors.
create: pulumi.interpolate`{ sudo cloud-init status --wait >/dev/null || [ $? -eq 2 ]; } && sudo apt-get -o DPkg::Lock::Timeout=300 update && sudo apt-get -o DPkg::Lock::Timeout=300 install -y qemu-guest-agent && sudo systemctl enable --now qemu-guest-agent`,
triggers: [id], triggers: [id],
}, },
{ dependsOn: readiness }, { dependsOn: readiness },
+3
View File
@@ -1,6 +1,9 @@
{ {
"name": "k8s-bootstrap", "name": "k8s-bootstrap",
"main": "index.ts", "main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"typescript": "^6.0.0" "typescript": "^6.0.0"
+4 -53
View File
@@ -1,55 +1,6 @@
# k8s-infra # 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. - **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.
Cluster-level infrastructure for the k3s homelab cluster, deployed via Helm and `@pulumi/kubernetes`. Reads `kubeconfig` from `k8s-bootstrap` via StackReference. - 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`.
## 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 <truenas-ip>
pulumi config set --secret truenasNfsPath /mnt/pool/k8s
pulumi config set --secret cloudflareApiToken <cf-token>
pulumi config set --secret letsencryptEmail <your-email>
pulumi config set --secret kubeVipAddress <vip-ip>
pulumi config set kubeVipInterface <e.g. eth0>
```
`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`)
## CI/CD
Workflow: `../.gitea/workflows/03-deploy-k8s-infra.yaml`. Secret: `K8S_INFRA_PULUMI_DEV_YAML`.
+123 -2
View File
@@ -19,7 +19,17 @@ const letsencryptEmail = config.requireSecret("letsencryptEmail");
const kubeVipAddress = config.requireSecret("kubeVipAddress"); const kubeVipAddress = config.requireSecret("kubeVipAddress");
const kubeVipInterface = config.require("kubeVipInterface"); const kubeVipInterface = config.require("kubeVipInterface");
const k8sProvider = new k8s.Provider("k3s", { kubeconfig }); const domain = config.requireSecret("domain");
const longhornUiUser = config.requireSecret("longhornUiUser");
const longhornUiPassword = config.requireSecret("longhornUiPassword");
// Keep the kubeconfig stored in state. A changed API address would otherwise
// make Pulumi replace the provider and every resource in this stack.
const k8sProvider = new k8s.Provider(
"k3s",
{ kubeconfig },
{ ignoreChanges: ["kubeconfig"] },
);
const opts = (extras?: pulumi.ResourceOptions): pulumi.ResourceOptions => ({ const opts = (extras?: pulumi.ResourceOptions): pulumi.ResourceOptions => ({
provider: k8sProvider, provider: k8sProvider,
...extras, ...extras,
@@ -69,6 +79,7 @@ const certManager = new k8s.helm.v3.Release(
{ {
name: "cert-manager", name: "cert-manager",
chart: "cert-manager", chart: "cert-manager",
version: "v1.21.1",
repositoryOpts: { repo: "https://charts.jetstack.io" }, repositoryOpts: { repo: "https://charts.jetstack.io" },
namespace: "cert-manager", namespace: "cert-manager",
createNamespace: true, createNamespace: true,
@@ -133,15 +144,61 @@ const longhorn = new k8s.helm.v3.Release(
version: "1.12.0", version: "1.12.0",
values: { values: {
defaultSettings: { defaultSettings: {
defaultReplicaCount: 2, defaultReplicaCount: 3,
nodeDownPodDeletionPolicy: "delete-both-statefulset-and-deployment-pod", nodeDownPodDeletionPolicy: "delete-both-statefulset-and-deployment-pod",
createDefaultDiskLabeledNodes: true, createDefaultDiskLabeledNodes: true,
orphanResourceAutoDeletion: "replica-data;instance",
// Longhorn's recommendation for dedicated disks (longhorn-extra).
// Docs: https://longhorn.io/docs/1.12.0/best-practices/
storageMinimalAvailablePercentage: 10,
}, },
}, },
}, },
opts(), opts(),
); );
// Purges system snapshots, which can otherwise grow to a full volume's size
// on every replica. Docs:
// https://longhorn.io/docs/1.12.0/snapshots-and-backups/scheduling-backups-and-snapshots/
new k8s.apiextensions.CustomResource(
"longhorn-snapshot-cleanup",
{
apiVersion: "longhorn.io/v1beta2",
kind: "RecurringJob",
metadata: { name: "snapshot-cleanup", namespace: "longhorn-system" },
spec: {
name: "snapshot-cleanup",
task: "snapshot-cleanup",
cron: "30 3 * * *",
groups: ["default"],
retain: 0,
concurrency: 1,
},
},
opts({ dependsOn: [longhorn] }),
);
// Returns blocks deleted inside a volume (e.g. expired Prometheus data) to the
// disk. Runs after snapshot-cleanup, since trim can't reclaim valid snapshots.
// Docs: https://longhorn.io/docs/1.12.0/nodes-and-volumes/volumes/trim-filesystem/
new k8s.apiextensions.CustomResource(
"longhorn-filesystem-trim",
{
apiVersion: "longhorn.io/v1beta2",
kind: "RecurringJob",
metadata: { name: "filesystem-trim", namespace: "longhorn-system" },
spec: {
name: "filesystem-trim",
task: "filesystem-trim",
cron: "30 4 * * *",
groups: ["default"],
retain: 0,
concurrency: 1,
},
},
opts({ dependsOn: [longhorn] }),
);
// Patches Longhorn instances to use the mountend Longhorn storage on the worker nodes. // Patches Longhorn instances to use the mountend Longhorn storage on the worker nodes.
["k3s-worker-1", "k3s-worker-2", "k3s-worker-3"].forEach( ["k3s-worker-1", "k3s-worker-2", "k3s-worker-3"].forEach(
(nodeName) => (nodeName) =>
@@ -173,6 +230,70 @@ const longhorn = new k8s.helm.v3.Release(
), ),
); );
// ── Longhorn UI ───────────────────────────────────────────────────────────
// Docs: https://longhorn.io/docs/1.12.0/deploy/accessing-the-ui/longhorn-ingress-traefik/
// https://doc.traefik.io/traefik/reference/routing-configuration/http/middlewares/basicauth/
const longhornUiAuthSecret = new k8s.core.v1.Secret(
"longhorn-ui-basic-auth",
{
metadata: { name: "longhorn-ui-basic-auth", namespace: "longhorn-system" },
type: "kubernetes.io/basic-auth",
stringData: { username: longhornUiUser, password: longhornUiPassword },
},
opts({ dependsOn: [longhorn] }),
);
// Fixed name: the Ingress references it as <namespace>-<name>@kubernetescrd.
const longhornUiAuth = new k8s.apiextensions.CustomResource(
"longhorn-ui-auth",
{
apiVersion: "traefik.io/v1alpha1",
kind: "Middleware",
metadata: { name: "longhorn-ui-auth", namespace: "longhorn-system" },
spec: { basicAuth: { secret: longhornUiAuthSecret.metadata.name } },
},
opts(),
);
const longhornUiHost = pulumi.interpolate`longhorn.${domain}`;
new k8s.networking.v1.Ingress(
"longhorn-ui",
{
metadata: {
name: "longhorn-ui",
namespace: "longhorn-system",
annotations: {
"cert-manager.io/cluster-issuer": "letsencrypt-prod",
"traefik.ingress.kubernetes.io/router.middlewares":
"longhorn-system-longhorn-ui-auth@kubernetescrd",
},
},
spec: {
ingressClassName: "traefik",
tls: [{ hosts: [longhornUiHost], secretName: "longhorn-ui-tls" }],
rules: [
{
host: longhornUiHost,
http: {
paths: [
{
path: "/",
pathType: "Prefix",
backend: {
service: { name: "longhorn-frontend", port: { number: 80 } },
},
},
],
},
},
],
},
},
opts({ dependsOn: [longhorn, longhornUiAuth] }),
);
// ── kube-vip ──────────── // ── kube-vip ────────────
const kubeVipNamespace = "kube-system"; const kubeVipNamespace = "kube-system";
+3
View File
@@ -1,6 +1,9 @@
{ {
"name": "k8s-infra", "name": "k8s-infra",
"main": "index.ts", "main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": { "devDependencies": {
"@types/node": "^18", "@types/node": "^18",
"typescript": "^5.0.0" "typescript": "^5.0.0"
+2 -30
View File
@@ -1,32 +1,4 @@
# k8s-apps # 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. - 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.
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.<domain>`
- 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 <your-domain>
```
## CI/CD
Workflow: `../.gitea/workflows/04-deploy-k8s-apps.yaml`. Secret: `K8S_APPS_PULUMI_DEV_YAML`.
+22 -1
View File
@@ -10,7 +10,13 @@ const bootstrapRef = new pulumi.StackReference(
const kubeconfig = bootstrapRef.requireOutput("kubeconfig"); const kubeconfig = bootstrapRef.requireOutput("kubeconfig");
export const domain = config.requireSecret("domain"); export const domain = config.requireSecret("domain");
const k8sProvider = new k8s.Provider("k3s", { kubeconfig }); // Keep the kubeconfig stored in state. A changed API address would otherwise
// make Pulumi replace the provider and every resource in this stack.
const k8sProvider = new k8s.Provider(
"k3s",
{ kubeconfig },
{ ignoreChanges: ["kubeconfig"] },
);
const opts = (extras?: pulumi.ResourceOptions): pulumi.ResourceOptions => ({ const opts = (extras?: pulumi.ResourceOptions): pulumi.ResourceOptions => ({
provider: k8sProvider, provider: k8sProvider,
...extras, ...extras,
@@ -47,6 +53,7 @@ new k8s.apps.v1.Deployment(
}, },
spec: { spec: {
replicas: 1, replicas: 1,
strategy: { type: "Recreate" },
selector: { matchLabels: labels }, selector: { matchLabels: labels },
template: { template: {
metadata: { labels }, metadata: { labels },
@@ -70,6 +77,20 @@ new k8s.apps.v1.Deployment(
}, },
], ],
terminationGracePeriodSeconds: 5, terminationGracePeriodSeconds: 5,
tolerations: [
{
key: "node.kubernetes.io/unreachable",
operator: "Exists",
effect: "NoExecute",
tolerationSeconds: 30,
},
{
key: "node.kubernetes.io/not-ready",
operator: "Exists",
effect: "NoExecute",
tolerationSeconds: 30,
},
],
}, },
}, },
}, },
+3
View File
@@ -1,6 +1,9 @@
{ {
"name": "k8s-apps", "name": "k8s-apps",
"main": "index.ts", "main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"typescript": "^6.0.0" "typescript": "^6.0.0"
+1 -32
View File
@@ -1,34 +1,3 @@
# monitoring # 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. - 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.
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.<domain>` (`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 <password>
```
## CI/CD
Workflow: `../.gitea/workflows/05-deploy-monitoring.yaml`. Secret: `MONITORING_PULUMI_DEV_YAML`.
+7 -1
View File
@@ -18,7 +18,13 @@ const grafanaDbPassword = config.requireSecret("grafanaDbPassword");
const grafanaDbHost = config.requireSecret("grafanaDbHost"); const grafanaDbHost = config.requireSecret("grafanaDbHost");
const grafanaDbName = config.require("grafanaDbName"); const grafanaDbName = config.require("grafanaDbName");
const k8sProvider = new k8s.Provider("k3s", { kubeconfig }); // Keep the kubeconfig stored in state. A changed API address would otherwise
// make Pulumi replace the provider and every resource in this stack.
const k8sProvider = new k8s.Provider(
"k3s",
{ kubeconfig },
{ ignoreChanges: ["kubeconfig"] },
);
const monitoringNs = new k8s.core.v1.Namespace( const monitoringNs = new k8s.core.v1.Namespace(
"monitoring", "monitoring",
+3
View File
@@ -1,6 +1,9 @@
{ {
"name": "monitoring", "name": "monitoring",
"main": "index.ts", "main": "index.ts",
"scripts": {
"typecheck": "tsc --noEmit"
},
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"typescript": "^6.0.0" "typescript": "^6.0.0"
+33 -42
View File
@@ -1,20 +1,12 @@
# CLAUDE.md # 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. <!-- Notes for the human, stripped before this file reaches Claude:
- Start Claude Code sessions from the repository root: the permission rules and
hooks in .claude/settings.json only load from there.
- Keep this file to what Claude can't work out from the code. Stack-specific notes
go in the stack's own CLAUDE.md, which loads when Claude touches that stack. -->
## Project overview 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`.
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`.
## Deployment order & StackReferences ## Deployment order & StackReferences
@@ -23,42 +15,41 @@ proxmox-infra → k8s-bootstrap → k8s-infra
↘ k8s-apps → monitoring ↘ k8s-apps → monitoring
``` ```
- `k8s-bootstrap` reads VM IDs, Proxmox credentials, and the SSH private key from `proxmox-infra` 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` all read `kubeconfig` from `k8s-bootstrap` via StackReference (`requireOutput("kubeconfig")`) — never set `kubeconfig` as Pulumi config in these stacks. - `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` via StackReference. - `monitoring` additionally reads `domain` from `k8s-apps`.
- StackReference format: `${pulumi.getOrganization()}/<stack-name>/dev`. - StackReference format: `${pulumi.getOrganization()}/<stack-name>/dev`.
- A stack's outputs must exist (it must have been deployed) before a downstream stack referencing it will succeed.
A stack's outputs must exist (i.e. it must have been deployed) before any downstream stack referencing it will succeed.
## Shared conventions ## 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. - **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`. - **`Pulumi.dev.yaml`**: gitignored (contains the encryption salt). Never delete it or secrets become unrecoverable. CI restores it from a base64 Gitea secret `<STACK>_PULUMI_DEV_YAML`; after changing local config, remind me to update that secret.
- **Backend**: self-hosted Postgres state backend, set via `PULUMI_BACKEND_URL`. - **Environment**: `PULUMI_BACKEND_URL` (self-hosted Postgres backend) and `PULUMI_CONFIG_PASSPHRASE` must be set.
- Don't add a co-author when committing to git. - **CI**: PRs run `pulumi preview`. `01` and `03`–`05` deploy on push to `main`; `02` deploys only via manual dispatch. Automatic `01` deploys skip `pulumi refresh`, so run its workflow manually after changing VMs in the Proxmox GUI.
## Common commands (run from a stack directory) ## Git conventions
```bash Branch names, commit messages and PR titles follow @CONVENTIONS.md. The commit-msg hook needs `git config core.hooksPath .githooks` once per clone.
npm install
pulumi preview
pulumi up --yes
pulumi destroy
pulumi stack output
pulumi config
```
Requires `PULUMI_BACKEND_URL` and `PULUMI_CONFIG_PASSPHRASE` in the environment (or `pulumi login`). 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.
## CI/CD (Gitea Actions) 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.
One workflow per stack: `.gitea/workflows/0N-deploy-<stack>.yaml`, scoped to changes under that stack's directory. ## Live infrastructure
- **Pull request → `main`**: `pulumi preview` only. - 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.
- `01`/`02` (VM provisioning / cluster bootstrap — riskier to automate): deploy only via manual `workflow_dispatch`. - Code edits in the repo are fine without asking.
- `03`–`05`: deploy on push to `main` *or* `workflow_dispatch` — `pulumi refresh` then `pulumi up`. - Never recreate VMs to apply a change. Write code for a clean fresh install, plus separate manual steps for the running cluster.
- Each workflow restores `Pulumi.dev.yaml` from a base64-encoded Gitea secret (`<STACK>_PULUMI_DEV_YAML`). After changing local config, re-encode and update the secret:
```bash ## Looking things up
base64 -w 0 0N-<stack>/Pulumi.dev.yaml
``` - 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.
+2 -2
View File
@@ -31,7 +31,7 @@
``` ```
- **Type** — same list as branch types above (`feature`, `bug`, `enhancement`, `chore`, `docs`) - **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 - **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. - **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.
@@ -60,4 +60,4 @@ This repo uses Gitea Actions (see root `CLAUDE.md`); Gitea's merge commit reuses
- `Enhancement: Refactor k8s-bootstrap for clearer deployment order` - `Enhancement: Refactor k8s-bootstrap for clearer deployment order`
- `Chore: Upgrade Pulumi packages across all stacks` - `Chore: Upgrade Pulumi packages across all stacks`
Since `01`/`02` deploys are manual (`workflow_dispatch`) and `03`–`05` deploy on merge to `main`, a clear PR title also doubles as a quick changelog of what just went live. Since `02` deploys are manual (`workflow_dispatch`) and `01` and `03`–`05` deploy on merge to `main`, a clear PR title also doubles as a quick changelog of what just went live.
+15 -13
View File
@@ -38,15 +38,16 @@ proxmox-infra → k8s-bootstrap → k8s-infra
### 1. proxmox-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 | | VM | Role | Proxmox host |
| --- | --- | | --- | --- | --- |
| k3s-master-1 | master | | k3s-master-1 | master | pve-b550 |
| k3s-master-2 | master | | k3s-worker-1 | worker | pve-b550 |
| k3s-worker-1 | worker | | k3s-master-2 | master | pve-esprimo |
| k3s-master-3 | master | | k3s-worker-3 | worker | pve-esprimo |
| k3s-worker-2 | worker | | 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. 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 ### 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 ### 3. k8s-infra
@@ -63,7 +64,7 @@ Cluster-level infrastructure via Helm and `@pulumi/kubernetes`:
| Component | What it does | | Component | What it does |
| --- | --- | | --- | --- |
| NFS CSI Driver + `truenas-nfs` StorageClass | Dynamic NFS-backed PVCs from a TrueNAS share | | 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 | | 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) | | 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: Stack-specific notes:
1. **proxmox-infra** — set Proxmox API tokens, pfSense credentials, VM credentials/SSH public key, and a static IP per node. 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`. 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 the TrueNAS, Cloudflare, and `kubeVipAddress`/`kubeVipInterface` config. 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. 4. **k8s-apps** — set `domain`, the base domain used for ingress hostnames.
5. **monitoring** — set `grafanaAdminPassword`. 5. **monitoring** — set `grafanaAdminPassword`.
@@ -119,10 +120,11 @@ One workflow per stack, `.gitea/workflows/0N-deploy-<stack>.yaml`, scoped to cha
| Trigger | Stacks | Action | | Trigger | Stacks | Action |
| --- | --- | --- | | --- | --- | --- |
| PR → `main` | all | `pulumi preview` (read-only) | | PR → `main` | all | `pulumi preview` (read-only) |
| Push to `main` | 01 | `pulumi up` (no refresh) |
| Push to `main` | 03–05 | `pulumi refresh` + `pulumi up` | | Push to `main` | 03–05 | `pulumi refresh` + `pulumi up` |
| Manual dispatch | all | `pulumi refresh` + `pulumi up` | | Manual dispatch | all | `pulumi refresh` + `pulumi up` |
Stacks 01/02 (VM provisioning, cluster bootstrap) deploy **only** via manual dispatch — they're riskier to automate. Stack 02 (cluster bootstrap) deploys **only** via manual dispatch, because re-running it restarts the bootstrap sequence. Stack 01 (VM provisioning) skips the refresh on automatic deploys so a VM missing from Proxmox can't be recreated blank. After changing VMs in the Proxmox GUI, run its workflow manually to sync state.
### Required secrets ### Required secrets
@@ -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.
@@ -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 = `<controlPlaneVipAddress>/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 = `<master1Ip>:6443`, `<master2Ip>:6443`, `<master3Ip>:6443`.
5. Services → HAProxy → Frontend: add a frontend listening on `<controlPlaneVipAddress>: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.
+10
View File
@@ -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`)