Created
December 16, 2024 00:07
-
-
Save seanslma/8ae04d242902a3eae83b02e8cd1d36dc to your computer and use it in GitHub Desktop.
Delete pods in kubernetes that are with the status of either completed or error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Check if kubectl is configured to connect to the AKS cluster | |
if ! command -v kubectl &> /dev/null | |
then | |
echo "kubectl could not be found. Please install kubectl and configure it to access your AKS cluster." | |
exit 1 | |
fi | |
# Get the list of pods that are either in Completed or Error state | |
echo "Fetching pods in Completed (Succeeded) or Error (Failed) state..." | |
PODS=$(kubectl get pods --all-namespaces -o custom-columns="NAMESPACE:.metadata.namespace,POD:.metadata.name,STATUS:.status.phase" | grep -E 'Succeeded|Failed') | |
# Check if any such pods are found | |
if [[ -z "$PODS" ]]; then | |
echo "No Completed or Error pods found." | |
exit 0 | |
fi | |
# Loop through each pod and delete it | |
echo "Deleting Completed or Error pods..." | |
while read -r line | |
do | |
# Extract namespace, pod name, and pod status | |
NAMESPACE=$(echo $line | awk '{print $1}') | |
POD=$(echo $line | awk '{print $2}') | |
STATUS=$(echo $line | awk '{print $3}') | |
# Delete the pod | |
echo "Deleting pod $POD in namespace $NAMESPACE with status $STATUS..." | |
kubectl delete pod -n $NAMESPACE $POD | |
done <<< "$PODS" | |
echo "Completed deleting all Completed or Error pods." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment