How to Find and Delete Failing Kubernetes Pods with kubectl?
Sometimes we want to cleanup a bunch of pods that are failing to get scheduled or failing to execute after getting scheduled. Removal and cleanup of pods failing to execute can even help scale down your cluster workers and hence reduce costs. When I say failing pods, it means pods with statuses (that you see in kubectl get pods
) like:
- ErrImagePull
- NodeAffinity
- ImagePullBackOff
- CrashLoopBackOff
- Terminated
- Error
- ContainerStatusUnknown
- … so on and so forth
How can we filter out pods with these statuses from kubectl get pods
? With the help of awk
:
kubectl get po --all-namespaces | \
awk '{ if ($4 == "ErrImagePull" || $4 == "ImagePullBackOff" || $4 == "CrashLoopBackOff") { print } }'
And if you want to delete these pods, then you can further pass the pod name and namespace to kubectl delete pod
like this:
kubectl get po --all-namespaces | \
awk '{ if ($4 == "ErrImagePull" || $4 == "ImagePullBackOff" || $4 == "CrashLoopBackOff") { print } }' | \
awk '{ print $1, $2 }' | \
xargs -r -n2 kubectl delete pod -n