<p>I have something in a secret template like this:</p>
<pre><code>apiVersion: v1
kind: Secret
metadata:
  # not relevant
type: Opaque
data:
  password: {{ randAlphaNum 32 | b64enc | quote }}
</code></pre>
<p>Now, when doing <code>helm upgrade</code>, the secret is recreated, but the pods using this aren't (they also shouldn't, this is OK).</p>
<p>This causes the pods to fail when they are restarted or upgraded as the new password now doesn't match the old one.</p>
<p>Is it possible to skip re-creation of the secret when it exists, like, a <code>{{- if not(exists theSecret) }}</code> and how to do it?</p>

rabejens
<p>You can use the <strong>look up</strong> <strong>function</strong> in HELM to check the if secret exist or not</p>
<p><a href="https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function" rel="noreferrer">https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function</a></p>
<p>Function in helm chart goes like : <a href="https://github.com/sankalp-r/helm-charts-examples/blob/1081ab5a5af3a1c7924c826c5a2bed4c19889daf/sample_chart/templates/_helpers.tpl#L67" rel="noreferrer">https://github.com/sankalp-r/helm-charts-examples/blob/1081ab5a5af3a1c7924c826c5a2bed4c19889daf/sample_chart/templates/_helpers.tpl#L67</a></p>
<pre><code>{{/*
Example for function
*/}}
{{- define &quot;gen.secret&quot; -}}
{{- $secret := lookup &quot;v1&quot; &quot;Secret&quot; .Release.Namespace &quot;test-secret&quot; -}}
{{- if $secret -}}
{{/*
   Reusing value of secret if exist
*/}}
password: {{ $secret.data.password }}
{{- else -}}
{{/*
    add new data
*/}}
password: {{ randAlphaNum 32 | b64enc | quote }}
{{- end -}}
{{- end -}}
</code></pre>
<p>secret creation will be something like</p>
<p>example file : <a href="https://github.com/sankalp-r/helm-charts-examples/blob/main/sample_chart/templates/secret.yaml" rel="noreferrer">https://github.com/sankalp-r/helm-charts-examples/blob/main/sample_chart/templates/secret.yaml</a></p>
<pre><code>apiVersion: v1
kind: Secret
metadata:
  name: &quot;test-secret&quot;
type: Opaque
data:
{{- ( include &quot;gen.secret&quot; . ) | indent 2 -}}
</code></pre>
<p>chart example : <a href="https://github.com/sankalp-r/helm-charts-examples" rel="noreferrer">https://github.com/sankalp-r/helm-charts-examples</a></p>
<pre><code>{{- $secret := (lookup &quot;v1&quot; &quot;Secret&quot; .Release.Namespace &quot;test-secret&quot; -}}
apiVersion: v1
kind: Secret
metadata:
  name: test-secret
type: Opaque

# 2. If the secret exists, write it back
{{ if $secret -}}
data:
  password: {{ $secret.data.password }}

# 3. If it doesn't exist ... create new
{{ else -}}
stringData:
  password: {{ randAlphaNum 32 | b64enc | quote }}
{{ end }}
</code></pre>
