How to Merge Multiple Kubeconfig Files Into One

Sometimes when managing multiple kubernetes clusters, you will end up with multiple kubeconfig files. You use kubeconfig to authenticate to the cluster. The default kubeconfig is always placed in ~/.kube/config. In an event that you already have the ~/.kube/config file and you are importing a new cluster, you might need to merge them together.

We use kubeconfig files to organize information about clusters, users, namespaces, and authentication mechanisms. kubectl command-line tool itself, uses kubeconfig files to source the information it needs in order to connect and communicate with the API server of a cluster.

By default, kubectl requires a file named config that lives under $HOME/.kube directory. You can multiple cluster entries in that file or specify additional kubeconfig files by setting the KUBECONFIG environment variable or by setting the --kubeconfig flag.

In this guide, we will assume that we have our default kubeconfig here ~/.kube/config and are importing a new cluster here ~/.kube/new.yml.

Ideally, kubernetes has this feature out of the box. If you supply e.g. export KUBECONFIG="${KUBECONFIG}:config-file-1:config-file-2 it will merge those three files. But it can be cumbersome so we will learn how to combine them into a single file.

To see your configuration, enter this command:

1
kubectl config view

Backup the original kubeconfig file

Make a copy of your existing config so you can always fallback to it in case of anything

1
cp ~/.kube/config ~/.kube/config.bk

Merge the two config files together into a new config file

Set the KUBECONFIG env variables with a list of kubeconfigs to combine

1
export KUBECONFIG=~/.kube/config:~/.kube/new.yml

If you want to see now the current merged configuration that your kubectl is working with, just issue the command:

1
kubectl config view

Next flatten the config into one file

1
kubectl config view --flatten > /tmp/all-in-one-kubeconfig.yml

Replace your old config with the new merged config

1
mv /tmp/all-in-one-kubeconfig.yml ~/.kube/config

Once we have our new kubeconfig, lets set its permissions properly:

1
chmod 600 ~/.kube/config

Delete the backup once you confirm everything worked ok

1
rm ~/.kube/config.bk

We can now set our context to the new cluster we’ve just provisioned!

1
kubectl config use-context $(kubectl config get-contexts --kubeconfig=~/.kube/config --output=name)

You can also verify with this command

1
kubectl config get-clusters
Last updated on Oct 14, 2024 11:46 +0300
comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy