Home > OS >  Specifying Which Kubernetes Namespaces to Display Resources from with the CLI Only
Specifying Which Kubernetes Namespaces to Display Resources from with the CLI Only

Time:05-13

Is it possible to display Kubernetes (K8s) resources from multiple specified namespaces with only the CLI (kubectl)?

In other words, given two namespaces in a K8s cluster:

kubectl get namespaces \
--output=go-template \
--template='{{ range .items }}{{ .metadata.name }}{{ "\n" }}{{ end }}'

#=>

. . .
$SOME_NAMESPACE
. . .
$ANOTHER_NAMESPACE
. . .

would it be possible to get resources (such as pods) from only those two namespaces ($SOME_NAMESPACE and $ANOTHER_NAMESPACE) using only kubectl?

Supplying the --all-namespaces flag and filtering using either the --field-selector or --selector flags will not work, because both flags accept only =, == and != operators.

CodePudding user response:

According to the discussion that has already occurred in this GitHub issue, it does not currently seem possible to specify multiple namespaces: either with just the --namespace flag alone or using a filtering flag such as --selector.

You can, for now, use workarounds such as Bash brace expansion, as suggested here, or feeding the output of the get command with the --all-namespaces flag into awk:

kubectl get pods \
--all-namespaces \
| awk \
-v SOME_NAMESPACE=$SOME_NAMESPACE \
-v ANOTHER_NAMESPACE=$ANOTHER_NAMESPACE \
'$1 == SOME_NAMESPACE || $1 == ANOTHER_NAMESPACE'

CodePudding user response:

You may use go-template to print the name of the pods belonging to the two namespaces, following is an example of printing pods from the test-1 and test-2 namespace.

kubectl get pod -A -o go-template='{{range .items}}{{if or (eq .metadata.namespace "test-1") (eq .metadata.namespace "test-2") }}{{printf "%s %s\n" .metadata.namespace .metadata.name}}{{end}}{{end}}'
  • Related