With DKP 2.X, generating kubeconfig files in your working directory is part of setting up your cluster. Having to manually select this kubeconfig as your active context or editing it into your existing ~/.kube/config can be tiresome, especially if you have multiple clusters to merge in. There is an easy way to have kubectl do the work for you though, and I will break down the steps required below.
We start by defining the two kubeconfig files we want to merge together. The order in which we merge is important, as any duplicate contexts will be discarded from the right most kubeconfig, and its twin in the leftmost kubeconfig will be retained.
If you have just deployed a DKP 2.1.1 cluster, you will have a kubeconfig in your working directory, we'll use cluster-a.conf as an example. You will also have your existing kubeconfigs located in your home directory at ~/.kube/config. We want to merge our existing kubeconfigs into cluster-a.conf so that if cluster-a's kubeconfig was previously merged into kube/config, we will update it with newer values. We separate our kubeconfigs with a : operator as demonstrated below:
cluster-a.conf:~/.kube/config
Lets set an environment variable for our kubeconfig so that kubectl will use this merged config for subsequent commands:
KUBECONFIG=cluster-a.conf:~/.kube/config
We will want to view the current kubeconfig, so we'll use the following command to do so:
kubectl config view
You'll notice this has redacted the values of our certificates and keys, this is not helpful as we'll need the unredacted output to generate a proper kubeconfig for use with our kubernetes clusters. We can fix this via the --flatten flag:
kubectl config view --flatten
We can then pipe this to a file, please do not send the output to one of the two kubeconfigs you are merging as data loss will occur!
kubectl config view --flatten > merged.conf
Bringing everything together, the full command can be done in one line via:
KUBECONFIG=cluster-a.conf:~/.kube/config kubectl config view --flatten > merged.conf
Once we have our new kubeconfig, lets set its permissions properly:
chmod 600 merged.conf
Then lets back up our existing kubeconfig and move it to our home directory:
cp ~/.kube/config backupOfKubeconfig.conf
mv merged.conf ~/.kube/config
We can now set our context to the new cluster we've just provisioned!
kubectl config use-context $(kubectl config get-contexts --kubeconfig=${CLUSTER_NAME}.conf --output=name)
The above command relies on the fact that we define ${CLUSTER_NAME} as part of the DKP 2.X deployment process. In our example this would be cluster-a.conf.
We should ensure we're not using the merged kubeconfig in the future by cleaning up the environment variable we defined:
unset KUBECONFIG