如何使用 kubectl 获取当前上下文的当前名称空间

我尝试使用 kubectl获取当前使用的 Kubernetes 上下文的名称空间。

我知道有一个命令 kubectl config get-contexts,但是我看到它不能在 json/yaml 中输出。我唯一的剧本是这样的:

kubectl config get-contexts --no-headers | grep '*' | grep -Eo '\S+$'
53104 次浏览

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.

kubectl config view | grep namespace

Print the current namespace being used:

kubectl config view --minify | grep namespace

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

Use the default service account:

kubectl describe sa default | grep Namespace

You can print the namespace of the current context by making use of the commands kubectl config current-context and kubectl config view as follows:

kubectl config view -o jsonpath="{.contexts[?(@.name == '$(kubectl config current-context)')].context.namespace}"

However I think https://stackoverflow.com/a/55854690/5655567 is the best solution

# short alias to set/show context/namespace (only works for bash and bash-compatible shells, current context to be set before using kn to set namespace)
alias kx='f() { [ "$1" ] && kubectl config use-context $1 || kubectl config current-context ; } ; f'
alias kn='f() { [ "$1" ] && kubectl config set-context --current --namespace $1 || kubectl config view --minify | grep namespace | cut -d" " -f6 ; } ; f'

For more kubectl code check this usefull cheatsheet: https://kubernetes.io/docs/reference/kubectl/cheatsheet/