1

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.

Mike
  • 1,080
  • 1
  • 9
  • 25

2 Answers2

1

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}}'
P....
  • 17,421
  • 2
  • 32
  • 52
  • I can't believe I didn't think to use the `--output=go-template` and `--template` flags. What if I was interested in `pods` from 10 or 20 different `namespaces` out of hundreds? This wasn't in my original question, but would you be able to add a GoLang template that's easier to scale with to your answer? Is there a GoLang template that does not need to check and see if a `pod`'s `namespace` is equal to any of the 10 or 20 I would be looking for? Thank you. – Mike May 17 '22 at 00:54
  • I dont think, scaling it to higher number of namespace is possible without using an OR condition for each namespace. – P.... May 17 '22 at 01:35
0

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'
Mike
  • 1,080
  • 1
  • 9
  • 25