Prevents unempty namespace deletion

Viewed 174

I have constraint template yaml code policy to prevent all namespaces deletion.

Now I want to create a policy to prevent only non-empty namespace deletion, i.e, which containing a resource like pod, ingress, pv, pvc, secret, service, etc.

Therefore empty namespace should be able to be deleted but namespace which contains content should not be able to be deleted.

Any suggestions on this?

Template:

apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
  metadata:
    name: k8snamespacecannotbedeleted 
  spec:
    crd:
      spec:
        names:
          kind: K8sNamespaceCannotBeDeleted 
      targets:
        - target: admission.k8s.gatekeeper.sh
          rego: |
            package kubernetes.admission     
            violation[{"msg": msg}] {
              input.review.kind.kind == "Namespace"
              input.review.operation == "DELETE"
              msg := "[OPA] Namespace deletions are not permitted"         
            }

Constraint:

apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sNamespaceCannotBeDeleted
metadata:
  name: namespace-cannot-be-deleted
spec:
  match:
    kinds:
      - apiGroups: [""]
        kinds: ["Namespace"]
1 Answers

its probably a bit too late, but this is how i would approach this problem:

first step: create a cronjob in your fav language that call API server, run that every x min to check for non empty namespaces, add an annotation to those namespaces, like "can_delete" : "no"

second step:

Edit your rego code and check if there is any annotations called "can_delete", if yes, and its set to "no", prevent deletion

Related