<p>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:</p>
<pre><code>2021-04-10, restarts:0, id = 1234 -&gt; failed
2021-04-10, restarts:1, id = 1234 -&gt; failed
2021-04-10, restarts:2, id = 1234 -&gt; failed

2021-04-11, restarts:0, id 1235 -&gt; failed
2021-04-11, restarts:1, id 1235 -&gt; failed

2021-04-12, restarts:0, id 1236 -&gt; success

2021-04-13, restarts:0, id 1237 -&gt; success
</code></pre>
<p>Is there a way I generate such a variable ?</p>

<p><strong>Is there a way I generate such a variable ?</strong></p>
<p>Yes, with usage of UID.  Every object created over the whole lifetime of a Kubernetes cluster has a distinct <code>UID</code>. It is intended to distinguish between historical occurrences of similar entities.</p>
<p>This UID then can be expose as <a href="https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/" rel="nofollow noreferrer">environment variable</a> and injected into your pod:</p>
<pre class="lang-yaml prettyprint-override"><code>
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: &quot;*/1 * * * *&quot;
  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 
</code></pre>
<p>And here you have printed out the unique UID:</p>
<pre><code>➜  ~ k logs hello-1618817040-4jkpx 
Mon Apr 19 07:24:02 UTC 2021
f9060e34-a4e8-40d2-b459-6029b07e4fe7
</code></pre>
<p>You can use it directly or you can hash it and make it into any datatype you want.</p>
