In real life projects, we work with multiple Kubernetes clusters. Lets say Dev, QA and Prod cluster. Configuring kubectl and connecting it every time with several commands and config files will be difficult for us.

Is there any solution for this ? Can we quickly connect to the clusters ?. Yes we have a nice solution.

There is a way to configure contexts in the kubectl client. We can switch between these contexts very easily. This will make our life easy.

I have explained the steps to configure the kubectl for AKS in one of my previous posts.

Using the same approach, you can configure the credentials of various clusters in your kubectl config file. Internally kubectl refers to a file located in ~/.kube/config and maintains the credentials required to connect to a Kubernetes cluster. Every time you generate the configuration using azure cli, the file gets appended with the credentials of the new cluster. If we clearly observe the message at the time of credential generation, we can see a message that “config merged to the config file”.

So if we connect to multiple clusters, all the configurations corresponding to various clusters will be present in this file.

We can list the available contexts present in the configuration file using the following command.

kubectl config get-contexts

This will list all the available contexts. A Sample output is given below.

There will be an asterisk symbol on the currently connected context.

You can switch to any other context by using the following command.

kubectl config use-context  [cluster-name]

The cluster-name is the value that you see in the NAME field while listing the contexts.

If you do frequent switching across contexts, you can easily perform the context switching without typing long commands.

Just create aliases for the contexts.

For example, I have a Development cluster with the name azr-aks-dev and Production cluster with the name azr-aks-prod.

The usual commands for switching the contexts will be

For Development cluster

kubectl config use-context  azr-aks-dev

For Production cluster

kubectl config use-context  azr-aks-prod

This can be simplified by creating aliases like the below example.

alias kb-d=kubectl config use-context azr-aks-dev
alias kb-p=kubectl config use-context azr-aks-prod

This alias entries need to be added to the following file

nano ~/.bashrc

Reload the file

source ~/.bashrc

Now typing kb-d will switch the context to Dev cluster and kb-p will switch the context to Prod cluster

More details about kubectl configurations and context management are available in the Official Kubernetes documentation.

Thanks for reading the article. Feel free to comment if you have any question.