1

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 }}
Charlie
  • 2,004
  • 6
  • 20
  • 40
  • You can't refer to `.Files` in the `templates` directory; you need to move the file somewhere else. [Accessing Files Inside Templates](https://helm.sh/docs/chart_template_guide/accessing_files/) in the Helm documentation has more information on `.Files`, including how to retrieve a specific file. – David Maze Feb 17 '21 at 17:46
  • Thanks - improved my answer below – Charlie Feb 18 '21 at 14:55

2 Answers2

1

Here's what worked for me but I'm open to a better answer. The only things I don't understand is why I need the empty line {{""}} - I thought new lines would have been inserted without that.

The issue I had with the answer from @Matt was that the indentation came out wrong.

{{ $file := .Files.Get ".env" | trimSuffix "\n" }}
{{- range $line := splitList "\n" $file -}}
{{- $kv := splitList "=" $line -}}
    {{ "" }}
    - name: {{ first $kv }}
      value: {{ last $kv | quote }}
{{- end }}
Charlie
  • 2,004
  • 6
  • 20
  • 40
0

Here is what I have come up with.

kind: Deployment
spec:
  template:
    spec:
      containers:
        env:
{{ $files := .Files }}
{{- range tuple ".env" -}}
    {{- $file := $files.Get . | trimSuffix "\n" -}}
    {{- range $line := splitList "\n" $file -}}
      {{- $kv := splitList "=" $line -}}
      {{- $k := first $kv -}}
      {{- $v := last $kv -}}
      {{- printf "- name: \"%s\"\n" $k | indent 8 }}
      {{- printf "  value: \"%s\"\n" $v }}
    {{- end }}
{{- end }}

It should work copypasted assuming .env file is placed in helm project root directory

I tested it with following .env file:

key1=value1
key2=value2

And got the following yaml as the output:

---
kind: Deployment
spec:
  template:
    spec:
      containers:
        env:
        - name: "key1"
          value: "value1"
        - name: "key2"
          value: "value2"
Matt
  • 7,419
  • 1
  • 11
  • 22