Files
kasun 2327e42cdd
Deploy k8s Bootstrap / Bootstrap k3s Cluster (pull_request) Skipped
Deploy k8s Bootstrap / Pulumi Preview (pull_request) Successful in 31s
Secret Scan / Betterleaks (pull_request) Successful in 5s
feature(k8s-bootstrap): remove the CI SSH key from nodes after bootstrap
The key is only needed during bootstrap, but it stayed on every node with
passwordless sudo. A final step now removes it once all SSH steps are done.
Needs the ciRunnerPublicKey output from proxmox-infra, so deploy that first.

Also moves the repeated start, SSH-wait and join commands into helpers.
Resource names are unchanged, so nothing re-runs on the live cluster.
2026-12-06 02:33:21 +01:00

499 lines
16 KiB
TypeScript

import * as pulumi from "@pulumi/pulumi";
import * as command from "@pulumi/command";
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(
`${pulumi.getOrganization()}/proxmox-infra/dev`,
);
const pve1Endpoint = infraRef.requireOutput(
"pve1Endpoint",
) as pulumi.Output<string>;
const pve1ApiToken = infraRef.requireOutput(
"pve1ApiToken",
) as pulumi.Output<string>;
const pve2Endpoint = infraRef.requireOutput(
"pve2Endpoint",
) as pulumi.Output<string>;
const pve2ApiToken = infraRef.requireOutput(
"pve2ApiToken",
) as pulumi.Output<string>;
const pve3Endpoint = infraRef.requireOutput(
"pve3Endpoint",
) as pulumi.Output<string>;
const pve3ApiToken = infraRef.requireOutput(
"pve3ApiToken",
) as pulumi.Output<string>;
// Node IPs — static DHCP leases set in the router
const master1Ip = infraRef.requireOutput("master1Ip");
const master2Ip = infraRef.requireOutput("master2Ip");
const master3Ip = infraRef.requireOutput("master3Ip");
const worker1Ip = infraRef.requireOutput("worker1Ip");
const worker2Ip = infraRef.requireOutput("worker2Ip");
const worker3Ip = infraRef.requireOutput("worker3Ip");
// Pre-shared k3s cluster token
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`;
const secretsEncryptionArgs =
"--secrets-encryption --secrets-encryption-provider=secretbox";
// 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}`;
}
// Kubernetes API address (port 6443), used by kubectl, Pulumi and joining nodes.
// pfSense holds this IP, and HAProxy forwards connections to the masters, so
// the API doesn't depend on a single master.
// This isn't kubeVipAddress in 03-k8s-infra, which is Traefik's IP for web apps.
const controlPlaneVipAddress = config.requireSecret("controlPlaneVipAddress");
// VM IDs and CI runner SSH key — read from proxmox-infra stack outputs
const vmIdsOutput = infraRef.requireOutput("vmIds") as pulumi.Output<
Record<string, number>
>;
const ciRunnerPrivateKey = infraRef.requireOutput(
"ciRunnerPrivateKey",
) as pulumi.Output<string>;
const ciRunnerPublicKey = infraRef.requireOutput(
"ciRunnerPublicKey",
) as pulumi.Output<string>;
const master1VmId = vmIdsOutput.apply((ids) => String(ids.master1));
const master2VmId = vmIdsOutput.apply((ids) => String(ids.master2));
const master3VmId = vmIdsOutput.apply((ids) => String(ids.master3));
const worker1VmId = vmIdsOutput.apply((ids) => String(ids.worker1));
const worker2VmId = vmIdsOutput.apply((ids) => String(ids.worker2));
const worker3VmId = vmIdsOutput.apply((ids) => String(ids.worker3));
// SSH connection helper
function conn(
ip: pulumi.Input<string>,
): command.types.input.remote.ConnectionArgs {
return { host: ip, user: "ubuntu", privateKey: ciRunnerPrivateKey };
}
// ---------------------------------------------------------------------------
// Step 1: Start all VMs (VMs are owned by proxmox-infra)
// ---------------------------------------------------------------------------
// 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`;
}
function startVm(
name: string,
create: pulumi.Input<string>,
apiToken: pulumi.Input<string>,
vmId: pulumi.Input<string>,
): command.local.Command {
return new command.local.Command(name, {
create,
environment: { PVE_API_TOKEN: apiToken },
triggers: [vmId],
interpreter: ["/bin/bash", "-c"],
});
}
const startMaster1 = startVm(
"start-master-1",
startVmScript(pve1Endpoint, "pve1", "pve", master1VmId),
pve1ApiToken,
master1VmId,
);
const startMaster2 = startVm(
"start-master-2",
startVmScript(pve3Endpoint, "pve3", "pve", master2VmId),
pve3ApiToken,
master2VmId,
);
const startWorker1 = startVm(
"start-worker-1",
startVmScript(pve1Endpoint, "pve1", "pve", worker1VmId),
pve1ApiToken,
worker1VmId,
);
const startMaster3 = startVm(
"start-master-3",
startVmScript(pve2Endpoint, "pve2", "pve-bckp", master3VmId),
pve2ApiToken,
master3VmId,
);
const startWorker2 = startVm(
"start-worker-2",
startVmScript(pve2Endpoint, "pve2", "pve-bckp", worker2VmId),
pve2ApiToken,
worker2VmId,
);
const startWorker3 = startVm(
"start-worker-3",
startVmScript(pve3Endpoint, "pve3", "pve", worker3VmId),
pve3ApiToken,
worker3VmId,
);
const allStarts = [
startMaster1,
startMaster2,
startMaster3,
startWorker1,
startWorker2,
startWorker3,
];
// ---------------------------------------------------------------------------
// Step 2: Wait for SSH on master-1, install k3s
// ---------------------------------------------------------------------------
// Succeeds once port 22 answers, polling every 5 s for up to 5 min.
function waitSsh(
name: string,
ip: pulumi.Input<string>,
vmId: pulumi.Input<string>,
dependsOn: pulumi.ResourceOptions["dependsOn"],
): command.local.Command {
return new command.local.Command(
name,
{
create: pulumi.interpolate`for i in $(seq 1 60); do (timeout 5 bash -c "echo > /dev/tcp/${ip}/22") 2>/dev/null && exit 0; sleep 5; done; exit 1`,
triggers: [vmId],
interpreter: ["/bin/bash", "-c"],
},
{ dependsOn },
);
}
const waitMaster1Ssh = waitSsh(
"wait-ssh-master-1",
master1Ip,
master1VmId,
allStarts,
);
const installMaster1 = new command.remote.Command(
"install-k3s-master-1",
{
connection: conn(master1Ip),
create: k3sInstallScript(
"",
pulumi.interpolate`server --cluster-init --tls-san ${master1Ip} --tls-san ${controlPlaneVipAddress} --disable servicelb ${secretsEncryptionArgs} --node-name k3s-master-1`,
),
stdin: k3sToken,
triggers: [master1VmId],
},
{ dependsOn: [waitMaster1Ssh] },
);
const waitK3sMaster1Ready = new command.remote.Command(
"wait-k3s-master-1-ready",
{
connection: conn(master1Ip),
create: `for i in $(seq 1 60); do sudo kubectl --kubeconfig /etc/rancher/k3s/k3s.yaml get node k3s-master-1 --no-headers 2>/dev/null | grep -q " Ready" && exit 0; sleep 10; done; exit 1`,
triggers: [master1VmId],
},
{ dependsOn: [installMaster1] },
);
// ---------------------------------------------------------------------------
// Step 3: Confirm the control-plane VIP is actually reachable before anyone
// else joins, so master-2/master-3 and every worker join through the VIP
// instead of master1Ip directly. The VIP itself is NOT managed here (or by
// any Pulumi stack) — it's a pfSense IP Alias Virtual IP with HAProxy
// TCP-load-balancing 6443 across all three masters, set up manually (see
// "pfSense one-time setup" in this stack's CLAUDE.md). This intentionally
// avoids a second kube-vip/ARP-based VIP for something as critical as API
// access — 03-k8s-infra's existing kube-vip DaemonSet already handles
// Service/LoadBalancer VIPs (e.g. Traefik) separately, entirely inside the
// cluster.
// ---------------------------------------------------------------------------
const waitControlPlaneVipReady = new command.remote.Command(
"wait-control-plane-vip-ready",
{
connection: conn(master1Ip),
// 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],
},
{ dependsOn: [waitK3sMaster1Ready] },
);
// ---------------------------------------------------------------------------
// Step 4: Wait for SSH on remaining masters, join cluster via the VIP
// ---------------------------------------------------------------------------
const waitMaster2Ssh = waitSsh("wait-ssh-master-2", master2Ip, master2VmId, [
waitK3sMaster1Ready,
]);
const waitMaster3Ssh = waitSsh("wait-ssh-master-3", master3Ip, master3VmId, [
waitK3sMaster1Ready,
]);
// Joins an extra control-plane node through the VIP. Every master must get the
// same server flags, so they live here, not at the call site.
function joinMaster(
nodeName: string,
ip: pulumi.Input<string>,
vmId: pulumi.Input<string>,
dependsOn: pulumi.ResourceOptions["dependsOn"],
): command.remote.Command {
return new command.remote.Command(
`join-${nodeName}`,
{
connection: conn(ip),
create: k3sInstallScript(
"",
pulumi.interpolate`server --server https://${controlPlaneVipAddress}:6443 --disable servicelb ${secretsEncryptionArgs} --node-name ${nodeName}`,
),
stdin: k3sToken,
triggers: [vmId],
},
{ dependsOn },
);
}
const joinMaster2 = joinMaster("k3s-master-2", master2Ip, master2VmId, [
waitMaster2Ssh,
waitControlPlaneVipReady,
]);
const joinMaster3 = joinMaster("k3s-master-3", master3Ip, master3VmId, [
waitMaster3Ssh,
waitControlPlaneVipReady,
joinMaster2,
]);
// ---------------------------------------------------------------------------
// Step 5: Join worker nodes via the VIP
// ---------------------------------------------------------------------------
const waitWorker1Ssh = waitSsh("wait-ssh-worker-1", worker1Ip, worker1VmId, [
joinMaster3,
]);
const waitWorker2Ssh = waitSsh("wait-ssh-worker-2", worker2Ip, worker2VmId, [
joinMaster3,
]);
const waitWorker3Ssh = waitSsh("wait-ssh-worker-3", worker3Ip, worker3VmId, [
joinMaster3,
]);
function joinWorker(
nodeName: string,
ip: pulumi.Input<string>,
vmId: pulumi.Input<string>,
dependsOn: pulumi.ResourceOptions["dependsOn"],
): command.remote.Command {
return new command.remote.Command(
`join-${nodeName}`,
{
connection: conn(ip),
create: k3sInstallScript(
pulumi.interpolate`K3S_URL=https://${controlPlaneVipAddress}:6443`,
`--node-name ${nodeName}`,
),
stdin: k3sToken,
triggers: [vmId],
},
{ dependsOn },
);
}
const joinWorker1 = joinWorker("k3s-worker-1", worker1Ip, worker1VmId, [
waitWorker1Ssh,
]);
const joinWorker2 = joinWorker("k3s-worker-2", worker2Ip, worker2VmId, [
waitWorker2Ssh,
]);
const joinWorker3 = joinWorker("k3s-worker-3", worker3Ip, worker3VmId, [
waitWorker3Ssh,
]);
// ---------------------------------------------------------------------------
// Step 6: Format and mount Longhorn disks
// ---------------------------------------------------------------------------
const workers = [worker1Ip, worker2Ip, worker3Ip];
const workerSshReady = [waitWorker1Ssh, waitWorker2Ssh, waitWorker3Ssh];
const longhornMounts = workers.map((worker, i) => {
return new command.remote.Command(
`mount-longhorn-disk-${i}`,
{
connection: conn(worker),
create: `set -euo pipefail;
DISK_ID=$(ls /dev/disk/by-id/ | grep 'scsi1');
[ "$(echo "$DISK_ID" | wc -l)" -eq 1 ];
DISK_PATH="/dev/disk/by-id/$DISK_ID";
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;
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;
mountpoint -q /mnt/longhorn-extra;
df -h /mnt/longhorn-extra`,
},
{ dependsOn: workerSshReady[i] },
);
});
// ---------------------------------------------------------------------------
// Step 7: Read kubeconfig from master-1, patch server URL to the VIP
// ---------------------------------------------------------------------------
const getKubeconfig = new command.remote.Command(
"get-kubeconfig",
{
connection: conn(master1Ip),
create: `sudo cat /etc/rancher/k3s/k3s.yaml`,
triggers: [master1VmId],
},
{
dependsOn: [joinWorker1, joinWorker2, joinWorker3],
additionalSecretOutputs: ["stdout"],
},
);
// ---------------------------------------------------------------------------
// Step 8: Install additional packages
// ---------------------------------------------------------------------------
const allVms = [
{
id: master1VmId,
ip: master1Ip,
name: "master-1",
readiness: waitMaster1Ssh,
},
{
id: master2VmId,
ip: master2Ip,
name: "master-2",
readiness: waitMaster2Ssh,
},
{
id: master3VmId,
ip: master3Ip,
name: "master-3",
readiness: waitMaster3Ssh,
},
{
id: worker1VmId,
ip: worker1Ip,
name: "worker-1",
readiness: waitWorker1Ssh,
},
{
id: worker2VmId,
ip: worker2Ip,
name: "worker-2",
readiness: waitWorker2Ssh,
},
{
id: worker3VmId,
ip: worker3Ip,
name: "worker-3",
readiness: waitWorker3Ssh,
},
];
const packageInstalls = allVms.map(
({ id, ip, name, readiness }) =>
new command.remote.Command(
`install-packages-${name}`,
{
connection: conn(ip),
// 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],
},
{ dependsOn: readiness },
),
);
// ---------------------------------------------------------------------------
// Step 9: Remove the CI runner's SSH key from every node
// ---------------------------------------------------------------------------
// The key is only needed for the steps above, so it shouldn't stay valid on
// the nodes afterwards. A rebuilt VM gets it again from cloud-init, so a fresh
// bootstrap still works.
const sshSteps = [getKubeconfig, ...longhornMounts, ...packageInstalls];
const revokeCiKeyScript = `set -euo pipefail
IFS= read -r KEY || true
[ -n "$KEY" ]
f="$HOME/.ssh/authorized_keys"
grep -vxF -- "$KEY" "$f" > "$f.new" || [ $? -eq 1 ]
[ -s "$f.new" ]
chmod 600 "$f.new"
mv "$f.new" "$f"
if grep -qxF -- "$KEY" "$f"; then exit 1; fi`;
allVms.forEach(({ id, ip, name }) => {
new command.remote.Command(
`revoke-ci-key-${name}`,
{
connection: conn(ip),
create: revokeCiKeyScript,
stdin: ciRunnerPublicKey,
triggers: [id],
},
{ dependsOn: sshSteps },
);
});
export const kubeconfig = pulumi.secret(
pulumi
.all([getKubeconfig.stdout, controlPlaneVipAddress])
.apply(([kc, vip]) => kc.replaceAll("127.0.0.1", vip as string).trim()),
);