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.
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 )
Hi,
Thank you for your message, the idea of the sed command is to remove the new line character and show all the files in one line.
If not working on the MAC-os with sed you could try with awk -> awk ‘{printf “%s+”,$0} END {print “”}’ (https://serverfault.com/questions/391360/remove-line-break-using-awk)
brew install gnu-sed
change sed to gsed
bashrc file should work now