Search code examples
kubernetescronjobsschedule

Want to parameterize cronjob schedule on Kubernetes


I have an yaml. I want to parameterize the schedule of that kubernetes cronjob. On environment file I declared JobFrequencyInMinutes: "10"

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: scheduled-mongo-cronjob
spec:
  schedule: "*/$(JobFrequencyInMinutes) * * * *"
concurrencyPolicy: "Forbid"
jobTemplate:
spec:
   template:
     spec:
          containers:
          - name: scheduled-mongo-cronjob
            image: xxxx
          env:
          - name: JobFrequencyInMinutes
            valueFrom:
              configMapKeyRef:
                key: JobFrequencyInMinutes
                name: env-conf

When I am applying the above yaml I am getting an error. The CronJob "scheduled-mongo-cronjob" is invalid: spec.schedule: Invalid value: "*/$(JobFrequencyInMinutes) * * * *": Failed to parse int from $(JobFrequencyInMinutes): strconv.Atoi: parsing "$(JobFrequencyInMinutes)": invalid syntax

Please guide me if there is any alternative way to achieve this.


Solution

  • The issue here is that the environment variable will be just available when the CronJob is created and inside the job itself, but it is failing to create because the variable $JobFrequencyInMinutes does not exists in the node level.

    I would say that to achieve what you are trying to do, you would need to have an environment variable at cluster level. Whenever you want to update your schedule, you would need to set a new value to it and then re-create your CronJob.

    It seems though that the declarative way it's not working (via your YAML), so you would need to create using the imperative way:

    kubectl run scheduled-mongo-cronjob --schedule="*/$JobFrequencyInMinutes * * * *" --restart=OnFailure --image=xxxx