# Clean up finished Jobs with a Kyverno DeletingPolicy

> Delete finished Kubernetes Jobs on a schedule with a Kyverno DeletingPolicy: RBAC, CEL conditions, propagation, CLI tests and troubleshooting.

Published: 2026-12-03
Author: k8wiz Team
URL: https://k8wiz.com/articles/kyverno-deletingpolicy-clean-up-finished-jobs

Jobs pile up. A CI system, a migration tool or an operator creates one, it finishes, and nobody removes it. Each finished Job keeps its Pods around for log access, so a busy namespace can collect thousands of objects that the API server, etcd and every controller watching Pods have to carry. Kubernetes has `ttlSecondsAfterFinished` for this, but only if whoever creates the Job remembers to set it.

Kyverno's `DeletingPolicy` cleans up after the fact. It runs on a cron schedule, lists the resources you match, evaluates CEL conditions against each one and deletes those that pass. In Kyverno 1.20 it replaces the legacy `ClusterCleanupPolicy`, which no longer runs. This guide builds a policy that removes Jobs that finished more than a day ago, tests it with the Kyverno CLI, and covers the four reasons a `DeletingPolicy` quietly deletes nothing.

## Step 1: check the controller and the CRD

A `DeletingPolicy` is not an admission policy. No webhook is involved, and nothing happens when a Job is created. The cleanup controller holds the schedule, wakes up at each cron tick and does the listing and deleting itself. If that controller is not running, the policy is accepted and never acts.

```bash
kubectl get crd deletingpolicies.policies.kyverno.io
kubectl -n kyverno get deployment kyverno-cleanup-controller
```

The deployment name assumes a Helm release called `kyverno` in the `kyverno` namespace. In Kyverno 1.20 the CRD serves `policies.kyverno.io/v1`, and the short name is `dpol`. A namespaced variant, `NamespacedDeletingPolicy` (short name `ndpol`), has the same spec but only acts on resources in its own namespace.

## Step 2: give the cleanup controller permission to delete Jobs

The cleanup controller deletes resources with its own service account. The Helm chart grants that account access to Kyverno's own objects, Namespaces, ConfigMaps and Events, but not to Jobs or Pods. You have to add the permissions for every kind a policy targets.

The chart's cleanup controller ClusterRole is an aggregated role. Any ClusterRole that carries the label `rbac.kyverno.io/aggregate-to-cleanup-controller: "true"` has its rules merged in, so you can grant access without changing Helm values.

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kyverno-cleanup-jobs
  labels:
    rbac.kyverno.io/aggregate-to-cleanup-controller: "true"
rules:
  - apiGroups: ["batch"]
    resources: ["jobs"]
    verbs: ["get", "list", "watch", "delete"]
```

Apply it and confirm that the service account now has the access. The service account name follows the same release name assumption as before.

```bash
kubectl apply -f clusterrole-cleanup-jobs.yaml
kubectl auth can-i delete jobs.batch --all-namespaces \
  --as=system:serviceaccount:kyverno:kyverno-cleanup-controller
kubectl auth can-i list jobs.batch --all-namespaces \
  --as=system:serviceaccount:kyverno:kyverno-cleanup-controller
```

Both commands should print `yes`. If you manage the chart through values instead, `cleanupController.rbac.clusterRole.extraResources` takes the same list of rules.

## Step 3: choose which namespaces the policy touches

A cleanup policy deletes data, so start narrow. An opt-in label on the namespace lets teams decide whether their Jobs are cleaned up, and keeps the policy away from namespaces you didn't think about. Label the namespaces you want included.

```bash
kubectl label namespace batch-ci cleanup.example.com/finished-jobs=true
```

When a cluster-scoped `DeletingPolicy` has a `namespaceSelector`, the controller lists the matching namespaces first and then lists Jobs in each of them. Without a selector it lists Jobs across the whole cluster in pages of 500. An `objectSelector` is passed to the list call as a label selector, so it narrows what the API server returns before any CEL runs.

## Step 4: write the policy

The policy below runs at the top of every hour. It matches `batch/v1` Jobs in opted-in namespaces and deletes those that finished, successfully or not, more than 24 hours ago.

```yaml
apiVersion: policies.kyverno.io/v1
kind: DeletingPolicy
metadata:
  name: cleanup-finished-jobs
