Skip to main content

cronjobs-k8s

Setting helm chart to deploy k8s cronjobs

Cronjob.yml

apiVersion: batch/v1beta1
kind: CronJob
metadata:
namespace: {{ .Values.env }}
name: {{ .Chart.Name }}
labels:
draft: {{ default "draft-app" .Values.draft }}
chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}"
spec:
schedule: {{ .Values.schedule }}
successfulJobsHistoryLimit: 0
jobTemplate:
spec:
template:
metadata:
labels:
draft: {{ default "draft-app" .Values.draft }}
app: {{ .Chart.Name }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
args:
- sh
- -c
- |
sleep 2
"/opt/myapp/myscript.sh"
sleep 30
env:
- name: APP_SECRET
valueFrom:
secretKeyRef:
name: {{ .Values.appsecret }}
key: app_secret
- name: APP_CLIENT_ID
valueFrom:
secretKeyRef:
name: {{ .Values.appsecret }}
key: app_client_id
ports:
- containerPort: {{ .Values.service.internalPort }}
restartPolicy: {{ .Values.restartPolicy }}
imagePullSecrets:
- name: artifactory

Values.yml

env: dev
appsecret: myapp-secret
schedule: '"30 10 * * *"'
restartPolicy: OnFailure
image:
repository: XYZ
tag: 1.0.2
pullPolicy: IfNotPresent
service:
internalPort: 8028

We can use the ‘range’ instruction for iterative cronjob resource, using the values.yaml you could be able to pass multiple values for all different jobs. In the range instruction, you need to call all Values $.Values.val instead of .Values.val . You need to have and — and end to close the loop.

cronjob.yaml

{{- range $job, $val := .Values.cronjob.crons }}
apiVersion: batch/v1beta1
kind: CronJob
metadata:
namespace: {{ .Values.env }}
name: {{ .name }}
labels:
draft: {{ default "draft-app" $.Values.draft }}
chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}"
spec:
schedule: {{ .schedule | quote }}
successfulJobsHistoryLimit: 0
jobTemplate:
spec:
template:
metadata:
labels:
draft: {{ default "draft-app" $.Values.draft }}
app: {{ .name }}
spec:
containers:
- name: {{ .name }}
image: "{{ $.Values.image.repository }}:{{ $.Values.image.tag }}"
imagePullPolicy: {{ $.Values.image.pullPolicy }}
args:
- sh
- -c
- |
sleep 2
"./bin/console --env={{ $.Values.env }} {{ .command}}"
sleep 30
ports:
- containerPort: {{ $.Values.service.internalPort }}
restartPolicy: {{ $.Values.restartPolicy }}
imagePullSecrets:
- name: artifactory
---
{{- end}}

Values.yaml

env: dev
restartPolicy: OnFailure
image:
repository: XYZ
tag: 1.0.2
pullPolicy: IfNotPresent
service:
internalPort: 8028
crons:
"0":
name: cog-first-cron
command: /opt/myapp/myscript1.sh
schedule: "10 4 * * *"
"1":
name: cog-second-cron
command: /opt/myapp/myscript2.sh
schedule: "" 30 5 * * *"
"2":
name: cog-third-cron
command: /opt/myapp/myscript3.sh
schedule: "0/5 * * * *"