k8s CronJob jobId which survive restarts

Viewed 85

I have a daily k8s cron job, I need to have unique id for every created job, which is same on job restart in case of job failure. Example:

2021-04-10, restarts:0, id = 1234 -> failed
2021-04-10, restarts:1, id = 1234 -> failed
2021-04-10, restarts:2, id = 1234 -> failed

2021-04-11, restarts:0, id 1235 -> failed
2021-04-11, restarts:1, id 1235 -> failed

2021-04-12, restarts:0, id 1236 -> success

2021-04-13, restarts:0, id 1237 -> success

Is there a way I generate such a variable ?

1 Answers

Is there a way I generate such a variable ?

Yes, with usage of UID. Every object created over the whole lifetime of a Kubernetes cluster has a distinct UID. It is intended to distinguish between historical occurrences of similar entities.

This UID then can be expose as environment variable and injected into your pod:


apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            imagePullPolicy: IfNotPresent
            env:
              - name: MY_UID
                valueFrom:
                  fieldRef:
                    fieldPath: metadata.uid            
            command:
            - /bin/sh
            - -c
            - date; echo $MY_UID
          restartPolicy: OnFailure 

And here you have printed out the unique UID:

āžœ  ~ k logs hello-1618817040-4jkpx 
Mon Apr 19 07:24:02 UTC 2021
f9060e34-a4e8-40d2-b459-6029b07e4fe7

You can use it directly or you can hash it and make it into any datatype you want.

Related