Kubernetes show Cron Job Successfully but when not getting desired result

Viewed 915

when I run the cronjob into Kubernetes, that time cron gives me to success the cron but not getting the desired result

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: {{ $.Values.appName }}
  namespace: {{ $.Values.appName }}
spec:
  schedule: "* * * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: test
              image: image
              command: ["/bin/bash"] 
              args: [ "test.sh" ]
          restartPolicy: OnFailure

also, I am sharing test.sh

#!/bin/sh
rm -rf /tmp/*.*
echo "remove done"

cronjob running successfully but when I checked the container the file is not getting deleted into /tmp directory

3 Answers

Cronjob run in one specific container, if you want to remove the file or directory from another container it won't work.

If your main container running under deployment while when your job or cronjob gets triggered it create a new container (POD) which has a separate file system and mount option.

if you want to achieve this scenario you have to use the PVC with ReadWriteMany where multiple containers (POD) can connect with your single PVC and share the file system.

In this way then your cronjob container (POD) get started with the existing PVC file system and you can remove the directory using job or cronjobs.

mount the same PVC to the cronjob container and the main container and it will work.

You need to have the persistence volume attached with you pod and cronjob that you are using so it can remove all the files when the script get executed. You need to mount and provide path accordingly in your script. For adding kubernetes cronjobs kindly go through this link

Change test.sh to:

#!/bin/sh

set -e

rm -rf /tmp/*.*
echo "remove done"

Without -e your bash script will return with the same status as its last command. In this case, it's an echo so it will always have status 0 (success). Using set -e will make your script abort and fail if the rm command fails.


Also, without any volume mounts, this cron job does not do anything meaningful. If you want to delete some files from another container, you would need to use Cron within that container (or have a volume with ReadWriteMany).

Related