Philippe
Philippe

Reputation: 197

Print the namespace of the current context in Kubernetes

I'd like to print the namespace of the current context in Kubernetes.

oc config view -o json returns the following output (shortened for readability)

{
    "kind": "Config",
    "apiVersion": "v1",
    "contexts": [
        {
            "name": "pp2-review/master-ocp-internal-company-com:443/Philippe",
            "context": {
                "cluster": "master-ocp-internal-company-com:443",
                "user": "Philippe",
                "namespace": "pp2-review"
            }
        },
        {
            "name": "pp2-master/master-ocp-internal-company-com:443/Philippe",
            "context": {
                "cluster": "master-ocp-internal-company-com:443",
                "user": "Philippe",
                "namespace": "review"
            }
        }
    ],
    "current-context": "pp2-review/master-ocp-internal-company-com:443/Philippe"
}

I'd like to return pp2-review. The namespace of the current context.

oc config view -o "jsonpath={\$.current-context}" returns pp2-review/master-ocp-internal-company-com:443/Philippe.

oc config view -o "jsonpath={.contexts[?(@.name==\"pp2-review/master-ocp-internal-company-com:443/Philippe\")].context.namespace}" returns pp2-review.

Combining them into oc config view -o "jsonpath={\$.contexts[?(@.name==\$.current-context)]}" returns nothing.

Is there some other way besides executing the first command and putting its return value in the second?

Upvotes: 0

Views: 2120

Answers (4)

Kevin Vo
Kevin Vo

Reputation: 301

This command will display your current context and namespace. The --minify flag means only details about the current context will be return:

kubectl config view --minify

Upvotes: 1

Chandan Patra
Chandan Patra

Reputation: 491

This should work:

kubectl config view --minify | grep namespace:

Upvotes: 0

Philippe
Philippe

Reputation: 197

Because JSON path doesn't seem to work. I searched and found a solution using Go templates:

> oc config view -o go-template='{{$currentContext := index . "current-context"}}{{- range .contexts -}}{{- if eq .name $currentContext -}}{{ .context.namespace}}{{- end -}}{{- end -}}'
review

Upvotes: 0

mario
mario

Reputation: 11098

Simple bash command substitution should do the job:

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

Upvotes: 1

Related Questions