Kubernetes: deleting all evicted pods using kubectl

If there is a Kubernetes event that causes mass eviction of pods, it is important to understand the root cause to rule out real issues in the system.  However, at some point in your investigation you will want to remove the evicted pods so they do not lead to exhaustion of IP addresses and also stop littering the kubectl output.

This Bash snippet can delete all evicted pods in all namespaces.

IFS=$'\n'
for line in $(kubectl get pods -A | awk {'printf "%s,%s,%s\n", $1,$2,$4'} | grep -E "Evicted"); do 
  ns=$(echo $line | cut -d',' -f1)
  pod=$(echo $line | cut -d',' -f2)
  kubectl delete pod -n $ns $pod
done

If you wanted to include pods which were evicted or terminated, you could change the regex grep to “Evicted|Terminated”.

There are additional flags that can be used to force the deletion “–force=true”, “–wait=false”, and “–grace-period=0”

 

REFERENCES

studytonight.com, delete evicted pods to avoid IP exhaustion

computingforgeeks.com, force deletion of evicted/terminated pods

codepre.com, force removal of evicted pods