I was to get a list of my Kubernetes namespace based on a particular label

I am writing a bash script and I need the kubectl command to get all the namespace in my cluster based on a particular label.

kubectl get ns -l=app=backend

When I run the command above I get:
no resources found

>Solution :

only the pods in the ns have that label. wondering if there’s a way I can manipulate kubectl to output only the ns of the pods that have that label

You can combine a few commands to do something like:

kubectl get pods -A -l app=backend  -o json |
  jq -r '.items[]|.metadata.namespace' |
  sort -u

This gets a list of all pods in all namespaces that match the label selector; uses jq to extract the namespace name from each pod, and then uses sort -u to produce a unique list.


You can actually do this without jq by using the go-template output format, but for me that always means visiting the go template documentation:

kubectl get pods -A -l app=backend \
  -o go-template='{{range .items}}{{.metadata.namespace}}{{"\n"}}{{end}}' |
  sort -u

Leave a Reply