import * as pulumi from "@pulumi/pulumi"; import * as k8s from "@pulumi/kubernetes"; const config = new pulumi.Config(); const bootstrapRef = new pulumi.StackReference( `${pulumi.getOrganization()}/k8s-bootstrap/dev`, ); const kubeconfig = bootstrapRef.requireOutput("kubeconfig"); export const nfsStorageClass = "truenas-nfs"; const truenasHost = config.requireSecret("truenasHost"); const truenasNfsPath = config.requireSecret("truenasNfsPath"); const cloudflareToken = config.requireSecret("cloudflareApiToken"); const letsencryptEmail = config.requireSecret("letsencryptEmail"); // Traefik's IP for web apps (ports 80 and 443). kube-vip announces it on the // LAN, and the app domains in pfSense's DNS Resolver must point to it. // This isn't the Kubernetes API address. That's controlPlaneVipAddress in // 02-k8s-bootstrap, which is provided by pfSense and HAProxy. const kubeVipAddress = config.requireSecret("kubeVipAddress"); const kubeVipInterface = config.require("kubeVipInterface"); const domain = config.requireSecret("domain"); const longhornUiUser = config.requireSecret("longhornUiUser"); const longhornUiPassword = config.requireSecret("longhornUiPassword"); // A fixed identifier makes kubeconfig changes (e.g. a new API address) provider // updates. Without it, they replace the provider and every resource in this // stack. Changing this value triggers that replacement, so never change it. const k8sProvider = new k8s.Provider("k3s", { kubeconfig, clusterIdentifier: "homelab-k3s", }); const opts = (extras?: pulumi.ResourceOptions): pulumi.ResourceOptions => ({ provider: k8sProvider, ...extras, }); // ── NFS CSI Driver ──────────────────────────────────────────────────────── const nfsCsiDriver = new k8s.helm.v3.Release( "nfs-csi-driver", { name: "csi-driver-nfs", chart: "csi-driver-nfs", repositoryOpts: { repo: "https://raw.githubusercontent.com/kubernetes-csi/csi-driver-nfs/master/charts", }, namespace: "kube-system", version: "4.12.0", values: { kubeletDir: "/var/lib/kubelet", }, }, opts(), ); new k8s.storage.v1.StorageClass( nfsStorageClass, { metadata: { name: nfsStorageClass }, provisioner: "nfs.csi.k8s.io", parameters: { server: truenasHost, share: truenasNfsPath, mountPermissions: "0", }, reclaimPolicy: "Retain", volumeBindingMode: "Immediate", allowVolumeExpansion: true, mountOptions: ["nfsvers=4.1"], }, opts({ dependsOn: [nfsCsiDriver] }), ); // ── cert-manager ────────────────────────────────────────────────────────── const certManager = new k8s.helm.v3.Release( "cert-manager", { name: "cert-manager", chart: "cert-manager", version: "v1.21.1", repositoryOpts: { repo: "https://charts.jetstack.io" }, namespace: "cert-manager", createNamespace: true, timeout: 600, values: { crds: { enabled: true }, }, }, opts(), ); // ── Cloudflare token secret + ClusterIssuer ─────────────────────────────── const cfSecret = new k8s.core.v1.Secret( "cloudflare-token", { metadata: { name: "cloudflare-api-token", namespace: "cert-manager" }, stringData: { "api-token": cloudflareToken }, }, opts({ dependsOn: [certManager] }), ); new k8s.apiextensions.CustomResource( "letsencrypt-prod", { apiVersion: "cert-manager.io/v1", kind: "ClusterIssuer", metadata: { name: "letsencrypt-prod" }, spec: { acme: { server: "https://acme-v02.api.letsencrypt.org/directory", email: letsencryptEmail, privateKeySecretRef: { name: "letsencrypt-prod-account-key" }, solvers: [ { dns01: { cloudflare: { apiTokenSecretRef: { name: cfSecret.metadata.name, key: "api-token", }, }, }, }, ], }, }, }, opts({ dependsOn: [certManager, cfSecret] }), ); // ── Longhorn ────────────────────────────────────────────────────────────── const longhorn = new k8s.helm.v3.Release( "longhorn", { name: "longhorn", chart: "longhorn", repositoryOpts: { repo: "https://charts.longhorn.io" }, namespace: "longhorn-system", createNamespace: true, version: "1.12.0", values: { defaultSettings: { defaultReplicaCount: 3, nodeDownPodDeletionPolicy: "delete-both-statefulset-and-deployment-pod", 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(), ); // 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. ["k3s-worker-1", "k3s-worker-2", "k3s-worker-3"].forEach( (nodeName) => new k8s.apiextensions.CustomResourcePatch( `${nodeName}-longhorn-disks`, { apiVersion: "longhorn.io/v1beta2", kind: "Node", metadata: { name: nodeName, namespace: "longhorn-system", annotations: { "pulumi.com/patchForce": "true" }, }, spec: { disks: { "longhorn-extra": { allowScheduling: true, diskDriver: "", diskType: "filesystem", evictionRequested: false, path: "/mnt/longhorn-extra", storageReserved: 0, tags: [], }, }, }, }, opts({ dependsOn: [longhorn] }), ), ); // ── 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 -@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 ──────────── const kubeVipNamespace = "kube-system"; const controlPlaneTolerations = [ { key: "node-role.kubernetes.io/master", effect: "NoSchedule" }, { key: "node-role.kubernetes.io/control-plane", effect: "NoSchedule" }, ]; // Keeps regular workloads off the master nodes; kube-vip and // kube-vip-cloud-provider below explicitly tolerate these same taints. ["k3s-master-1", "k3s-master-2", "k3s-master-3"].forEach((nodeName) => { new k8s.core.v1.NodePatch( `${nodeName}-control-plane-taint`, { metadata: { name: nodeName, annotations: { "pulumi.com/patchForce": "true" }, }, spec: { taints: controlPlaneTolerations }, }, opts(), ); }); const kubeVipServiceAccount = new k8s.core.v1.ServiceAccount( "kube-vip", { metadata: { name: "kube-vip", namespace: kubeVipNamespace } }, opts(), ); const kubeVipClusterRole = new k8s.rbac.v1.ClusterRole( "kube-vip-role", { metadata: { name: "system:kube-vip-role", annotations: { "rbac.authorization.kubernetes.io/autoupdate": "true" }, }, rules: [ { apiGroups: [""], resources: ["services/status"], verbs: ["update"] }, { apiGroups: [""], resources: ["services", "endpoints"], verbs: ["list", "get", "watch", "update"], }, { apiGroups: [""], resources: ["nodes"], verbs: ["list", "get", "watch", "update", "patch"], }, { apiGroups: ["coordination.k8s.io"], resources: ["leases"], verbs: ["list", "get", "watch", "update", "create"], }, { apiGroups: ["discovery.k8s.io"], resources: ["endpointslices"], verbs: ["list", "get", "watch", "update"], }, { apiGroups: [""], resources: ["pods"], verbs: ["list"] }, ], }, opts(), ); const kubeVipClusterRoleBinding = new k8s.rbac.v1.ClusterRoleBinding( "kube-vip-binding", { metadata: { name: "system:kube-vip-binding" }, roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "ClusterRole", name: kubeVipClusterRole.metadata.name, }, subjects: [ { kind: "ServiceAccount", name: kubeVipServiceAccount.metadata.name, namespace: kubeVipNamespace, }, ], }, opts(), ); const kubeVipLabels = { name: "kube-vip-ds" }; const kubeVip = new k8s.apps.v1.DaemonSet( "kube-vip", { metadata: { name: "kube-vip-ds", namespace: kubeVipNamespace }, spec: { selector: { matchLabels: kubeVipLabels }, template: { metadata: { labels: kubeVipLabels }, spec: { serviceAccountName: kubeVipServiceAccount.metadata.name, hostNetwork: true, tolerations: [ ...controlPlaneTolerations.map((t) => ({ ...t, operator: "Exists", })), { effect: "NoExecute", operator: "Exists" }, ], containers: [ { name: "kube-vip", image: "ghcr.io/kube-vip/kube-vip:v1.2.0", imagePullPolicy: "Always", args: ["manager"], env: [ { name: "vip_arp", value: "true" }, { name: "vip_interface", value: kubeVipInterface }, { name: "vip_subnet", value: "32" }, { name: "cp_enable", value: "false" }, { name: "svc_enable", value: "true" }, { name: "svc_election", value: "true" }, { name: "vip_leaderelection", value: "true" }, ], securityContext: { capabilities: { add: ["NET_ADMIN", "NET_RAW"] }, }, }, ], }, }, }, }, opts({ dependsOn: [kubeVipClusterRoleBinding] }), ); // -- kube-vip-cloud-provider: allocates LoadBalancer IPs for Services on bare-metal // k3s (replacing the disabled ServiceLB). The DaemonSet above only *announces* IPs // via ARP; this controller is what actually assigns them to Service.status. const cloudProviderServiceAccount = new k8s.core.v1.ServiceAccount( "kube-vip-cloud-controller", { metadata: { name: "kube-vip-cloud-controller", namespace: kubeVipNamespace, }, }, opts(), ); const cloudProviderClusterRole = new k8s.rbac.v1.ClusterRole( "kube-vip-cloud-controller-role", { metadata: { name: "system:kube-vip-cloud-controller-role", annotations: { "rbac.authorization.kubernetes.io/autoupdate": "true" }, }, rules: [ { apiGroups: ["coordination.k8s.io"], resources: ["leases"], verbs: ["get", "create", "update", "list", "watch"], }, { apiGroups: [""], resources: [ "configmaps", "endpoints", "events", "services/status", "leases", ], verbs: ["*"], }, { apiGroups: [""], resources: ["nodes", "services"], verbs: ["list", "get", "watch", "update"], }, ], }, opts(), ); const cloudProviderClusterRoleBinding = new k8s.rbac.v1.ClusterRoleBinding( "kube-vip-cloud-controller-binding", { metadata: { name: "system:kube-vip-cloud-controller-binding" }, roleRef: { apiGroup: "rbac.authorization.k8s.io", kind: "ClusterRole", name: cloudProviderClusterRole.metadata.name, }, subjects: [ { kind: "ServiceAccount", name: cloudProviderServiceAccount.metadata.name, namespace: kubeVipNamespace, }, ], }, opts(), ); const kubeVipCloudProviderLabels = { app: "kube-vip", component: "kube-vip-cloud-provider", }; // IP pool the cloud-provider allocates from — scoped to exactly the one VIP we // want, so it can never hand the address to some other LoadBalancer Service. const kubeVipPool = new k8s.core.v1.ConfigMap( "kube-vip-pool", { metadata: { name: "kubevip", namespace: kubeVipNamespace }, data: { "range-global": pulumi.interpolate`${kubeVipAddress}-${kubeVipAddress}`, }, }, opts(), ); const kubeVipCloudProvider = new k8s.apps.v1.Deployment( "kube-vip-cloud-provider", { metadata: { name: "kube-vip-cloud-provider", namespace: kubeVipNamespace }, spec: { replicas: 1, selector: { matchLabels: kubeVipCloudProviderLabels, }, template: { metadata: { labels: kubeVipCloudProviderLabels, }, spec: { serviceAccountName: cloudProviderServiceAccount.metadata.name, tolerations: controlPlaneTolerations, containers: [ { name: "kube-vip-cloud-provider", image: "ghcr.io/kube-vip/kube-vip-cloud-provider:v0.0.12", imagePullPolicy: "Always", command: [ "/kube-vip-cloud-provider", "--leader-elect-resource-name=kube-vip-cloud-controller", ], }, ], }, }, }, }, opts({ dependsOn: [cloudProviderClusterRoleBinding, kubeVipPool] }), ); // Assigns kubeVipAddress to the Traefik Service that k3s creates. new k8s.core.v1.ServicePatch( "traefik-vip", { metadata: { name: "traefik", namespace: kubeVipNamespace, annotations: { "kube-vip.io/loadbalancerIPs": kubeVipAddress }, }, spec: { loadBalancerIP: kubeVipAddress }, }, opts({ dependsOn: [kubeVip, kubeVipCloudProvider] }), );