All Policies

Cleanup Empty ReplicaSets

ReplicaSets serve as an intermediate controller for various Pod controllers like Deployments. When a new version of a Deployment is initiated, it generates a new ReplicaSet with the specified number of replicas and scales down the current one to zero. Consequently, numerous empty ReplicaSets may accumulate in the cluster, leading to clutter and potential false positives in policy reports if enabled. This cleanup policy is designed to remove empty ReplicaSets across the cluster within a specified timeframe, for instance, ReplicaSets created one day ago, ensuring the ability to rollback to previous ReplicaSets in case of deployment issues

Policy Definition

/cleanup/cleanup-empty-replicasets/cleanup-empty-replicasets.yaml

 1#The described logic currently deletes the ReplicaSets created 30 seconds ago. You can adjust this timeframe according to your specific requirements.
 2apiVersion: kyverno.io/v2beta1
 3kind: ClusterCleanupPolicy
 4metadata:
 5  name: cleanup-empty-replicasets
 6  annotations:
 7    policies.kyverno.io/title: Cleanup Empty ReplicaSets
 8    policies.kyverno.io/category: Other
 9    policies.kyverno.io/severity: medium
10    policies.kyverno.io/subject: ReplicaSet
11    kyverno.io/kyverno-version: 1.11.1
12    policies.kyverno.io/minversion: 1.9.0
13    kyverno.io/kubernetes-version: "1.27"
14    policies.kyverno.io/description: >-
15      ReplicaSets serve as an intermediate controller for various Pod controllers like Deployments. When a new version of a Deployment is initiated, it generates a new ReplicaSet with the specified number of replicas and scales down the current one to zero. Consequently, numerous empty ReplicaSets may accumulate in the cluster, leading to clutter and potential false positives in policy reports if enabled. This cleanup policy is designed to remove empty ReplicaSets across the cluster within a specified timeframe, for instance, ReplicaSets created one day ago, ensuring the ability to rollback to previous ReplicaSets in case of deployment issues
16spec:
17  match:
18    any:
19    - resources:
20        kinds:
21          - ReplicaSet
22  exclude:
23    any:
24    - resources:
25        namespaces:
26          - kube-system
27  conditions:
28    all:
29    - key: "{{ target.spec.replicas }}"
30      operator: Equals
31      value: 0
32    - key: "{{ time_diff('{{target.metadata.creationTimestamp}}','{{ time_now_utc() }}') }}"
33      operator: GreaterThan
34      value: "0h0m30s"
35  schedule: "*/1 * * * *"