Depending on your use case, you may want to use multiple Kubernetes clusters. But how does that work? Fortunately, it's quite simple:
For each cluster you want to manage, you need a Kubeconfig file. This file contains the information that Kubectl needs to connect to a cluster. By merging multiple Kubeconfig files together, you can switch between multiple clusters using Kubectl.
- For the steps in this tutorial, you need Kubectl. Install Kubectl first if you haven't done so already.
- If you haven't gone through our Kubernetes quickstart tutorial yet, please go through step 1 and 2 for Windows users and step 1 for Mac/Linux users.
Merging Kubeconfig Files
You can merge multiple Kubeconfig files into one file. This can be done by using the KUBECONFIG environment variable and merging the files with a Kubectl command.
Step 1
Download the Kubeconfig files for all your clusters from the control panel (via this link > click on your cluster > 'Download kubeconfig') and save the file in any directory. It can be the directory %USERPROFILE%\.kube for Windows or ~\.kube for Linux/MacOS.
Do not change the names of the files (they look like kube-k123a.yml).
Step 2
Export the KUBECONFIG environment variable. Make sure to adjust the directory and filenames to the directory where you saved the files and the downloaded filenames.
Windows:
Open PowerShell (Windows Start Menu > search for 'Powershell' > right-click and select 'Run as administrator'). Execute the following command (but with your own details):
$env:KUBECONFIG="
C:\Users\TransIP\.kube\
config-k8kk8.yml
;
C:\Users\TransIP\.kube\
config-k123a.yml
"
Linux/MacOS:
Execute the following command in the command-line (but with your own details):
export KUBECONFIG=~/.kube/config-k8kk8.yml
:~/.kube/config-k8kk8.yml
Step 3
Finally, merge the different Kubeconfig files with the following command:
kubectl config view --flatten > ~/.kube/config
That's it! You can now switch between your clusters. We'll show you how it works in the next section.
Switching Between Kubernetes Clusters
Now that you have included multiple clusters in your Kubeconfig file, you can switch between them using the kubectl config use-context command.
Step 1
View the available contexts with the command:
kubectl config get-contexts
You will see a list of all contexts (clusters) in your kubeconfig file.
Step 2
To use a context (and switch to the corresponding cluster), execute the following command:
kubectl config use-context cluster-k8kk8
Replace cluster-k8kk8-context with the name of the context you want to use. Typically, this will be the name of your cluster.
And that's it! You can now manage multiple Kubernetes clusters with Kubectl. You can always check the current context with the command:
kubectl config current-context