'How to get the current namespace of current context using kubectl

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+$'


Solution 1:[1]

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

kubectl config view --minify -o jsonpath='{..namespace}'

Also, kube-ps1 can be used to display your current context and namespace in your shell prompt.

Solution 2:[2]

kubectl config view | grep namespace

Solution 3:[3]

1. Using service accounts of the current namespace

At least one service account exists in current namespace, so use it to retrieve the current namespace:

NS=$(kubectl get sa -o=jsonpath='{.items[0]..metadata.namespace}')

2. kubectl

Sometimes kubectl config view --minify will not display default namespace, so a more robust solution to get the namespace is:

NS=$(kubectl config view --minify --output 'jsonpath={..namespace}')
NS=$([ ! -z "$NS" ] && echo "$NS" || echo "default")

3. kubens plugin

kubens plugin, https://github.com/ahmetb/kubectx/blob/master/kubens, is also an interesting solution:

# kubens -c
default

Solution 4:[4]

Print the current namespace being used:

$ kubectl config view --minify | grep namespace

Solution 5:[5]

Use the default service account:

kubectl describe sa default | grep Namespace

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Bednark
Solution 2 Rob Bednark
Solution 3 Rob Bednark
Solution 4 Rob Bednark
Solution 5 Rob Bednark