infra/stacks/proxmox-csi/modules/proxmox-csi/main.tf
Viktor Barzin 8ed427a7e4 cloud-init: hands-off k8s worker provisioning + 5 bug fixes
Goal: re-clone the worker template, boot, and have it appear as `kubectl
get nodes …Ready` with no manual steps. Adds `scripts/provision-k8s-worker
NAME VMID IP` and rebuilds the cloud-init pipeline that was failing five
distinct ways on a clean boot.

Bugs fixed (all hit during the k8s-node5 + k8s-node6 builds today):

1. `indent(6, containerd_config_update_command)` indented the bodies of
   `cat >> /etc/containerd/config.toml <<'CONTAINERD_GC'` heredocs, so
   [plugins.*] TOML sections landed in /etc/containerd/config.toml at
   col 6 — containerd refused to parse them. Source is now a normal
   .sh file (`modules/create-template-vm/k8s-node-containerd-setup.sh`)
   base64-embedded into `write_files`; YAML whitespace never touches
   the heredoc bodies.

2. The same script tried to `cat >> /etc/containerd/config.toml`
   `[plugins."io.containerd.gc.v1.scheduler"]` etc., which containerd
   v2.2.4's `config default` ALREADY emits. Result: `toml: table …
   already exists`. Patched with sed-in-place overrides instead.

3. Kubelet tuning (sed against /var/lib/kubelet/config.yaml) ran from
   the containerd setup script — BEFORE `kubeadm join` writes that
   file. Sed aborted with "No such file or directory", `set -e` killed
   the script, post-script cloud-init steps kept going (cloud-init
   doesn't stop on runcmd failure). Split into a dedicated
   `k8s-node-post-join-tune.sh` invoked AFTER kubeadm join.

4. cloud_init.yaml fallocate'd a 4G swapfile and `swapon`'d it BEFORE
   kubeadm join. kubelet defaults to failSwapOn=true → exited 1
   immediately. Replaced the swap setup with `swapoff -a` (node4
   already runs this way and the cluster is fine).

5. Without `hostname:` in the shared user-data snippet, Proxmox's
   auto-generated meta-data does NOT include local-hostname when
   `cicustom user=…` is set — so cloud-init falls back to the cloud
   image's default `ubuntu` and `kubeadm join` registers the wrong
   node name. `provision-k8s-worker` now writes a per-node
   `<NAME>-meta.yaml` snippet and passes both via
   `cicustom user=…,meta=…`.

Other improvements rolled in while fixing the above:

- `ssh_public_key` read from Vault (`secret/viktor.ssh_public_key`,
  added today) instead of `var.ssh_public_key`. The last
  `terragrunt apply` was run with that var empty, leaving the snippet's
  `ssh_authorized_keys` with a single blank entry; the wizard user
  was effectively locked out of every fresh node.
- `cloud_init.yaml` adds `/etc/systemd/resolved.conf.d/global-dns.conf`
  with `DNS=8.8.8.8 1.1.1.1, FallbackDNS=10.0.20.201`. Without it,
  systemd-resolved only consulted Technitium (link-level), which
  returns NXDOMAIN for `forgejo.viktorbarzin.me` — kubelet pulls from
  the Forgejo registry then failed DNS until I patched it manually
  on node5.
- k8s apt repo bumped v1.32 → v1.34 (matches cluster).
- The containerd setup script now creates hosts.toml for forgejo,
  quay, registry.k8s.io in addition to docker.io + ghcr.io. node3/4
  had these added by hand post-bootstrap; now they're baked in.
- `config_path` sed matches both `""` (containerd v1) and `''`
  (containerd v2.x). Without the v2 match, the certs.d mirror dir was
  silently ignored.
- `proxmox-csi` node map adds k8s-node5 + k8s-node6 entries so CSI
  topology labels (region/zone, max-volume-attachments=28) apply on
  next `tg apply`.
- `stacks/infra/main.tf` shed the 160-line inline containerd setup
  heredoc — that whole thing now lives in the module as a .sh file.

Known unsolved gaps (deferred):

- iscsid restart hangs ~90s on first boot before SIGKILL releases it
  (systemd-resolved restart kicks iscsid via dependency). Adds wall-
  clock time but doesn't block the join.
- `provision-k8s-worker` doesn't run `tg apply` on `proxmox-csi`
  afterward, so the CSI topology labels need a manual apply after
  the node joins. Solving cleanly needs the CSI map to derive from
  `kubectl get nodes` instead of a static local — separate work.
- `var.containerd_config_update_command` is now ignored when
  is_k8s_template=true (replaced by the bundled .sh file). Variable
  kept with a deprecation note to avoid breaking other call sites.

E2E proof: k8s-node6 (VMID 206) boots hands-off from
`provision-k8s-worker k8s-node6 206 10.0.20.106` and appears as
`kubectl get nodes …Ready` ~7 min later (most of which is the apt
package_upgrade — separate optimization).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 11:52:00 +00:00

237 lines
7.4 KiB
HCL

resource "kubernetes_namespace" "proxmox_csi" {
metadata {
name = "proxmox-csi"
labels = {
tier = var.tier
"resource-governance/custom-quota" = "true"
"keel.sh/enrolled" = "true"
}
}
lifecycle {
# KYVERNO_LIFECYCLE_V1: goldilocks-vpa-auto-mode ClusterPolicy stamps this label on every namespace
ignore_changes = [metadata[0].labels["goldilocks.fairwinds.com/vpa-update-mode"]]
}
}
resource "helm_release" "proxmox_csi" {
namespace = kubernetes_namespace.proxmox_csi.metadata[0].name
create_namespace = false
name = "proxmox-csi-plugin"
atomic = true
timeout = 300
repository = "oci://ghcr.io/sergelogvinov/charts"
chart = "proxmox-csi-plugin"
version = "0.5.6"
values = [yamlencode({
config = {
clusters = [{
url = var.proxmox_url
insecure = true
token_id = var.proxmox_token_id
token_secret = var.proxmox_token_secret
region = var.proxmox_cluster_name
}]
}
# StorageClass for block volumes on existing HDD thin pool.
# `resize.topolvm.io/enabled=true` opts the SC into pvc-autoresizer:
# without it, the controller filters this SC out and never patches its
# PVCs no matter how full they get. Required alongside the per-PVC
# threshold/increase/storage_limit annotations.
storageClass = [
{
name = "proxmox-lvm"
storage = "local-lvm"
reclaimPolicy = "Retain"
fstype = "ext4"
ssd = false
cache = "none"
volumeBindingMode = "WaitForFirstConsumer"
allowVolumeExpansion = true
annotations = {
"resize.topolvm.io/enabled" = "true"
}
},
{
name = "proxmox-lvm-encrypted"
storage = "local-lvm"
reclaimPolicy = "Retain"
fstype = "ext4"
ssd = false
cache = "none"
volumeBindingMode = "WaitForFirstConsumer"
allowVolumeExpansion = true
annotations = {
"resize.topolvm.io/enabled" = "true"
}
extraParameters = {
"csi.storage.k8s.io/node-stage-secret-name" = "proxmox-csi-encryption"
"csi.storage.k8s.io/node-stage-secret-namespace" = "kube-system"
"csi.storage.k8s.io/node-expand-secret-name" = "proxmox-csi-encryption"
"csi.storage.k8s.io/node-expand-secret-namespace" = "kube-system"
}
},
]
controller = {
replicas = 2
resources = {
requests = { cpu = "10m", memory = "32Mi" }
limits = { memory = "64Mi" }
}
}
# LUKS2 Argon2id key derivation needs ~1GiB memory (memory id=712).
# Request bumped from 64Mi → 1024Mi (2026-05-23) so the pod is reserved
# for the unlock burst instead of risking OOM under node pressure.
node = {
plugin = {
resources = {
requests = { cpu = "10m", memory = "1024Mi" }
limits = { memory = "1280Mi" }
}
}
}
})]
}
# Topology labels on K8s nodes — required for Proxmox CSI to map nodes to Proxmox VMs.
# region = Proxmox cluster name, zone = Proxmox node name (where the VM runs).
# All our VMs run on the single Proxmox node "pve".
locals {
k8s_nodes = {
"k8s-master" = { vmid = 200, proxmox_node = "pve" }
"k8s-node1" = { vmid = 201, proxmox_node = "pve" }
"k8s-node2" = { vmid = 202, proxmox_node = "pve" }
"k8s-node3" = { vmid = 203, proxmox_node = "pve" }
"k8s-node4" = { vmid = 204, proxmox_node = "pve" }
"k8s-node5" = { vmid = 205, proxmox_node = "pve" }
"k8s-node6" = { vmid = 206, proxmox_node = "pve" }
}
}
resource "null_resource" "node_labels" {
for_each = local.k8s_nodes
# max-volume-attachments: capped at 28 (4 below plugin's hard ceiling of 30,
# see VolumesPerNodeHardLimit in sergelogvinov/proxmox-csi-plugin pkg/csi/node.go).
# Default is 24; bumping to 28 gives ~4-PVC headroom per node while keeping
# 2 slots for recovery (boot disk + transient attach during reschedule).
# Without this label the plugin reports 24 and node1 cascades through that
# ceiling during evictions — see post-mortem 2026-05-25.
provisioner "local-exec" {
command = <<-EOT
kubectl --kubeconfig=${var.kube_config_path} label node ${each.key} \
topology.kubernetes.io/region=${var.proxmox_cluster_name} \
topology.kubernetes.io/zone=${each.value.proxmox_node} \
node.csi.proxmox.sinextra.dev/name=${each.key} \
csi.proxmox.sinextra.dev/max-volume-attachments=28 \
--overwrite
EOT
}
triggers = {
region = var.proxmox_cluster_name
zone = each.value.proxmox_node
max_volumes = "28"
}
}
# --- RBAC for PVE host snapshot restore script ---
# Provides kubectl access from the Proxmox host for the lvm-pvc-snapshot restore subcommand.
# Minimal permissions: read PVs/PVCs/Pods, scale Deployments/StatefulSets.
resource "kubernetes_service_account" "pve_snapshot_admin" {
metadata {
name = "pve-snapshot-admin"
namespace = "kube-system"
}
}
resource "kubernetes_secret" "pve_snapshot_admin_token" {
metadata {
name = "pve-snapshot-admin-token"
namespace = "kube-system"
annotations = {
"kubernetes.io/service-account.name" = kubernetes_service_account.pve_snapshot_admin.metadata[0].name
}
}
type = "kubernetes.io/service-account-token"
}
resource "kubernetes_cluster_role" "pve_snapshot_admin" {
metadata {
name = "pve-snapshot-admin"
}
rule {
api_groups = [""]
resources = ["persistentvolumes", "persistentvolumeclaims", "pods"]
verbs = ["get", "list"]
}
rule {
api_groups = ["apps"]
resources = ["deployments", "statefulsets", "replicasets"]
verbs = ["get", "list", "update", "patch"]
}
rule {
api_groups = ["apps"]
resources = ["deployments/scale", "statefulsets/scale"]
verbs = ["get", "update", "patch"]
}
}
resource "kubernetes_cluster_role_binding" "pve_snapshot_admin" {
metadata {
name = "pve-snapshot-admin"
}
role_ref {
api_group = "rbac.authorization.k8s.io"
kind = "ClusterRole"
name = kubernetes_cluster_role.pve_snapshot_admin.metadata[0].name
}
subject {
kind = "ServiceAccount"
name = kubernetes_service_account.pve_snapshot_admin.metadata[0].name
namespace = "kube-system"
}
}
# --- ExternalSecret for LUKS encryption passphrase ---
# Creates K8s Secret "proxmox-csi-encryption" in kube-system from Vault KV.
# Referenced by the proxmox-lvm-encrypted StorageClass for node-stage and node-expand.
resource "kubernetes_manifest" "external_secret_encryption" {
manifest = {
apiVersion = "external-secrets.io/v1beta1"
kind = "ExternalSecret"
metadata = {
name = "proxmox-csi-encryption"
namespace = "kube-system"
}
spec = {
refreshInterval = "1h"
secretStoreRef = {
kind = "ClusterSecretStore"
name = "vault-kv"
}
target = {
name = "proxmox-csi-encryption"
creationPolicy = "Owner"
deletionPolicy = "Retain"
}
data = [{
secretKey = "encryption-passphrase"
remoteRef = {
key = "viktor"
property = "proxmox_csi_encryption_passphrase"
}
}]
}
}
}