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.

1
2
3
4
5
$ kubectl get ns
NAME              STATUS        AGE
apps              Active        2d19h
default           Active        3d8h
my-apps           Terminating   11h

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:

1
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --show-labels --ignore-not-found -n <your_namespace>

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 “” with your namespace itself:

1
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('http://127.0.0.1:8001/api/v1/namespaces/{}/finalize'.format(namespace), json=data).raise_for_status()"