Kubectl: List & Change Namespaces – Kubernetes

Kubernetes supports multiple virtual clusters backed by the same physical cluster.

These virtual clusters in Kubernetes are called Namespaces.

The Namespaces allow to partition physical resources into the logically named groups, allowing a Kubernetes cluster to share resources between multiple groups.

In this note i will show how to get the current Namespace, list all Namespaces and switch between Namespaces in Kubernetes cluster using the kubectl and kubens commands.

Cool Tip: List Nodes in Kubernetes cluster! Read more →

List & Change Namespaces in Kubernetes

The error as follows means that you probably have to change the current Namespace:

Error from server (Forbidden): <RESOURCE> is forbidden: User “<USER>” cannot list resource “<RESOURCE>” in API group “<GROUP>” in the namespace “default”.

In Kubernetes you can list the Namespaces and switch between them using the kubectl – the official command-line tool for Kubernetes and also using a handy third-party tool, named kubens.

Kubectl

Get the list of all Namespaces in the Kubernetes cluster:

$ kubectl get namespaces
- or -
$ kubectl get ns

List all Namespaces with the details:

$ kubectl describe namespaces
- or -
$ kubectl describe ns

Get the details about the particular Namespace:

$ kubectl describe ns <NAME>

Get the name of the current Namespace:

$ kubectl config view --minify --output 'jsonpath={..namespace}'; echo

Change the Namespace (set the default namespace for the current context):

$ kubectl config set-context --current --namespace=<NAME>

The command above sets the default Namespace for the current context, so all the kubectl commands in this context, by default, will be executed in the defined Namespace.

Cool Tip: List Pods in Kubernetes cluster! Read more →

Kubens

Alternatively, you can install and use kubens to list and switch between Kubernetes Namespaces smoothly.

List the Namespaces:

$ kubens

Change the active Namespace:

$ kubens <NAME>

Switch to the previous Namespace:

$ kubens -

Show the current Namespace:

$ kubens -c

Cool Tip: Switch context in Kubernetes cluster! Read more →