How to Merge Multiple kubeconfig Files into One

When accessing multiple Kubernetes clusters, you will have many kubeconfig files. By default, kubectl only looks for a file named config in the $HOME/.kube directory. So, how can we merge many kubeconfig files into one?

Here are the few steps:

1. Make a copy of your kubeconfig file

cp ~/.kube/config ~/.kube/config-backup

2. Set the KUBECONFIG environment variable

The KUBECONFIG environment variable is a list of paths to configuration files, for example /path/cluster1:/path/cluster2:/path/cluster3

export KUBECONFIG=~/.kube/config:/path/cluster1:/path/cluster2

If you have many kubeconfig files in the current directory, you can use the following command to set the KUBECONFIG environment variable quickly.

export KUBECONFIG=~/.kube/config:$(find . -type f | tr '\n' ':')

3. Merge all kubeconfig files into one

kubectl config view --flatten > all-in-one-kubeconfig.yaml

4. Replace the old config file with the new merged one

mv all-in-one-kubeconfig.yaml ~/.kube/config

5. Verify it works

Display all your clusters defined in the kubeconfig:

kubectl config get-clusters

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Able Lv

Able Lv

252 Followers

Cloud Infrastructure Engineer @Airwallex: Kubernetes, DevOps, Terraform, Istio, Go, and Cloud-Native stuff