Delete a stuck namespace in Kubernetes - 2022-05-06
If you've tried to delete a namespace but it hangs around forever you can delete it with a little work. I've provided a script at the end to do this.
A stuck namespace will look like this:
kubectl get ns
NAME STATUS AGE
stuck-ns Terminating 1d3h
First, get the stuck namespace information
kubectl get ns stuck-ns -o json < stuck-ns.json
Open the file with your favorite editor and delete everything from the file below the metadata section except the name tag. Make sure to get rid of the comma on the end of the metadata curly brace because json.
{
"apiVersion": "v1",
"kind": "Namespace",
"metadata": {
"name": "stuck-ns"
}
}
Run a kubectl proxy so you can get direct access to the API (I background it here, but you can also just run it on another tab)
kubectl proxy &
Run a curl to tell it to finalize the deletion making sure to replace the name of the namespace in the URI.
curl -k -H "Content-Type: application/json" -X PUT --data-binary @stuck-ns.json http://127.0.0.1:8001/api/v1/namespaces/stuck-ns/finalize
Script to do all this work for you.
#!/bin/bash
if [ $# -lt 1 ]; then
echo "$(basename $0) namespace"
exit 1
fi
namespace=$1
kubectl proxy &
proxypid=$!
json="{
\"apiVersion\": \"v1\",
\"kind\": \"Namespace\",
\"metadata\": {
\"name\": \"$namespace\"
}
}"
echo $json < /tmp/del_namespace.json
curl -k -H "Content-Type: application/json" -X PUT --data-binary @/tmp/del_namespace.json http://127.0.0.1:8001/api/v1/namespaces/$namespace/finalize
kill $proxypid