Search code examples
dockerkubernetesenvironment-variableskubernetes-helm

How to parse .env file (dotenv) with Helm template?


I'm migrating from Docker to Helm3. My Docker deployment uses .env files to load environment variables see reference. During the migration I need to support both the old way and new way so I don't want change the .env format if I can avoid it.

Here's my sample .env file:

key1=value1
key2=value2

Then in my Helm3 deployment.yaml I need:

kind: Deployment
spec:
  template:
    spec:
      containers:
          env:
            - name: key1
              value: "value1"
            - name: key2
              value: "value2"

The .env file is the helm project root directory so I'm hoping I can do something like this based on this question but not sure how to proceed:

  {{- $files := .Files }}
  #Not sure how to select just one file?
  {{- range tuple ".env" }}
  
      #Split file by newlines and =
      {{- range $line := splitList "\n" $files.Get . }}
        {{/* Break the line into words */}}
        {{- $kv := splitList "=" $line -}}
        {{- $k := first $kv -}}
        {{ $k }}: {{ last $kv | quote }}
      {{- end }}

  {{- end }}

Solution

  • Related to the answer of @Charlie, if the environment value contains = symbol, it will break. I fixed this issue with join function as follow:

    {{ $file := .Files.Get ".env" | trimSuffix "\n" }}
    {{- range $line := splitList "\n" $file -}}
    {{- $kv := splitList "=" $line -}}
        {{ "" }}
        - name: {{ first $kv }}
          value: {{ join "=" (slice $kv 1) | quote }}
    {{- end }}