Home > OS >  How do I delete a Kubernetes Namespace with a Cronjob?
How do I delete a Kubernetes Namespace with a Cronjob?

Time:12-01

I have a cron that's I'm testing for another project that is supposed to delete a namespace called "test" every minute.

I have set up a ServiceAccount, ClusterRole, and RoleBinding as shown below:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: test
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: test
rules:
- apiGroups: [""]
  resources: ["namespaces"]
  verbs: ["delete", "get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: test # This will bind the role and service account
subjects:
- kind: ServiceAccount
  name: test
roleRef:
  kind: ClusterRole
  name: test
  apiGroup: rbac.authorization.k8s.io

My Cronjob is as follows:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: kill-ns
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: test
          containers:
          - name: kill-ns
            image: bitnami/kubectl:latest
            command:
            - kubectl
            args:
            - delete
            - namespace
            - test
          restartPolicy: Never

I get the following error on from the job.

Error from server (Forbidden): namespaces "test" is forbidden: User "system:serviceaccount:default:test" cannot delete resource "namespaces" in API group "" in the namespace "test"

I thought my apiGroups was the issue it was not. apiGroups is [""] for namespaces.

I'm currently using docker desktop locally.

Edit: I am deploying the job in the default namespace.

CodePudding user response:

You have to use ClusterRoleBinding instead of RoleBinding. RoleBinding only allows access to resources in the namespace of the service account while ClusterRoleBinding allows cluster-wide access.

  • Related