Search code examples
kuberneteskubernetes-helm

Helm: How to avoid recreating secrets on upgrade?


I have something in a secret template like this:

apiVersion: v1
kind: Secret
metadata:
  # not relevant
type: Opaque
data:
  password: {{ randAlphaNum 32 | b64enc | quote }}

Now, when doing helm upgrade, the secret is recreated, but the pods using this aren't (they also shouldn't, this is OK).

This causes the pods to fail when they are restarted or upgraded as the new password now doesn't match the old one.

Is it possible to skip re-creation of the secret when it exists, like, a {{- if not(exists theSecret) }} and how to do it?


Solution

  • You can use the look up function in HELM to check the if secret exist or not

    https://helm.sh/docs/chart_template_guide/functions_and_pipelines/#using-the-lookup-function

    Function in helm chart goes like : https://github.com/sankalp-r/helm-charts-examples/blob/1081ab5a5af3a1c7924c826c5a2bed4c19889daf/sample_chart/templates/_helpers.tpl#L67

    {{/*
    Example for function
    */}}
    {{- define "gen.secret" -}}
    {{- $secret := lookup "v1" "Secret" .Release.Namespace "test-secret" -}}
    {{- if $secret -}}
    {{/*
       Reusing value of secret if exist
    */}}
    password: {{ $secret.data.password }}
    {{- else -}}
    {{/*
        add new data
    */}}
    password: {{ randAlphaNum 32 | b64enc | quote }}
    {{- end -}}
    {{- end -}}
    

    secret creation will be something like

    example file : https://github.com/sankalp-r/helm-charts-examples/blob/main/sample_chart/templates/secret.yaml

    apiVersion: v1
    kind: Secret
    metadata:
      name: "test-secret"
    type: Opaque
    data:
    {{- ( include "gen.secret" . ) | indent 2 -}}
    

    chart example : https://github.com/sankalp-r/helm-charts-examples

    {{- $secret := (lookup "v1" "Secret" .Release.Namespace "test-secret" -}}
    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 }}