helm chart / go-template | Translate environment variables from string

8/24/2021

I have a general helm chart in my Kubernetes cluster taking a multiline text field with environment variables (identified by KEY=VALUE), translating them into the deployment.yaml like this:

Inside the Rancher dialog: enter image description here

In the deployment.yaml:

{{- if .Values.envAsMultiline }}
{{- range (split "\n" .Values.envAsMultiline) }}
            - name: "{{ (split "=" .)._0 }}"
              value: "{{ (split "=" .)._1 }}"
{{- end }}
{{- end }}

This works fine so far. But the problem now is: If I have a "=" in my environment variable (Like in the JAVA_OPTS above), it splits the environment variable value at the second "=" of the line:

JAVA_OPTS=-Xms1024m -Xmx2048m -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=512m

is translated to

-Xms1024m -Xmx2048m -XX:MetaspaceSize

The "=256M -XX:MaxMetaspaceSize=512m" is missing here.

How do I correct my deployment.yaml template accordingly?

-- Max
go-templates
kubernetes
kubernetes-helm
rancher
sprig-template-functions

1 Answer

8/25/2021

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: ENVIRONMENT1
	value: "testABC"
  - name: JAVA_OPTS
	value: "-Xms1024m -Xmx2048m -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=512M"
  - name: TZ
	value: "Europe/Berlin"

deployment.yaml

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

(ps: xxx --> actual indent)

Plan 2:

Env is defined in the form of kv, which is rendered in an iterative manner

values.yaml

env:
  ENVIRONMENT1: "testABC"
  JAVA_OPTS: "-Xms1024m -Xmx2048m -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=512M"
  TZ: "Europe/Berlin"

deployment.yaml

containers:
- name: {{ .Chart.Name }}
  env: 
    {{- range $k, $v := .Values.env }}
    - name: {{ $k | quote }}
      value: {{ $v | quote }}
    {{- end }}

Plan 3:

If you still need to follow your previous writing, then you can do this

values.yaml

env: |
  ENVIRONMENT1=testABC
  JAVA_OPTS=-Xms1024m -Xmx2048m -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=512M
  TZ=Europe/Berlin

deployment.yaml

containers:
- name: {{ .Chart.Name }}
  {{- if .Values.env }}
  env:
  {{- range (split "\n" .Values.env) }}
  - name: {{ (split "=" .)._0 }}
    value: {{ . | trimPrefix (split "=" .)._0 | trimPrefix "=" | quote }}
  {{- end }}
  {{- end }}

output:

env:
- name: ENVIRONMENT1
  value: "testABC"
- name: JAVA_OPTS
  value: "-Xms1024m -Xmx2048m -XX:MetaspaceSize=256M -XX:MaxMetaspaceSize=512M"
- name: TZ
  value: "Europe/Berlin"
-- z.x
Source: StackOverflow