Sha
Sha

Reputation: 41

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.

Upvotes: 0

Views: 2763

Answers (2)

Doddabasappa
Doddabasappa

Reputation: 11

You can try this:

kubectl get pods --all-namespaces | grep 'CrashLoopBackOff' | awk '{print $2 " --namespace=" $1}' | xargs kubectl delete pod

Upvotes: 1

Mostafa Wael
Mostafa Wael

Reputation: 3846

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!

Upvotes: 1

Related Questions