Post

How to switch Kubernetes Contexts

What is Kubernetes context ?

A Kubernetes context is a group of access parameters that define which cluster you’re interacting with, which user you’re using, and which namespace you’re working in. It’s helpful if you need to access different clusters for different purposes or if you want to limit your access to certain parts of a cluster.

Data config of Kubernetes context is at default location path file: $HOME/.kube/config.

How To Use Kubernetes Contexts

How to list current local Kubernetes contexts ?

1
2
3
4
5
6
$ kubectl config get-contexts
CURRENT   NAME                                     CLUSTER                                                            AUTHINFO                                                                    NAMESPACE
*         amagez-gitlab                            amagez-ant_asia-northeast3_inspectorio-gitlab                      amagez-ant_asia-northeast3_inspectorio-gitlab
          amagez-preprod                           amagez-preprod_us-west1_inspectorio-preprod                        amagez-preprod_us-west1_inspectorio-preprod
          amagez-prod                              amagez-production_asia-northeast1_inspectorio-production           amagez-production_asia-northeast1_inspectorio-production
          amagez-stg                               amagez-saas-west1_inspectorio-staging                              amagez-saas-west1_inspectorio-staging

You can list without header column and show only name part.

1
2
3
4
5
$ kubectl config get-contexts --no-headers -o=name
amagez-gitlab
amagez-preprod
amagez-prod
amagez-stg

How about list current kubectl context ?

1
2
$ kubectl config current-context
amagez-prod

Or you can view directly content of file $HOME/.kube/config.

1
2
$ grep "current-context" ${HOME}/.kube/config | awk -F':' '{print $2}' | tr -d ' '
amagez-prod

Final, i want to switch to a new Kubernetes context.

1
2
3
4
5
$ kubectl config use-context amagez-stg
Switched to context "amagez-stg".

$ kubectl config current-context
amagez-stg

Open source tools

  • https://github.com/ahmetb/kubectx
  • https://github.com/Amagez/kube-profiles

Practice Video

Conclusion

Above is just some writeup relate to scope content How to switch Kubernetes contexts. We still have many actions like add and delete kubernetes context. But you can see in another articles.