Reputation: 197
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
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
Reputation: 491
This should work:
kubectl config view --minify | grep namespace:
Upvotes: 0
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
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