How to force deletion of a namespace stuck in a terminating state
Overview/Background
In certain scenarios, you may observe that Kubernetes namespaces get stuck in a terminating state. Typically, this is due to resources existing in the namespace or finalizers. However, there are certain cases where there are no resources in the namespace and manually removing finalizers via `kubectl edit` does not resolve the issue. One such example is when an apiservice is unavailable, and many more scenarios can be found in the following GitHub issues: https://github.com/kubernetes/kubernetes/issues/77086 https://github.com/kubernetes/kubernetes/issues/60807
Solution
To resolve this issue, first ensure that there are no resources in the namespace:
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n <namespace>
If there are any resources in the namespace, you will want to remove them. After you have determined that there are no resources in the namespace, you can force deletion of the namespace by making an API call directly to the kube-apiserver to finalize the namespace:
kubectl proxy & PID=$! kubectl get namespace -o json | \ jq '.spec.finalizers=[]' | \ NO_PROXY=127.0.0.1 curl -vvv -X PUT http://127.0.0.1:8001/api/v1/namespaces/<namespace>/finalize -H "Content-Type: application/json" --data @- kill $PID
After performing the steps above, check the namespaces in the cluster and ensure that the namespace was deleted as expected:
kubectl get namespaces