{{- if and .Values.hubble.tls.auto.enabled (eq .Values.hubble.tls.auto.method "cronJob") }}
apiVersion: batch/v1
kind: Job
metadata:
  name: hubble-generate-certs
  namespace: {{ .Release.Namespace }}
  labels:
    k8s-app: hubble-generate-certs
{{ include "hubble-generate-certs.job.spec" . }}
{{- end }}

{{- if and .Values.hubble.tls.auto.enabled (eq .Values.hubble.tls.auto.method "cronJob") }}
{{/*
Because Kubernetes job specs are immutable, Helm will fail patch this job if
the spec changes between releases. To avoid breaking the upgrade path, we
generate a name for the job here which is based on the checksum of the spec.
This will cause the name of the job to change if its content changes,
and in turn cause Helm to do delete the old job and replace it with a new one.
*/}}
{{- $jobSpec := include "hubble-generate-certs.job.spec" . -}}
{{- $checkSum := $jobSpec | sha256sum | trunc 10 -}}
apiVersion: batch/v1
kind: Job
metadata:
  name: hubble-generate-certs-{{$checkSum}}
  namespace: {{ .Release.Namespace }}
  labels:
    k8s-app: hubble-generate-certs
{{ $jobSpec }}
{{- end }}

Fix patch failure when updating `hubble-generate-certs`
helm: Fix patch failure when updating `hubble-generate-certs`

This PR fixes an issue with Helm upgrade of users who set
`hubble.tls.auto.method=cronJob`.

Because the definition of the `hubble-generate-certs` Kubernetes Job can
change between releases (as it did e.g. between 1.9 and 1.10), Helm will
try to patch in the changes in the Job object via Kubernetes API.
However, because the Job object is immutable, this PATCH request will
fail with the following error:

```
Error: UPGRADE FAILED: cannot patch "hubble-generate-certs" with kind Job
```

Because jobs are immutable, the way to update them is to delete the old
one and create a new one. While Helm does not seem to have a built-in
mechanism for this, we can achieve the same by changing the Job name
when its definition changes. This commit introduces such a logic, by
appending the checksum of the job spec to the job name. This will cause
the name of the job to change when the spec changes, and in turn cause
Helm to do delete the old job and replace it with a new one.

Fixes: #16316

Signed-off-by: Sebastian Wicki <db043b2055cb3a47b2eb0b5aebf4e114a8c24a5a@isovalent.com>
