[Solved] Kubernetes Namespace stuck in Terminating state

If you have tried to delete a Kubernetes namespace, and it has been hanging in ‘deleting’ for hours on end, it’s likely that you have dangling resources that have not deleted yet.

$ kubectl get ns NAME STATUS AGE apps Active 2d19h default Active 3d8h my-apps Terminating 11h
Code language: plaintext (plaintext)

This will prevent the namespace from being removed.

How to find resources that need to be deleted

You can chain the api-resources verbs along with a kubectl get to find dangling resources:

kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --show-labels --ignore-not-found -n <your_namespace>
Code language: Bash (bash)

This will run through all API Resources available in your cluster and report if they are found in that namespace.

Now you can simply go and kubectl delete <resource> to each one as you find them.

A 1-liner to delete the problem namespace

If you are still not able to delete the namespace, then you can use the following 1-liner Python script.

Make sure to replace “<my-namespace>” with your namespace itself:

python3 -c "namespace='<my-namespace>';import atexit,subprocess,json,requests,sys;proxy_process = subprocess.Popen(['kubectl', 'proxy']);atexit.register(proxy_process.kill);p = subprocess.Popen(['kubectl', 'get', 'namespace', namespace, '-o', 'json'], stdout=subprocess.PIPE);p.wait();data = json.load(p.stdout);data['spec']['finalizers'] = [];requests.put('{}/finalize'.format(namespace), json=data).raise_for_status()"
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments