'delete kubernetes pods which status shows 'CrashLoopBackOff' via shell script

I trying to write a script to delete pods status CrashLoopBackOff from all namespaces.

#!/bin/bash
# This script is basically check all avialble namespaces 
# and delete pods in any particular status like 'Evicted',
# 'CrashLoopBackOff','Terminating'

NAMESPACE="popeye"
delpods2=$(sudo kubectl get pods -n ${NAMESPACE} |
  grep -i 'CrashLoopBackOff' |
  awk '{print $1 }')    

for i in ${delpods2[@]}; do

  sudo kubectl delete pod $i --force=true --wait=false \
    --grace-period=0 -n ${NAMESPACE}
    
done

The above script works with a specified namespace but how we can set if I have multiple namespaces and check for the pods in each one.



Solution 1:[1]

I would suggest a better way for doing this. You can simply run

kubectl delete pods --field-selector status.phase=Failed --all-namespaces

This way is much simple and neat. However, note that this doesn't delete evicted and CrashLoopBackOff pods only , but also pods that have failed due to different reasons ("ContainerCannotRun", "Error", "ContainerCreating", etc.).

We can also make this even better. Using -A instead of --all-namespaces.

So, the final command is

kubectl delete pods --field-selector status.phase=Failed -A

Happy Hacking!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mostafa Wael