How to get the pods from the namespaces with a particular label?

2/27/2020

It is possible to get all the pods on the cluster:

kubectl get pod --all-namespaces -o wide

It is also possible to get all pods on the cluster with a specific label:

kubectl get pod --all-namespaces -o wide --selector some.specific.pod.label

It is even possible to get all pods on the specific node of the cluster:

kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>

The question is, how to get all pods from the namespaces with a particular label?

e.g. kubectl get pod --namespace-label some.specific.namespace.label -o wide (pseudocode)

-- Ilya Buziuk
kubectl
kubernetes
kubernetes-pod

1 Answer

2/28/2020

One cannot do that operation in one shot, because labels on Namespace objects are not propagated down upon their child objects. Since kubectl is merely doing a GET on /api/v1/whatevers there is no obvious way to make a REST request to two endpoints at once and join them together.

You'll want either a for loop in shell, or to use one of the many API client bindings to create a program that does the Namespace fetch, then a Pod fetch for those matching Namespaces; for example:

for n in $(kubectl get ns --selector some.specific.namespace.label -o name); do
    # it's possible kubectl -n will accept the "namespace/foo" output of -o name
    # or one can even -o gotemplate="{{ .Name }}"
    n=${n##namespace/}
    kubectl -n "$n" get pods -o wide
done
-- mdaniel
Source: StackOverflow