Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent kubectl from deleting namespace with resources

Is there a way to configure Kubernetes (or kubectl) so that an attempt to delete a namespace that has Kubernetes resources will result in an error?

Here is an example:

$ kubectl create ns testing
namespace/testing created
$ kubectl apply -n testing -f pod-nginx.yaml 
pod/example-pod created
$ kubectl get -n testing pods
NAME          READY   STATUS    RESTARTS   AGE
example-pod   1/1     Running   0          5s
$ kubectl delete ns testing
namespace "testing" deleted
$ kubectl get -n testing pods
No resources found in testing namespace.

What I want is for the delete command (kubectl delete ns testing) to not delete anything, but rather to return with an error of the form "cannot delete namespace because it contains resources".

Is this possible?

like image 240
rlandster Avatar asked Nov 16 '25 01:11

rlandster


1 Answers

Unfortunately, I am not aware of any way to do this the way you expect it to work. The best solution I could come up with is to use RBAC to prevent users from deleting namespaces. It's not what you are asking for but it's probably the closest you are going to get:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: restricted-user
rules:
  - apiGroups: [""]
    resources: ["namespace"]
    verbs: ["get", "list", "watch", "create", "update", "patch"]
[...]

Then depending if you want to apply this namespace by namespace or cluster wide you can use a ClusterRoleBinding or RoleBinding

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: restricted-users
  namespace: my-namespace
subjects:
- kind: User
  name: jane
  apiGroup: rbac.authorization.k8s.io
[...]
roleRef:
  kind: ClusterRole
  name: restricted-user
[...]

or:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: restricted-users
subjects:
  - kind: User
    name: jane
    apiGroup: rbac.authorization.k8s.io
[...]
roleRef:
  kind: ClusterRole
  name: restricted-user
  apiGroup: rbac.authorization.k8s.io
[...]

This is just a quick example. You would usually setup Groups and a bunch of different [Cluster]Roles and [Cluster]RoleBindings. You can find more examples Here

like image 75
ITChap Avatar answered Nov 17 '25 15:11

ITChap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!