diff --git a/bootstrap/cluster/main.tf b/bootstrap/cluster/main.tf index d8e626d..30d0b6f 100644 --- a/bootstrap/cluster/main.tf +++ b/bootstrap/cluster/main.tf @@ -13,7 +13,89 @@ terraform { } } +resource "null_resource" "k3s_control_plane" { + count = local.k3s_enabled ? 1 : 0 + triggers = { + node_name = var.control_plane_node_name + host = var.control_plane_host + user = var.control_plane_user + ssh_key_path = var.control_plane_ssh_key_path + advertise_address = var.control_plane_advertise_address + kubeconfig_path = var.kubeconfig_path + kubeconfig_owner = var.kubeconfig_owner + k3s_version = var.k3s_version + pod_network_cidr = var.pod_network_cidr + } + connection { + type = "ssh" + user = self.triggers.user + private_key = file(self.triggers.ssh_key_path) + host = self.triggers.host + timeout = "30m" + } + provisioner "remote-exec" { + inline = [<&2 + exit 1 +fi +if ! command -v k3s >/dev/null 2>&1; then + curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION='${self.triggers.k3s_version}' sh -s - server \ + --node-name '${self.triggers.node_name}' \ + --node-ip '${self.triggers.advertise_address}' \ + --advertise-address '${self.triggers.advertise_address}' \ + --flannel-backend=none --disable-network-policy --disable=traefik \ + --write-kubeconfig-mode=0644 --cluster-cidr '${self.triggers.pod_network_cidr}' +fi +sudo systemctl enable k3s >/dev/null +sudo systemctl restart k3s +for _ in $(seq 1 90); do + if sudo k3s kubectl get --raw=/readyz >/dev/null 2>&1; then exit 0; fi + sleep 2 +done +sudo systemctl status k3s --no-pager -l || true +sudo journalctl -u k3s --no-pager -n 160 || true +exit 1 +EOT + ] + } +} + +resource "null_resource" "k3s_kubeconfig" { + count = local.k3s_enabled ? 1 : 0 + depends_on = [null_resource.k3s_control_plane] + triggers = { + control_plane_id = null_resource.k3s_control_plane[0].id + host = var.control_plane_host + user = var.control_plane_user + ssh_key_path = var.control_plane_ssh_key_path + advertise_address = var.control_plane_advertise_address + kubeconfig_path = var.kubeconfig_path + kubeconfig_owner = var.kubeconfig_owner + } + provisioner "local-exec" { + interpreter = ["/bin/bash", "-lc"] + command = <"$tmp_file" +sed -i "s#https://127.0.0.1:6443#https://${self.triggers.advertise_address}:6443#g" "$tmp_file" +install -m 0600 "$tmp_file" "${self.triggers.kubeconfig_path}" +EOT + } +} + +locals { + kubeadm_enabled = var.cluster_runtime == "kubeadm" + k3s_enabled = var.cluster_runtime == "k3s" +} + resource "null_resource" "kubeadm_control_plane" { + count = local.kubeadm_enabled ? 1 : 0 triggers = { node_name = var.control_plane_node_name advertise_address = var.control_plane_advertise_address @@ -490,10 +572,11 @@ EOT } resource "null_resource" "kubeconfig_pullback" { + count = local.kubeadm_enabled ? 1 : 0 depends_on = [null_resource.kubeadm_control_plane] triggers = { - control_plane_id = null_resource.kubeadm_control_plane.id + control_plane_id = null_resource.kubeadm_control_plane[0].id host = var.control_plane_host user = var.control_plane_user ssh_key_path = var.control_plane_ssh_key_path @@ -525,6 +608,7 @@ EOT } resource "null_resource" "kube_system_resource_policy" { + count = local.kubeadm_enabled ? 1 : 0 depends_on = [null_resource.kubeconfig_pullback] triggers = { @@ -675,6 +759,7 @@ EOT } resource "null_resource" "worker_nodes_required" { + count = local.kubeadm_enabled ? 1 : 0 triggers = { worker_count = tostring(length(var.worker_nodes)) } @@ -688,7 +773,7 @@ resource "null_resource" "worker_nodes_required" { } resource "null_resource" "kubeadm_worker" { - for_each = var.worker_nodes + for_each = local.kubeadm_enabled ? var.worker_nodes : {} depends_on = [ null_resource.kubeadm_control_plane, @@ -1582,6 +1667,8 @@ resource "null_resource" "node_labels" { null_resource.kubeadm_control_plane, null_resource.kubeconfig_pullback, null_resource.kubeadm_worker, + null_resource.k3s_control_plane, + null_resource.k3s_kubeconfig, ] triggers = { diff --git a/bootstrap/cluster/variables.tf b/bootstrap/cluster/variables.tf index 94ca48b..99c84d7 100644 --- a/bootstrap/cluster/variables.tf +++ b/bootstrap/cluster/variables.tf @@ -3,6 +3,23 @@ variable "control_plane_node_name" { default = "debian" } +variable "cluster_runtime" { + type = string + description = "Control-plane runtime to install on the selected profile host." + default = "kubeadm" + + validation { + condition = contains(["kubeadm", "k3s"], var.cluster_runtime) + error_message = "cluster_runtime must be kubeadm or k3s." + } +} + +variable "k3s_version" { + type = string + description = "Pinned k3s release installed for the direct Debian profile." + default = "v1.31.5+k3s1" +} + variable "control_plane_node_labels" { type = map(string) default = { diff --git a/homelab.yml b/homelab.yml index 98db570..18f30a3 100644 --- a/homelab.yml +++ b/homelab.yml @@ -88,6 +88,26 @@ cluster: control_plane_vmid: 9001 worker_count: 2 worker_static_ips: 192.168.100.66 192.168.100.67 + k3s: + control_plane: + node_name: debian + lan_ip: 192.168.100.73 + user: jv + ssh_key_path: /home/jv/.ssh/id_ed25519 + kubeconfig: /home/jv/.kube/k3s-config + kubeconfig_owner: jv:jv + registry: + endpoint: 192.168.100.73:30500 + provisioning: + host: 192.168.100.73 + user: jv + http: + host: 192.168.100.73 + gitops: + repo_url: ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git + platform: + calico_operator_node_name: debian + runtime: k3s hosts: debian: diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 803f603..d514bcf 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -8,7 +8,7 @@ plan_homelab() { require_debian_server "plan" if [[ "${target}" == "all" ]]; then - if [[ -z "${LAB_CLUSTER_VAR_FILE:-}" ]]; then + if [[ -z "${LAB_CLUSTER_VAR_FILE:-}" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then prepare_cluster_worker_var_file false fi stacks=( @@ -20,7 +20,7 @@ plan_homelab() { ) else stack="$(tofu_stack_from_plan_target "${target}")" - if [[ "${stack}" == "bootstrap/cluster" && -z "${LAB_CLUSTER_VAR_FILE:-}" ]]; then + if [[ "${stack}" == "bootstrap/cluster" && -z "${LAB_CLUSTER_VAR_FILE:-}" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then prepare_cluster_worker_var_file false fi stacks=("${stack}") @@ -142,6 +142,7 @@ Provisioning host: ${LAB_CLUSTER_PROVISIONING_HOST:-${LAB_DEBIAN_LAN_IP:-}} Provisioning user: ${LAB_CLUSTER_PROVISIONING_USER:-${LAB_DEBIAN_USER:-}} GitOps repo URL: ${LAB_GITOPS_REPO_URL:-} Calico operator node: ${LAB_CALICO_OPERATOR_NODE_NAME:-${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}} +Cluster runtime: ${LAB_CLUSTER_RUNTIME:-kubeadm} External services host: ${LAB_SERVICES_HOST:-debian} (${LAB_SERVICES_HOST_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}, tailscale ${LAB_SERVICES_HOST_TAILSCALE_IP:-${LAB_DEBIAN_TAILSCALE_IP:-}}) Gitea backend host: ${LAB_GITEA_BACKEND_HOST:-${LAB_GITEA_TAILSCALE_IP:-${LAB_GITEA_HOST:-}}} Dex backend host: ${LAB_DEX_BACKEND_HOST:-${LAB_DEBIAN_TAILSCALE_IP:-}} diff --git a/lib/jeannie/env.sh b/lib/jeannie/env.sh index 0d6e412..878c1ab 100644 --- a/lib/jeannie/env.sh +++ b/lib/jeannie/env.sh @@ -152,6 +152,7 @@ profile_mapping = { "http.host": ("LAB_CLUSTER_HTTP_HOST", "hosts.debian.lan_ip"), "gitops.repo_url": ("LAB_GITOPS_REPO_URL", "services.gitea.ssh_remote"), "platform.calico_operator_node_name": ("LAB_CALICO_OPERATOR_NODE_NAME", None), + "runtime": ("LAB_CLUSTER_RUNTIME", "cluster.runtime"), "pimox.host": ("LAB_CLUSTER_PIMOX_HOST", "hosts.opi5_pimox.lan_ip"), "pimox.user": ("LAB_CLUSTER_PIMOX_USER", "hosts.opi5_pimox.user"), "pimox.bridge": ("LAB_CLUSTER_PIMOX_BRIDGE", "hosts.opi5_pimox.bridge"), @@ -261,6 +262,7 @@ export_homelab_inventory_tf_vars() { export_if_unset TF_VAR_provisioning_user "${LAB_CLUSTER_PROVISIONING_USER:-${LAB_DEBIAN_USER:-}}" export_if_unset TF_VAR_http_host "${LAB_CLUSTER_HTTP_HOST:-${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}}" export_if_unset TF_VAR_pimox_host "${LAB_CLUSTER_PIMOX_HOST:-${LAB_PIMOX_HOST:-}}" + export_if_unset TF_VAR_cluster_runtime "${LAB_CLUSTER_RUNTIME:-kubeadm}" export_if_unset TF_VAR_pimox_user "${LAB_CLUSTER_PIMOX_USER:-${LAB_PIMOX_USER:-}}" export_if_unset TF_VAR_pimox_worker_storage "${LAB_CLUSTER_PIMOX_STORAGE:-${LAB_PIMOX_WORKER_STORAGE:-}}" export_if_unset TF_VAR_pimox_template_bridge "${LAB_CLUSTER_PIMOX_BRIDGE:-${LAB_PIMOX_BRIDGE:-}}" diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 9481e95..62eb887 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -971,7 +971,10 @@ run_tofu_stack() { local -a apply_args=() local target - if [[ "${stack}" == "bootstrap/cluster" || "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]]; then + # A new profile has no pinned identity until its control plane bootstrap + # completes. Platform/apps remain guarded by cluster-context as usual. + if [[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]] || + [[ "${stack}" == "bootstrap/cluster" && -f "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}/identity.json" ]]; then cluster_context_require || return 1 fi @@ -983,7 +986,7 @@ run_tofu_stack() { shift done - if [[ "${stack}" == "bootstrap/cluster" ]]; then + if [[ "${stack}" == "bootstrap/cluster" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then ensure_cluster_worker_var_file fi if [[ "${stack}" == "bootstrap/edge" ]]; then @@ -1051,7 +1054,7 @@ run_tofu_plan_stack() { local stack="$1" local -a plan_args=() - if [[ "${stack}" == "bootstrap/cluster" ]]; then + if [[ "${stack}" == "bootstrap/cluster" && "${LAB_CLUSTER_RUNTIME:-kubeadm}" != "k3s" ]]; then ensure_cluster_worker_var_file fi if [[ "${stack}" == "bootstrap/edge" ]]; then @@ -8964,6 +8967,11 @@ ensure_edge_haproxy_stats_password() { } ensure_cluster_worker_var_file() { + if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == "k3s" ]]; then + rm -f "${REPO_ROOT}/.lab/cluster-workers.auto.tfvars.json" + unset LAB_CLUSTER_VAR_FILE + return 0 + fi if [[ -z "${LAB_CLUSTER_VAR_FILE:-}" ]]; then prepare_cluster_worker_var_file false fi diff --git a/scripts/cluster-context.py b/scripts/cluster-context.py index 5d480f0..27b128d 100644 --- a/scripts/cluster-context.py +++ b/scripts/cluster-context.py @@ -421,16 +421,36 @@ def proxy_tofu(args): raise Refused("State/backend overrides are refused; use cluster-context migrate for reviewed legacy state") legacy = directory / "terraform.tfstate" if not state.exists() and legacy.exists(): - record = legacy_record(context, legacy) - owner = document(record) if record.exists() else {} - owner_profile = owner.get("profile", "") - owner_binding = context.root.parent / owner_profile / "identity.json" if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", owner_profile) else None - owner_identity = document(owner_binding) if owner_binding and owner_binding.exists() else {} - owned_elsewhere = bool(owner_identity) and owner_profile != context.profile and owner.get("sha256") == hashlib.sha256(legacy.read_bytes()).hexdigest() - owned_elsewhere = owned_elsewhere and all(owner.get(field) == owner_identity.get(field) for field in IDENTITY_FIELDS) - owned_elsewhere = owned_elsewhere and (context.root.parent / owner_profile / "stacks" / name / "terraform.tfstate").exists() - if not owned_elsewhere: - raise Refused(f"Legacy {name} state is preserved and is not safely assigned elsewhere. Review ./jeannie cluster-context migrate --stack {name}, then migrate --stack {name} --yes") + fresh_k3s_cluster = ( + name == "cluster" + and os.environ.get("TF_VAR_cluster_runtime") == "k3s" + and not context.binding.exists() + ) + if fresh_k3s_cluster: + # The retained legacy state belongs to another profile. The + # scoped backend initializer will seed a new empty k3s state; + # never migrate or inspect the legacy snapshot here. + legacy = None + if legacy is None: + pass + else: + record = legacy_record(context, legacy) + if legacy is not None: + owner = document(record) if record.exists() else {} + if legacy is not None: + owner_profile = owner.get("profile", "") + if legacy is not None: + owner_binding = context.root.parent / owner_profile / "identity.json" if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", owner_profile) else None + if legacy is not None: + owner_identity = document(owner_binding) if owner_binding and owner_binding.exists() else {} + if legacy is not None: + owned_elsewhere = bool(owner_identity) and owner_profile != context.profile and owner.get("sha256") == hashlib.sha256(legacy.read_bytes()).hexdigest() + if legacy is not None: + owned_elsewhere = owned_elsewhere and all(owner.get(field) == owner_identity.get(field) for field in IDENTITY_FIELDS) + if legacy is not None: + owned_elsewhere = owned_elsewhere and (context.root.parent / owner_profile / "stacks" / name / "terraform.tfstate").exists() + if not owned_elsewhere: + raise Refused(f"Legacy {name} state is preserved and is not safely assigned elsewhere. Review ./jeannie cluster-context migrate --stack {name}, then migrate --stack {name} --yes") env = dict(os.environ, TF_DATA_DIR=str(context.root / ".terraform" / name), TF_WORKSPACE="default") env["JEANNIE_PROFILE_TF_DATA"] = env["TF_DATA_DIR"] env["TF_VAR_kubeconfig_path"] = context.kubeconfig @@ -443,7 +463,13 @@ def proxy_tofu(args): if command == "init": return 0 mutable = command in ("apply", "destroy", "import", "refresh", "force-unlock", "taint", "untaint") or command == "state" and len(args) > 1 and args[1] not in ("list", "show", "pull") - observed = context.check() if mutable else None + initial_k3s_bootstrap = ( + name == "cluster" + and command == "apply" + and os.environ.get("TF_VAR_cluster_runtime") == "k3s" + and not context.binding.exists() + ) + observed = context.check() if mutable and not initial_k3s_bootstrap else None if command in ("apply", "destroy", "import", "refresh", "plan"): expression = "jsonencode(var.kubeconfig_path)" if name == "cluster": @@ -456,9 +482,12 @@ def proxy_tofu(args): if kubeconfig["node"] != context.expected_node or any(kubeconfig[key] != context.expected_host for key in ("host", "address")): raise Refused("Control-plane provisioner host/name/address does not match the selected profile") kubeconfig = kubeconfig["kubeconfig"] - effective = Context(kubeconfig=kubeconfig) - # Plans can evaluate declarative imports; validate those reads too. - observed = effective.check() + effective = Context(kubeconfig=kubeconfig) + # A first k3s control-plane apply creates the kubeconfig and + # identity; enrollment is intentionally a separate reviewed + # step after the API is available. + if not initial_k3s_bootstrap: + observed = effective.check() saved = [arg for arg in positionals(args[1:]) if (directory / arg).is_file()] if command == "apply" and saved: if len(saved) != 1: