Silly Kubectl Trick #7: Merge All the Kubeconfigs!
With a directory full of configuration files, you don't have to hand-edit them together, kubectl can merge them for us!
Join the DZone community and get the full member experience.Join For Free
Once you start managing more than one Kubernetes cluster, you'll start to demand more from your
$KUBECONFIG. Early on in my career spinning pods, I kept a separate
.kubeconfig file for each cluster, and wrote a small shell function to set the requisite environment variables. To switch between clusters was as simple as:
I did this because the "correct" command was too much to remember:
See what I mean?
Then I met kubectx and kubens, and they quickly became invaluable.
Now I've got this directory full of all these disparate, discrete configuration files, and I don't want to hand-edit them back together. Thankfully,
kubectl itself can merge them for us!
kubectl will only merge configuration files if you specify them via the
$KUBECONFIG environment variable. You cannot use the
--kubeconfig command-line flag, it won't work.
To demonstrate this, I'm going to show you my
kubectl config get-contexts commands, we can see that each of them is different:
If you put two (or more) files, separated by colons, in
kubectl will merge them together semantically, and operate on the composite configuration. Any changes you make, like changing namespaces or setting contexts, will update the appropriate member file(s).
To write a new, aggregate configuration that contains the results of the merge, we can use
kubectl config view --raw. The
--raw flag prevents
kubectl from redacting user secrets, certificates, and keys. To save this combined file, we can employ some shell redirection, along with a bit of caution.
Every UNIX shell I've ever used truncates files that are the target of
>-style output redirection, before the command producing the output gets executed. It's the nature of UNIX pipelines. We have to be careful with the order of our operations.
This will fail spectacularly (and most assuredly destroy data in the process!):
a configuration file will be empty by the time
kubectl gets around to trying to merge it in with the other two. Instead, use a temporary file and a rename operation:
Pro Tip: While you are merging all of these configurations together, you can also embed any referenced, external files (like certificates and private keys) by swapping out the
--raw flag for
--flatten. This produces "portable" kubeconfigs, which do not have any dependencies on other parts of your filesystem. They can be moved, or copied, without losing their utility.
Published at DZone with permission of . See the original article here.
Opinions expressed by DZone contributors are their own.