<p>Is there a way to configure Kubernetes (or <code>kubectl</code>) so that an attempt to delete a namespace that has Kubernetes resources will result in an error?</p>
<p>Here is an example:</p>
<pre><code>$ 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 &quot;testing&quot; deleted
$ kubectl get -n testing pods
No resources found in testing namespace.
</code></pre>
<p>What I <em>want</em> is for the delete command (<code>kubectl delete ns testing</code>) to <em>not</em> delete anything, but rather to return with an error of the form &quot;cannot delete namespace because it contains resources&quot;.</p>
<p>Is this possible?</p>

rlandster
<p>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:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: restricted-user
rules:
  - apiGroups: [&quot;&quot;]
    resources: [&quot;namespace&quot;]
    verbs: [&quot;get&quot;, &quot;list&quot;, &quot;watch&quot;, &quot;create&quot;, &quot;update&quot;, &quot;patch&quot;]
[...]
</code></pre>
<p>Then depending if you want to apply this namespace by namespace or cluster wide you can use a <code>ClusterRoleBinding</code> or <code>RoleBinding</code></p>
<pre class="lang-yaml prettyprint-override"><code>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
[...]
</code></pre>
<p>or:</p>
<pre class="lang-yaml prettyprint-override"><code>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
[...]
</code></pre>
<p>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 <a href="https://kubernetes.io/docs/reference/access-authn-authz/rbac" rel="nofollow noreferrer">Here</a></p>
