Using the Kubeconfig
The kubeconfig file tells kubectl how to reach and authenticate to your cluster.
Syntax
export KUBECONFIG=/path/to/k3s.yamlk3s writes a ready-to-use kubeconfig to /etc/rancher/k3s/k3s.yaml. On the server itself, kubectl finds it automatically. To manage the cluster from your laptop, copy it and change the server address.
Steps to use it remotely
- Copy the file from the server.
- Replace
127.0.0.1with the server's real IP or hostname. - Point the
KUBECONFIGvariable at it, or merge it into~/.kube/config.
Example
# Copy the kubeconfig from the server to your machine
scp [email protected]:/etc/rancher/k3s/k3s.yaml ./k3s.yaml
# Point it at the server's real address
sed -i 's/127.0.0.1/192.168.1.10/' ./k3s.yaml
# Use it
export KUBECONFIG=$PWD/k3s.yaml
kubectl get nodesWhen to use it
- A developer copies the k3s kubeconfig to their workstation and switches context to manage the remote cluster with their local kubectl.
- A CI pipeline exports the kubeconfig as an environment variable so multiple pipeline steps can authenticate to k3s without file-path conflicts.
- An administrator merges the k3s kubeconfig into their existing multi-cluster ~/.kube/config and uses kubectl config use-context to switch between clusters.
More examples
Copy kubeconfig to workstation
Copies the k3s-generated kubeconfig from the server to a workstation and points KUBECONFIG at it.
# On the server:
cat /etc/rancher/k3s/k3s.yaml
# On the workstation:
scp [email protected]:/etc/rancher/k3s/k3s.yaml ~/.kube/k3s.yaml
export KUBECONFIG=~/.kube/k3s.yaml
kubectl get nodesUpdate the server address in kubeconfig
Replaces the loopback address in the copied kubeconfig with the server's real IP so remote clients can connect.
sed -i 's/127.0.0.1/192.168.1.10/' ~/.kube/k3s.yaml
kubectl cluster-infoMerge k3s context into main kubeconfig
Merges the k3s kubeconfig into the default config file so you can switch between multiple clusters with kubectl config use-context.
KUBECONFIG=~/.kube/config:~/.kube/k3s.yaml \
kubectl config view --flatten > ~/.kube/merged.yaml
mv ~/.kube/merged.yaml ~/.kube/config
kubectl config get-contexts
Discussion