Skip to content

Add a Kubernetes cluster to kubectl

To add a new Kubernetes cluster to your kubectl configuration, you need to merge the kubeconfig file from the new cluster with the existing kubeconfig file on your local machine.

TL;DR quick steps

Where delta is a server in the cluster with the credentials you would like to add.

scp delta:/etc/rancher/k3s/k3s.yaml .
vi k3s.yaml # Update the server address and context name
export KUBECONFIG=~/.kube/config:./k3s.yaml
kubectl config view --merge --flatten > ~/.kube/merged_kubeconfig && mv ~/.kube/merged_kubeconfig ~/.kube/config
rm k3s.yaml

Copy the cluster's kubeconfig file to your local machine

In this example I am copying kubeconfig from a k3s cluster. The kubeconfig file is located at /etc/rancher/k3s/k3s.yaml on the k3s server.

scp delta:/etc/rancher/k3s/k3s.yaml .
vi k3s.yaml # Update the server address and context name

Add the new cluster to your kubectl configuration PATH temporarily

export KUBECONFIG=~/.kube/config:/tmp/k3s.yaml

Merge the new cluster's kubeconfig file with the existing one

kubectl config view --merge --flatten > ~/.kube/merged_kubeconfig && mv ~/.kube/merged_kubeconfig ~/.kube/config

Remove the k3s.yaml file that is no longer required

rm k3s.yaml

Verify the new cluster has been added to your kubectl configuration

kubectl config get-contexts 
kubectl config use-context delta-dev 
kubectl get pods -A