say.farewell.cloud admin

K8s Learning: Step 03 — Get Kubeconfig to Localhost

03 — Get Kubeconfig to Localhost

Script: 03_get_config_to_localhost.sh · Enable local kubectl access

Copies the cluster credentials from your VM to your laptop, so you can run kubectl commands locally instead of SSHing in every time.


Why This Matters

In step 02, you ran kubectl on the VM via SSH. That works, but it's clunky. For local access, kubectl needs the API server address, credentials, and the cluster CA — all stored in a kubeconfig file.

BEFORE (step 02):
  Your laptop ──SSH──▶ VM ──▶ kubectl ──▶ API server

AFTER  (step 03):
  Your laptop ──▶ kubectl ──HTTPS:6443──▶ VM API server

1. Backup existing kubeconfig

if [ -f ~/.kube/config ]; then
    mv ~/.kube/config ~/.kube/config.bak_$TIMESTAMP
fi

If you already had a Kubernetes config from another cluster, it gets backed up with a timestamp.


2. Copy the kubeconfig from the VM

ssh ... 'sudo cat /etc/rancher/k3s/k3s.yaml' > ~/.kube/config

k3s stores its kubeconfig at /etc/rancher/k3s/k3s.yaml. Contains: the API server address (initially https://127.0.0.1:6443), a client certificate for auth, and the cluster CA.


3. Fix the server address

VM_PUBLIC_IP=$(ssh ... 'curl -s https://ipinfo.io/ip')
sed -i '' "s/server: https:\/\/.*/server: https:\/\/$VM_PUBLIC_IP:6443/" ~/.kube/config

The kubeconfig points to 127.0.0.1:6443 — localhost on the VM. From your laptop, you need the VM's public IP. This fetches it and rewrites the kubeconfig.


4. Verify it works

kubectl get nodes

Same command as step 02, but now running locally. It reaches port 6443 on the VM (allowed through the firewall from your IP) and lists the nodes.

💡 After this step, you never need to SSH into the VM for Kubernetes management. All kubectl commands work directly from your terminal.
← Back to homepage