spec:
  schedule: "0 * * * *"
  deletionPropagationPolicy: Background
  matchConstraints:
    resourceRules:
      - apiGroups: ["batch"]
        apiVersions: ["v1"]
        resources: ["jobs"]
    namespaceSelector:
      matchLabels:
        cleanup.example.com/finished-jobs: "true"
  conditions:
    - name: not-owned-by-cronjob
      expression: >-
        !has(object.metadata.ownerReferences) ||
        !object.metadata.ownerReferences.exists(r, r.kind == 'CronJob')
    - name: finished-over-a-day-ago
      expression: >-
        has(object.status.conditions) &&
        object.status.conditions.exists(c,
          (c.type == 'Complete' || c.type == 'Failed') &&
          c.status == 'True' &&
          timestamp(c.lastTransitionTime) < time.now() - duration('24h'))
```

Every entry in `conditions` must evaluate to true for a resource to be deleted, and an empty list matches everything the constraints select. The first condition leaves Jobs created by a CronJob alone, because a CronJob already prunes its own history through `successfulJobsHistoryLimit` and `failedJobsHistoryLimit`. The second looks for a `Complete` or `Failed` condition and compares its `lastTransitionTime` with `time.now()`, a function from Kyverno's CEL time library that returns the current timestamp.

The `resourceRules` entry has no `operations` field. A deletion scan is not an API request, so Kyverno doesn't check operations when it matches a resource. You will see `operations: ["*"]` or `["DELETE"]` in some examples, and either works.

### Why deletionPropagationPolicy matters for Jobs

`deletionPropagationPolicy` accepts `Foreground`, `Background` or `Orphan`. When you leave it out, Kyverno sends the delete without a propagation policy and the API server uses the default for that resource. For `batch/v1` Jobs the default is to orphan dependents, kept for backward compatibility. The Job disappears and its Pods stay behind with no owner, which is the opposite of what a cleanup policy is for.

`kubectl delete job` hides this because kubectl sends `Background` by default. A `DeletingPolicy` calls the API directly, so set `Background` (or `Foreground` if you want the Job to remain until its Pods are gone).

## Step 5: test the policy with the Kyverno CLI

`kyverno test` can evaluate a `DeletingPolicy` against sample resources, which tells you what the next run would delete before anything is deleted. Put the policy in `policy.yaml` and add three Jobs to `resources.yaml`: one that finished long ago, one still running, and one that finished long ago in a namespace without the opt-in label.

```yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: old-report
  namespace: batch-ci
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: report
          image: busybox:1.36
          command: ["true"]
status:
  conditions:
    - type: Complete
      status: "True"
      lastTransitionTime: "2026-01-15T10:00:00Z"
---
apiVersion: batch/v1
kind: Job
metadata:
  name: running-report
  namespace: batch-ci
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: report
          image: busybox:1.36
          command: ["sleep", "3600"]
status:
  active: 1
---
apiVersion: batch/v1
kind: Job
metadata:
  name: old-backup
  namespace: payments
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: backup
          image: busybox:1.36
          command: ["true"]
status:
  conditions:
    - type: Complete
      status: "True"
      lastTransitionTime: "2026-01-15T10:00:00Z"
```

The CLI has no cluster to read namespace labels from, so a `values.yaml` file supplies the Namespace objects that the `namespaceSelector` is checked against.

```yaml
apiVersion: cli.kyverno.io/v1alpha1
kind: Value
metadata:
  name: values
namespaces:
  - apiVersion: v1
    kind: Namespace
    metadata:
      name: batch-ci
      labels:
        cleanup.example.com/finished-jobs: "true"
  - apiVersion: v1
    kind: Namespace
    metadata:
      name: payments
```

In the test file, `isDeletingPolicy: true` marks results that come from a `DeletingPolicy`. A `pass` means the resource matched and every condition was true, so it would be deleted. A `fail` means it matched but a condition was false, and a `skip` means the match constraints or selectors excluded it.

```yaml
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
  name: cleanup-finished-jobs
