How to switch namespace in kubernetes How to switch namespace in kubernetes kubernetes kubernetes

How to switch namespace in kubernetes


I like my answers short, to the point and with references to official documentation:

Answer:

kubectl config set-context --current --namespace=my-namespace

From:

https://kubernetes.io/docs/reference/kubectl/cheatsheet/

# permanently save the namespace for all subsequent kubectl commands in that context.kubectl config set-context --current --namespace=ggckad-s2


There are a few options:

  • Switch namespace only using the kubectl commands::
kubectl config set-context --current --namespace=<namespace>
  • Or, Create a new context with namespace defined:
kubectl config set-context gce-dev --user=cluster-admin --namespace=devkubectl config use-context gce-dev
  • Or, Use addons, like kubectx & kubens, the below command will switch the context to kube-system:
$ kubens kube-system 
  • Or, Another easy alternative that I like without installing third party tools, is using bash alias(linux).
$ alias kubens='kubectl config set-context --current --namespace '$ alias kubectx='kubectl config use-context '// Usage$ kubens kube-system    //Switch to a different namespace$ kubectx docker        //Switch to separate context


I was able to switch namespace using the below steps

kubectl config set-context $(kubectl config current-context) --namespace=<namespace>kubectl config view | grep namespacekubectl get pods

This is how i have tested

# Create namespaces k8s-app1, k8s-app2 and k8s-app3master $ kubectl create ns k8s-app1namespace/k8s-app1 createdmaster $ kubectl create ns k8s-app2namespace/k8s-app2 createdmaster $ kubectl create ns k8s-app3namespace/k8s-app3 created# Create Service Account app1-sa in k8s-app1# Service Account app2-sa in k8s-app2# Service Account app3-sa in k8s-app3master $ kubectl create sa app1-sa -n k8s-app1serviceaccount/app1-sa createdmaster $ kubectl create sa app2-sa -n k8s-app2serviceaccount/app2-sa createdmaster $ kubectl create sa app3-sa -n k8s-app3serviceaccount/app3-sa created# Switch namespacemaster $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app1Context "kubernetes-admin@kubernetes" modified.master $ kubectl config view | grep namespace    namespace: k8s-app1master $ kubectl get saNAME      SECRETS   AGEapp1-sa   1         1mdefault   1         6mmaster $master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app2Context "kubernetes-admin@kubernetes" modified.master $ kubectl get saNAME      SECRETS   AGEapp2-sa   1         2mdefault   1         7mmaster $master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app3Context "kubernetes-admin@kubernetes" modified.master $ kubectl get saNAME      SECRETS   AGEapp3-sa   1         2mdefault   1         7m