Deleting old pods using CronJob on OpenShift

Whenever I do a cluster install and after running a cluster for a while, the “Completed” pod references start to mount up in the GUI. Here’s a quick and dirty way to clean up old pods.

kind: ServiceAccount
apiVersion: v1
metadata:
  name: pod-cleaner
  namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: pod-list-delete-role
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["list", "delete"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: pod-cleaner-list-pods
subjects:
  - kind: ServiceAccount
    name: pod-cleaner
    namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: pod-list-delete-role
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: delete-completed-pods
  namespace: default
spec:
  schedule: "0 * * * *"  # Run every hour
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: pod-cleaner  # Specify the ServiceAccount created
          containers:
          - name: delete-completed-pods
            image: registry.redhat.io/openshift4/ose-cli:latest
            command:
            - /bin/sh
            - -c
            - |
              oc delete pod --field-selector=status.phase==Succeeded -A
              oc delete pod --field-selector=status.phase==Failed -A
          restartPolicy: OnFailure

One comment

Comments are closed.