How to Merge Multiple kubeconfig Files into One

Merge Multiple Kubernetes kubectl config files into a single

Able Lv
1 min readMay 21, 2022

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

--

--

Able Lv
Able Lv

Written by Able Lv

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

Responses (1)