How to get the current namespace of current context using kubectl
KubernetesKubernetes Problem Overview
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+$'
Kubernetes Solutions
Solution 1 - Kubernetes
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 - Kubernetes
kubectl config view | grep namespace
Solution 3 - Kubernetes
Print the current namespace being used:
$ kubectl config view --minify | grep namespace
Solution 4 - Kubernetes
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 5 - Kubernetes
Use the default service account:
kubectl describe sa default | grep Namespace