How to kill a stuck kubernetes namespace

If you are an hands on person dealing with cloud related technologies, such as container and kubernetes clusters, the following script could avoid you same headaches.

While playing with kuberentes, if it has not alredy happend to you, soon or later, you will stumble in a kubernetes namespace that remains in the “terminating” state for ever.

Usually this happens when a certain application is uninstalled in the wrong way or some weird bug led to this awkward situation.

If you don’t want, or you can’t, rebuild the entire cluster from scratch, forcing the deletion of the namespace can be a good option.

To force the deletion of a stuck namespace, you can try to run the following script by passing the problematic namespace. The only requirement is to have the kubectl command with the kube context properly configured against the target kubernetes cluster.



die() { echo "$*" 1>&2 ; exit 1; }

need() {
which "$1" &>/dev/null || die "Binary '$1' is missing but required"

need "kubectl"

test -n "$STUCK_NS" || die "Missing namespace: kill-ns <namespace>"

kubectl get namespace $STUCK_NS -o json | tr -d "\n" | sed "s/\"finalizers\": \[[^]]\+\]/\"finalizers\": []/"  | kubectl replace --raw /api/v1/namespaces/$STUCK_NS/finalize -f -