How to use kubectl to manage kubernetes cluster contexts

Kubernetes context

A context in kubernetes is used to group access parameters under a convenient name. Each context has three parameters: cluster, namespace, and user. By default, the kubectl command-line tool uses parameters from the current context to communicate with the cluster.

In this article, we will learn how to use kubectl to manage the cluster contexts and access the different clusters.

To list all the cluster contexts:

1
2
3
$ kubectl config get-contexts 
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1

To get the current cluster context:

1
2
$ kubectl config current-context
arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1

To add and switch to a different cluster context:

1
2
3
4
5
6
7
$ aws eks update-kubeconfig --name cluster-2 --region us-west-2
Added new context arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2 to /Users/cluster/.kube/config

$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1
* arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2

To switch to an existing cluster context:

1
2
3
4
5
6
7
$ kubectl config use-context arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1
Switched to context "arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1".

$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE*
* arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1
arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2

To delete an cluster context:

1
2
3
4
5
$ kubectl config delete-context arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-2

$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
* arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1 arn:aws:eks:us-west-2:xxxxxx:cluster/cluster-1