policies:
  - policy.yaml
resources:
  - resources.yaml
variables: values.yaml
results:
  - isDeletingPolicy: true
    kind: Job
    policy: cleanup-finished-jobs
    resources:
      - batch-ci/old-report
    result: pass
  - isDeletingPolicy: true
    kind: Job
    policy: cleanup-finished-jobs
    resources:
      - batch-ci/running-report
    result: fail
  - isDeletingPolicy: true
    kind: Job
    policy: cleanup-finished-jobs
    resources:
      - payments/old-backup
    result: skip
```

Save it as `kyverno-test.yaml` in the same directory and run the test.

```bash
kyverno test .
```

The policy calls `time.now()`, so keep the sample timestamps well in the past. A fixed date that is only a few hours old would start failing the test as soon as the clock moved past it.

## Step 6: apply the policy and watch the first run

Apply the policy, then check when it last ran.

```bash
kubectl apply -f policy.yaml
kubectl get dpol cleanup-finished-jobs -o jsonpath='{.status.lastExecutionTime}{"\n"}'
```

The first run is the next cron tick after the policy's creation time. After each run the controller writes `status.lastExecutionTime` and schedules the next tick from there. With `"0 * * * *"` you may wait up to an hour, so for a first trial in a test cluster use `"*/5 * * * *"` and change it back once you trust the result.

Each deletion produces a Kubernetes Event with reason `PolicyApplied`, reported by the `kyverno-cleanup` component. The Event refers to the policy and names the deleted Job in its `related` field and in a message such as `successfully deleted the target resource Job/batch-ci/old-report`. A failed delete produces a `PolicyError` Event instead.

```bash
kubectl get events -A --field-selector reason=PolicyApplied
kubectl get events -A --field-selector reason=PolicyError
```

These Events are your audit trail. Events expire after the API server's event TTL (one hour by default), so ship them to your log system if you need a longer record of what was deleted.

## Step 7: find out why nothing was deleted

A `DeletingPolicy` that deletes nothing reports no error on the policy itself. Work through these causes in order.

### The controller can't list or delete the kind

When the controller gets a forbidden error while listing a resource type, it treats the error as permanent, skips that type and moves on. The only trace is a log line in the cleanup controller.

```bash
kubectl -n kyverno logs deploy/kyverno-cleanup-controller | grep "skipping resource due to access restrictions"
```

If you see it, go back to step 2. The same applies to every kind you add to `resourceRules` later.

### The resource is excluded by resourceFilters

The cleanup controller honors the `resourceFilters` list in the Kyverno ConfigMap and skips any resource that matches it. The chart's default list includes everything in `kube-system`, `kube-public` and `kube-node-lease`, and every `ReplicaSet`. A policy that targets empty ReplicaSets or Jobs in `kube-system` therefore does nothing on a default install. Check what is filtered before you blame the CEL.

```bash
kubectl -n kyverno get configmap kyverno -o jsonpath='{.data.resourceFilters}{"\n"}'
```

### The selectors or conditions don't match

Run the CLI test from step 5 against an exported copy of the real resource. Export it with `kubectl get job <name> -n <namespace> -o yaml`, add it to `resources.yaml` and its namespace with labels to `values.yaml`. A `skip` points at the constraints or selectors, a `fail` at a condition.

### The schedule hasn't fired yet

Compare `status.lastExecutionTime` with the cron expression. A policy created at 10:05 with an hourly schedule first runs at 11:00, not at 10:05.

## When to use ttlSecondsAfterFinished instead

If you control the code that creates the Jobs, set `spec.ttlSecondsAfterFinished` there. The Kubernetes TTL controller deletes the Job and its Pods when the time is up, with no extra RBAC and no schedule. A `DeletingPolicy` is the right tool for Jobs you don't control, such as those created by third-party operators or CI runners, and for any other kind that has no built-in expiry. The same pattern works for ConfigMaps, Secrets or custom resources once you grant the controller access to them.
