Using multiple kubeconfig files and how to merge to a single

Reference: Kubernetes Documentation

When it’s the case that you are managing multiple Kubernetes clusters, you will have to do with multiple kubeconfig files.
There are multiple ways that you can deal with this, my favorite is to keep the files separate, you can achive this by:

Creating a folder and move the kubeconfig files there.

mkdir ~/.kube/clusters
mv /path/cluster1.config /path/cluster2.config ~/.kube/clusters

Add the $KUBECONFIG environment variable to your ~/.bashrc, the value has to be “/path/cluster1.config:/path/cluster2.config”.

export KUBECONFIG=$(find ~/.kube/clusters -type f | sed ':a;N;s/\n/:/;ba')

Start a new bash terminal in order to take effect or “source ~/.bashrc” in the current.

Check, you can see both clusters and of course you can switch to the one that you wish to use.

kubectl config get-clusters
NAME
cluster1
cluster2

Other way would be to merge the multiple kubeconfig files in one and store it in ~/.kube/config the default location that it’s used when the $KUBECONFIG environment variable it’s not set.

KUBECONFIG="/path/cluster1.config:/path/cluster2.config"
kubectl config view --flatten > ~/.kube/config

That being said, I prefer the first one because it makes life easier when adding or removing a cluster is needed by simply adding or removing files.

Leave a Reply

Your email address will not be published. Required fields are marked *