From 10aa98f3b0f73986cec16496de1c2e1be57750f4 Mon Sep 17 00:00:00 2001 From: liangxu Date: Sat, 2 May 2026 01:11:44 +0800 Subject: [PATCH] fix: enhance kubeconfig handling for NAS deployments to prevent permission issues --- .gitea/workflows/nas-k3s-deploy.yml | 36 +++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/.gitea/workflows/nas-k3s-deploy.yml b/.gitea/workflows/nas-k3s-deploy.yml index 1740702..d1c0a19 100644 --- a/.gitea/workflows/nas-k3s-deploy.yml +++ b/.gitea/workflows/nas-k3s-deploy.yml @@ -640,14 +640,40 @@ jobs: fi } - # k3s installs kubeconfig at /etc/rancher/k3s/k3s.yaml with mode 0600 - # (root only), so any kubectl path must go through sudo unless the - # current user is already root. + # k3s writes kubeconfig at /etc/rancher/k3s/k3s.yaml mode 0600 root:root. + # Many NAS sudo setups elevate admin to a service user instead of root, + # so `sudo kubectl` may still hit "permission denied". Copy kubeconfig + # once into the SSH user's home and point KUBECONFIG at the copy. + ensure_kubeconfig() { + kubeconfig_target="${HOME:-/tmp}/.kube/config" + mkdir -p "$(dirname "${kubeconfig_target}")" + + if [ -r /etc/rancher/k3s/k3s.yaml ]; then + cp /etc/rancher/k3s/k3s.yaml "${kubeconfig_target}" + else + kubeconfig_tmp="${kubeconfig_target}.tmp.$$" + if sudo_cmd cat /etc/rancher/k3s/k3s.yaml > "${kubeconfig_tmp}" 2>/dev/null && [ -s "${kubeconfig_tmp}" ]; then + mv "${kubeconfig_tmp}" "${kubeconfig_target}" + else + rm -f "${kubeconfig_tmp}" + echo "Cannot read /etc/rancher/k3s/k3s.yaml as $(whoami) or via sudo." + echo "On the NAS, fix once with one of:" + echo " sudo chmod 0644 /etc/rancher/k3s/k3s.yaml" + echo " sudo install -m 0640 -g admin /etc/rancher/k3s/k3s.yaml /etc/rancher/k3s/k3s.yaml" + echo "or restart k3s with --write-kubeconfig-mode 0644." + exit 1 + fi + fi + chmod 600 "${kubeconfig_target}" + export KUBECONFIG="${kubeconfig_target}" + } + ensure_kubeconfig + kubectl_cmd() { if command -v kubectl >/dev/null 2>&1; then - sudo_cmd kubectl "$@" + kubectl "$@" elif command -v k3s >/dev/null 2>&1; then - sudo_cmd k3s kubectl "$@" + k3s kubectl "$@" else echo "Cannot find kubectl or k3s on NAS." exit 1