<p>I want to generate a password in a Helm template, this is easy to do using the <code>randAlphaNum</code> function. However the password will be changed when the release is upgraded. Is there a way to check if a password was previously generated and then use the existing value? Something like this:</p>

<pre><code>apiVersion: v1
kind: Secret
metadata:
  name: db-details
data:
  {{ if .Secrets.db-details.db-password }}
  db-password:  {{ .Secrets.db-details.db-password | b64enc }}
  {{ else }}
  db-password: {{ randAlphaNum 20 | b64enc }}
  {{ end }}
</code></pre>

Mikhail Janowski
<p>You can build on <a href="https://stackoverflow.com/users/435563/shaunc">shaunc</a>'s idea to use the <a href="https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function" rel="noreferrer">lookup</a> function to fix the original poster's code like this:</p>
<pre><code>apiVersion: v1
kind: Secret
metadata:
  name: db-details
data:
  {{- if .Release.IsInstall }}
  db-password: {{ randAlphaNum 20 | b64enc }}
  {{ else }}
  # `index` function is necessary because the property name contains a dash.
  # Otherwise (...).data.db_password would have worked too.
  db-password:  {{ index (lookup &quot;v1&quot; &quot;Secret&quot; .Release.Namespace &quot;db-details&quot;).data &quot;db-password&quot; }}
  {{ end }}
</code></pre>
<p>Only creating the <code>Secret</code> when it doesn't yet exist won't work because Helm will delete objects that are no longer defined during the upgrade.</p>
<p>Using an annotation to keep the object around has the disadvantage that it will not be deleted when you delete the release with <code>helm delete ...</code>.</p>
