Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current namespace of current context using kubectl

Tags:

kubernetes

I am trying to get the namespace of the currently used Kubernetes context using kubectl.

I know there is a command kubectl config get-contexts but I see that it cannot output in json/yaml. The only script I've come with is this:

kubectl config get-contexts --no-headers | grep '*' | grep -Eo '\S+$' 
like image 271
Mikhail Golubtsov Avatar asked Apr 25 '19 16:04

Mikhail Golubtsov


People also ask

How do I get current namespace in kubectl?

The most basic command for viewing Kubernetes objects via kubectl is get . If you run kubectl get <resource-name> you will get a listing of all resources in the current namespace. If you want to get a specific resource, you can use kubectl get <resource-name> <object-name> .

How do you find the current context using kubectl?

Kubectl current-context command shows the current context of kubectl. When you enter the 'kubectl config current-context' in the virtual machine environment, the following output will be displayed. The 'kubectl config use-context cluster-name' command is used to set the default context to the given cluster name.


2 Answers

This works fine if you have a namespace selected in your context

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

You can always show up your current context and namespace in your prompt with kube-ps1

like image 99
Jose Armesto Avatar answered Oct 12 '22 07:10

Jose Armesto


Easy to memorize command line

kubectl config view | grep namespace 
like image 43
Kim G. Avatar answered Oct 12 '22 09:10

Kim G.