Cleaning Up Forgotten Kubernetes Resources with kube-janitor
Test deployments, pull-request environments and unused volumes pile up quietly and cost money. kube-janitor deletes them on a schedule you define.
How it works
kube-janitor scans all namespaces and namespaced resources, including custom resources. It deletes a resource when:
- its
janitor/ttlannotation says it has lived long enough (for example24hor7d), - its
janitor/expiresannotation gives a date and time that has passed, or - a rule in the rules file matches it and its TTL has run out.
Install
The project lives on Codeberg. Deploy it from the repository with Kustomize:
git clone https://codeberg.org/hjacobs/kube-janitor.git
cd kube-janitor
kubectl apply -k deploy/
This deploys to the default namespace. For another namespace, edit deploy/rbac.yaml first.
The example configuration runs with --dry-run, so it only logs what it would delete. Keep it that way until the logs look right, then remove the flag:
kubectl edit deploy kube-janitor
Try it
Create a throwaway deployment and give it five minutes to live:
kubectl create deployment temp-nginx --image=nginx
kubectl annotate deploy temp-nginx janitor/ttl=5m
Or delete it at a fixed time instead:
kubectl annotate deploy temp-nginx janitor/expires=2026-12-31T00:00:00Z
Rules for things nobody annotates
Annotations need people to remember them. Rules don't. Each rule matches resources with a JMESPath expression and gives them a TTL. These delete pull-request deployments after 4 hours, and PVCs that no pod mounts and no StatefulSet references after 4 days:
rules:
- id: cleanup-pr-deployments
resources:
- deployments
jmespath: "starts_with(metadata.name, 'pr-')"
ttl: 4h
- id: remove-unused-pvcs
resources:
- persistentvolumeclaims
jmespath: "_context.pvc_is_not_mounted && _context.pvc_is_not_referenced"
ttl: 4d
The rules live in the kube-janitor ConfigMap. Edit it, then restart the pod to load the changes:
kubectl edit configmap kube-janitor
kubectl rollout restart deploy kube-janitor
Resources with their own janitor/ttl annotation skip the rules. The first matching rule wins.
What about the volumes?
kube-janitor works on namespaced resources like PVCs. PersistentVolumes are cluster-scoped. What happens to the disk once its PVC is deleted depends on the volume's reclaim policy: Delete frees it, Retain keeps it for manual cleanup.
Check it's working
kubectl logs deploy/kube-janitor
kubectl get pvc --all-namespaces
Compare what's listed before and after a run. In dry-run mode, the logs show exactly what would have been deleted.
Start in a non-production cluster. A janitor with the wrong rule deletes things just as efficiently as one with the right rule.