Kubernetes

How to delete Kubernetes namespaces or pods with a specific pattern or name

I had a need to delete a number of Namespaces all at once that were created as part of some automated platform testing.

Each namespace had a common naming convention starting with “e2e”, the below command will get all namespaces without the initial returned header line from Kubectl, look for anything with the pattern “e2e” using the awk command, and print them to a variable $1, xargs then uses each object in the variable array into the “kubectl delete ns”

kubectl get ns --no-headers=true | awk '/e2e/{print $1}'| xargs  kubectl delete ns

You can also do the same for deleting pods. The below command, would delete any pods with “veducate” in their name, you would need to input the necessary namespace.

kubectl get pods -n {namespace} --no-headers=true | awk '/veducate/{print $1}'| xargs  kubectl delete -n {namespace} pod

Quick link to this Stackoverflow post which pointed me in the right direction, I just had to modify it from pods to namespaces as the use case.

Regards

Dean Lewis

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.