Sometimes, after issuing the command to delete the namespace, namespace will remain in Terminating state without getting deleted. It happened to be several times.

To delete the namespace stuck in terminating state, the following steps will be helpful.

First get the complete name of the namespace which is stuck in terminating state.

Command to list all namespaces is given below.

kubectl get namespaces

Now get the details of the finalizer of the terminating namespace

Save the namespace details in a temporary JSON file. The command is given below.

kubectl get namespace <terminating-namespace> -o json > temp.json

Open the JSON file and check the value of the key finalizers

A sample JSON is given below.

{
    "apiVersion": "v1",
    "kind": "Namespace",
    "metadata": {
        "annotations": {
            "kubectl.kubernetes.io/last-applied-configuration": "{"apiVersion":"v1","kind":"Namespace","metadata":{"annotations":{},"name":"<terminating-namespace>"}}"
        },
        "creationTimestamp": "2021-07-21T12:15:32Z",
        "managedFields": [
            {
                "apiVersion": "v1",
                "fieldsType": "FieldsV1",
                "fieldsV1": {
                    "f:metadata": {
                        "f:annotations": {
                            ".": {},
                            "f:kubectl.kubernetes.io/last-applied-configuration": {}
                        }
                    },
                    "f:status": {
                        "f:phase": {}
                    }
                },
                "manager": "kubectl-client-side-apply",
                "operation": "Update",
                "time": "2021-07-21T12:15:32Z"
            }
        ],
        "name": "<terminating-namespace>",
        "resourceVersion": "6886636",
        "selfLink": "/api/v1/namespaces/<terminating-namespace>",
        "uid": "43c64209-51bc-449e-8b1c-a8d45f0d0f8c"
    },
    "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },
    "status": {
        "phase": "Terminating"
    }
}

Remove the value kubernetes and update the value of the key finalizers to empty list.



"spec": {
        "finalizers": []
    }

Set a temporary proxy in the command line. The command to run a proxy is given below.

kubectl proxy

Once the proxy is started, we will be able to see the following output.

Starting to serve on 127.0.0.1:8001

Now keep the current terminal open and open another terminal.

In the newly opened terminal, execute the following command. We are making an API call with the locally stored JSON

curl -k -H "Content-Type: application/json" -X PUT --data-binary @temp.json http://127.0.0.1:8001/api/v1/namespaces/<terminating-namespace>/finalize

After running the above command, list the namespaces and check whether the terminating namespace is still present in the system or not.

kubectl get namespaces

I hope this tip is useful. Feel free to comment if you have any questions or suggestions.