Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading