In this tutorial I show you how to switch between Kubernetes clusters using kubectl contexts. This is useful when you have multiple clusters and need to switch between them to run commands. In this particular example I show you how to switch between clusters using the Azure CLI.
1. Authenticate to Azure CLI
First, let’s authenticate to the Azure CLI:
1
az login
Follow the on-screen instructions in the popup-browser window and ensure you authenticate correctly to the subscription you want to target.
1.1 You may also need to set the subscription
1
az account set --subscription "My-Subscription"
2. List and Connect to an AKS cluster using the Azure CLI
Great, we’re authenticated with the CLI, now we need to list the clusters.
1
az aks list -o table
This will give you a nice list of all your clusters in a table-like format:
Next step right after this, is to get the credentials from one of your clusters, which you can also do using the Azure CLI: Listing Azure Kubernetes Services available for the authenticated user
1
az aks get-credentials -n <yourClusterName> -g <yourResourceGroupName>
Great, this ensures you’ve got access and that the kubectl commands will now target this cluster.
3. Targeting your cluster with config get-contexts and use-context
This is the fun part, as I’m sure most readers are already familiar with the above commands to authenticate to the clusters.
Using kubectl config get-contexts we’ll be able to see all the clusters we’ve authenticated against, regardless what subscription they’re in:
1
kubectl config get-contexts
kubectl command to list context with the local user of the system
So here comes the simple context switch part. You can see that the first one in my list is marked with the asterisk *. This is the cluster that is currently selected and that my kubectl commands targets.
Switch cluster:
1
kubectl config use-context <yourClusterName>
Switch cluster using the kubectl config use-context command
Voila, that’s it. Now you’re targeting the other cluster. You can verify this by running kubectl get pods or any other command that targets the cluster i.e. kubectl get nodes.