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.

3 Replies to “Using multiple kubeconfig files and how to merge to a single”

  1. Hello ,

    Thank you for putting this together, it’s been quite helpful, I can’t seem to get the sed part of the export command work, could you help with that? I get sed undefined label when I execute it (MacOS). I’m able to do only this successfully export KUBECONFIG=$(find ~/.kube/clusters )

Leave a Reply

Your email address will not be published.