Obtain warning about resources to be deleted in Kubernetes

10/31/2020

Instead of using Kubernetes' default namespace, it's a good practice to xreate separate namespaces for each of your applications or each logical component of your infrastructure.

OReilly's "Cloud Native DevOps with Kubernetes" highlights a relevant potential risk:

You could use a namespace as a kind of temporary virtual cluster, and delete the namespace when you’re finished with it. But be careful! Deleting a namespace deletes all the resources within it. You really don’t want to run that command against the wrong namespace. (...) So don’t delete namespaces unless they really are temporary, and you’re sure they don’t contain any production resources.

In Kubernetes' documentation on namespaces, I read a similar warning:

Warning: This deletes everything under the namespace!

Of course we need to be careful, but it's a scary thought that resources can be deleted this easily. Is there any way to get a warning about which resources will be removed with: kubectl delete namespaces <ns-name>?

-- Casper Dijkstra
devops
kubernetes

2 Answers

10/31/2020

When you delete a namespace, all namespaced resources in this namespace will be deleted. There's no direct way to list all the resources in a namespace (kubectl get all lists only a selected set of resources).

However, you can enumerate all namespaced resource types with:

kubectl get api-resources --namespaced=true

And you can then iterate through these resource types and check if you have any instances of them in your namespace with kubectl get.

For example, the following command lists all resources in the ns-name namespace:

for r in $(kubectl api-resources --namespaced=true --no-headers 2>/dev/null | cut -d ' ' -f 1); do 
  kubectl get "$r" -n ns-name --no-headers -o custom-columns=:.metadata.name | sed "s/^/$r /"
done

And this are all the resources that will be deleted when you delete the ns-name namespace.

-- weibeld
Source: StackOverflow

10/31/2020

There is no native way to get warning. You can check all the resources in the namespace using below command. When the namespace gets deleted all resources in that namespace is going to be deleted.

kubectl get all -n namespacename

Also a best practice is to keep kubernetes yamls in a version control system such as git so that you can apply them again in case of a deletion by mistake.

-- Arghya Sadhu
Source: StackOverflow