Hello everyone! If you have to deal with different Kubernetes clusters and change between them multiple times a day, this post is for you. It will help you to save time connecting them with a few simple super-easy to remember commands!


I'm sure you have read about Kubeconfig files and about $KUBECONFIGenvironment variable. It's a common practice to have multiple Kubeconfigs files inside the ~/.kube directory and change the $KUBECONFIG variable in order to switch between clusters. But you'll soon learn how to do it better:

Contexts to the rescue

A Context is not other thing than a some kind of alias or tag for a given configuration.

You can specify multiple contexts in the config files and switch between them with a simple command. But first, let's create multiple context easily.

Creating and organizing different contexts

You should probably already have multiple k8s config files inside ~/.kube directory, if you don't we are going to organize the different cluster configurations in separated files for a easy management.

My example:

qatech_auto@testconn-unix:~/.kube$ ls -la
total 28
drwxrwxr-x 4 qatech_auto qatech_auto 4096 Apr 11 18:42 .
drwxr-xr-x 7 qatech_auto qatech_auto 4096 Apr 11 18:37 ..
drwxr-x--- 3 qatech_auto qatech_auto 4096 Apr 11 18:39 cache
-rw-rw-r-- 1 qatech_auto qatech_auto 3677 Apr 11 18:42 config
-rw-rw-r-- 1 qatech_auto qatech_auto 2052 Apr 11 18:37 devops-madrid-saitama
drwxr-x--- 3 qatech_auto qatech_auto 4096 Apr 11 18:42 http-cache
-rw-rw-r-- 1 qatech_auto qatech_auto 2047 Apr 11 18:36 popz-private-saitama

I have 2 diffrent configurations for 2 clusters, devops-madrid-saitama and popz-private-saitama

Now we are going to merge theses files into the config default file for forgetting the $KUBECONFIG environment variable:

KUBECONFIG=devops-madrid-saitama:popz-private-saitama kubectl config view --merge --flatten > config
Merging all specified config files into the config default file

Keep that command in order to update our main config file, which holds all the clusters configuration. If some day we have to add a new cluster or simply update one, we only have to update the specific files which refrence the cluster and re run the previous command.

Switching between contexts

We can list all available context wit this command:

kubectl config get-contexts
List all available contexts

Using kubectl we can specify --context <context-name> in every command for routing the request to the appropriate cluster, but this is not useful at all.

Is better to specify the context, at the beggining of all comands, this avoids us to add the --context flag on every kubectl call:

kubectl config use aks-popz-private

That's all!