kubernetes-helm

Helm referring to kubernetes secrets in enviroment variables


I have some environment variables that I'm using in a helm installation and want to hide the password using a k8s secret.

values.yaml

env:
  USER_EMAIL: "test@test.com"
  USER_PASSWORD: "p8ssword"

I want to add the password via a kubernetes secret mysecrets, created using

# file: mysecrets.yaml
apiVersion: v1
kind: Secret
metadata:
  name: mysecrets
type: Opaque
data:
  test_user_password: cGFzc3dvcmQ=


and then add this to values.yaml

  - name: TEST_USER_PASSWORD
    valueFrom:
      secretKeyRef:
        name: mysecrets
        key: test_user_password

I then use the following in the deployment

        env:
          {{- range $key, $value := $.Values.env }}
          - name: {{ $key }}
            value: {{ $value | quote }}
          {{- end }}

Is it possible to mix formats for environment variables in values.yaml i.e.,

env:
  USER_EMAIL: "test@test.com"
  - name: USER_PASSWORD
    valueFrom:
      secretKeyRef:
        name: mysecrets
        key: test_user_password

Or is there a way of referring to the secret in line in the original format?


Solution

  • Plan 1 :

    One of the simplest implementation methods

    You can directly use the yaml file injection method, put the env part here as it is, so you can write the kv form value and the ref form value in the values in the required format.

    As follows:

    values.yaml

    env:
      - name: "USER_EMAIL"
        value: "test@test.com"
      - name: "USER_PASSWORD"
        valueFrom:
          secretKeyRef:
            name: mysecrets
            key: test_user_password
    

    deployment.yaml

    containers:
      - name: {{ .Chart.Name }}
        env:
          {{ toYaml .Values.env | nindent xxx }}
        {{- end }}
    

    (ps: xxx --> actual indent)

    Plan 2:

    Distinguish the scene by judging the type.

    As follows:

    values.yaml

    env:
      USER_EMAIL: 
        type: "kv"
        value: "test@test.com"
      USER_PASSWORD: 
        type: "secretRef"
        name: mysecrets
        key: p8ssword
      USER_CONFIG:
        type: "configmapRef"
        name: myconfigmap
        key: mycm
    

    deployment.yaml

    containers:
      - name: {{ .Chart.Name }}
        env: 
          {{- range $k, $v := .Values.env }}
          - name: {{ $k | quote }}
          {{- if eq $v.type "kv" }}
            value: {{ $v.value | quote }}
          {{- else if eq $v.type "secretRef" }}
            valueFrom:
              secretKeyRef:
                name: {{ $v.name | quote }}
                key: {{ $v.key | quote }}
          {{- else if eq $v.type "configmapRef" }}
            valueFrom:
              configMapKeyRef:
                name: {{ $v.name | quote }}
                key: {{ $v.key | quote }}
          {{- end }}
          {{- end }}