Create k8s Cronjob To Schedule Delete Expired Files

Create k8s Cronjob To Schedule Delete Expired Files

ยท

2 min read

  • Application service processes documents and stores them in EFS volume as their cache, the requirement is to clear files which is older than 7 days.

  • Solution: Create a cronjob with expected schedule time, the cronjob will claim a volume of same EFS persistent volume and then check time life of the files. Alt Text

  • Note: -- The service mount path: /app/ and stores files in /app/Documents -- The cronjob should mount path: /opt/demo/ and then it can see Documents

demo.yaml

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: demo-clean
spec:
  schedule: "0 1 * * SAT"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: demo-clean
            image: busybox
            args:
            - /bin/sh
            - -c
            - find /opt/demo/Documents/ -type f -mtime +7 -exec rm {} \;
            volumeMounts:
            - name: efs
              mountPath: "/opt/demo/"

          restartPolicy: OnFailure
          volumes:
          - name: efs
            persistentVolumeClaim:
              claimName: efs-pvc

Apply yaml file and check

~:/# kubectl get cronjob
NAME              SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
demo-clean          0 1 * * SAT   False     0        30h             9d

~:/# kubectl get pod
demo-clean-1607838120-7kl2w                            0/1     Completed   0          18h