Amazon EKS (k8s) namespace cannot be deleted (stuck terminating status)
AWS/EKS
outline
When you are trying to delete namespace of k8s, the status may become stuck in terminating, occasionally because of “finalizer” of k8s.
script
#!/bin/bash
# Define the stuck namespace as a variable
NAMESPACE=$1
# Check if the namespace is provided
if [ -z "$NAMESPACE" ]; then
echo "Usage: $0 <namespace>"
exit 1
fi
# Check if the namespace exists
if ! kubectl get namespace "$NAMESPACE" > /dev/null 2>&1; then
echo "Namespace \"$NAMESPACE\" does not exist."
exit 1
fi
# Get the current Kubernetes context
CURRENT_CONTEXT=$(kubectl config current-context)
# Display the current context and the namespace to be deleted
echo "Current Kubernetes context: $CURRENT_CONTEXT"
echo "The namespace you want to delete is: $NAMESPACE"
# Ask for user confirmation to proceed
read -p "Do you want to delete \"$NAMESPACE\" namespace? Type 'yes' to continue: " CONFIRMATION
# Check if the user input is 'yes'
if [ "$CONFIRMATION" != "yes" ]; then
echo "Operation cancelled."
exit 1
fi
# Export the namespace JSON to a temporary file
kubectl get namespace "$NAMESPACE" -o json > tempfile.json
# Remove the finalizers block from the JSON file
jq 'del(.spec.finalizers)' tempfile.json > tempfile_modified.json
# Apply the modified JSON file to remove the stuck namespace
kubectl replace --raw "/api/v1/namespaces/$NAMESPACE/finalize" -f ./tempfile_modified.json
# Check if the namespace is removed
kubectl get namespaces
# Clean up the temporary files
rm tempfile.json tempfile_modified.json
echo "Namespace $NAMESPACE should be removed."
usage
# chmod +x ns_remove.sh
# ./ns_remove.sh <namespace_want_to_remove>