How to Merge Kubeconfig Files
Let's say you have a configuration file from kubeadm or another Kubernetes cluster, and you already have an existing kubeconfig file on your local system configured with other clusters.
Now, you want to merge the new configuration into the existing kubeconfig while preserving the configurations of other clusters.
Solution: You can merge a new kubeconfig
file into your existing ~/.kube/config
file using the KUBECONFIG
environment variable and kubectl config view
.
Follow the steps given below to merge and validate the Kubeconfig.
Step 1: Set the KUBECONFIG Environment Variable
Run the following command to temporarily merge both kubeconfig files
export KUBECONFIG=~/.kube/config:/path/to/new/kubeconfig
For example,
export KUBECONFIG=~/.kube/config:/Users/jacbo/Documents/GitHub/kubeadm-scripts/config
Step 2: Merge and Save the Configurations
Run this command to combine them into one
kubectl config view --flatten > ~/.kube/config-merged
Step 3: Replace the Original Config
Move the merged file back to ~/.kube/config
mv ~/.kube/config-merged ~/.kube/config
Step 4: Verify the Merged Config
Check if all contexts are available
kubectl config get-contexts
For example, in my case it lists many clusters.
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
do-blr1-jenkins-k8s-cluster do-blr1-jenkins-k8s-cluster do-blr1-jenkins-k8s-cluster-admin
kind-dev-cluster kind-dev-cluster kind-dev-cluster
* kubernetes-admin@kubernetes kubernetes kubernetes-admin
Step 5: Switch to required cluster context.
For example, for if you have merged kubeadm cluser config, you can set the context using:
kubectl config use-context kubernetes-admin@kubernetes
Step 6: Verify the config
Execute the following comands to verify the cluster connectivity using the following commands.
$ kubectl cluster-info
Kubernetes control plane is running at https://54.202.189.85:6443
CoreDNS is running at https://54.202.189.85:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
List nodes.
$ k get nodes
NAME STATUS ROLES AGE VERSION
controlplane Ready control-plane 2d19h v1.31.6
node01 Ready <none> 2d19h v1.31.6
node02 Ready <none> 2d19h v1.31.6