Removing Stuck Namespaces from Kubernetes

Sometimes, I found some namespace stuck at the “Terminating” phase. Not just it’s annoying but it also led to other Kubernetes objects stuck at the same phase too, even if said objects aren’t part of this problematic namespace. I’ve found a solution in the Stackoverflow1Namespace “stuck” as Terminating to easily remove these problematic namespaces.

#!/bin/sh

for ns in $(kubectl get ns --field-selector status.phase=Terminating -o jsonpath='{.items[*].metadata.name}')
do
  kubectl get ns $ns -ojson | jq '.spec.finalizers = []' | kubectl replace --raw "/api/v1/namespaces/$ns/finalize" -f -
done

for ns in $(kubectl get ns --field-selector status.phase=Terminating -o jsonpath='{.items[*].metadata.name}')
do
  kubectl get ns $ns -ojson | jq '.metadata.finalizers = []' | kubectl replace --raw "/api/v1/namespaces/$ns/finalize" -f -
done

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.