Merge multiple kubeconfig files
Merge multiple Kubernetes configuration files without the unnecessary drama
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 have multiple cluster entries in that file or specify additional kubeconfig
files by setting the KUBECONFIG
environment variable or by setting the --kubeconfig
flag.
When you have manykubeconfig
files you might want to merge them in one in order to avoid switching among them using the kubeconfig
flag; I personally get a headache because there is no way I’ll ever remember how to merge those files from the command line. But there is a simpler way, so please don’t waste brain cells to remember complicated bash commands.
As we mentioned before the easy way is by setting the KUBECONFIG
environment variable. You can specify there multiple config files divided by the colon symbol (:) and kubectl
will merge those automatically for you.
export KUBECONFIG=~/.kube/config:~/.rancher/local:~/.kube/kubeconfig.json
Special treat: You can mix and match YAML and JSON files!
If you want to see now the current merged configuration that your kubectl
is working with, just issue the command:
kubectl config view
and if you want to export this configuration for future use as a single file you can do it by running:
kubectl config view --flatten > my-config.yaml
and then you can replace your ~/.kube/config
file with the file above for permanent effect.
Don’t over-complicate staff, don’t try to memorize staff.