How can I apply template function to a range result in Helm?

Viewed 1199

My goal is to convert values in Values.yaml into the following:

CUSTOM_VARIABLE: "TEST_ENV_1=devil,TEST_ENV_2=god,TEST_ENV_3=angel"
### Values.yaml
env:
  TEST_ENV_1: devil
  TEST_ENV_2: god
  TEST_ENV_3: angel

The below template almost does this but I'm getting comma at the end: TEST_ENV_1=devil,TEST_ENV_2=god,TEST_ENV_3=angel,.

### _envVars.tpl
{{ define "envVars" }}

...

- name: CUSTOM_VARIABLE
  value: "
  {{- range $key, $value := .Values.env -}}
  {{- printf "%s=%s," $key $value -}}
  {{- end -}}
  " 

...

{{- end }}

Is there a way to apply template function (e.g. trunc to remove last symbol) to a range result in my case?

2 Answers

If you write the range call into a helper template, Helm has an include extension function that calls a template and captures its output as a string.

{{/* Render the map-type template parameter to a key=value,key=value,
     list, ending with a trailing comma. */}}
{{- define "custom.variable.format" -}}
{{- range $key, $value := . -}}
{{ $key }}={{ $value }},
{{- end -}}
{{- end -}}

- name: CUSTOM_VARIABLE
  value: {{ include "custom.variable.format" .Values.env | trimSuffix "," | quote }}

(It is probably cleaner to not generate the comma at all, as @HarshManvar's answer proposes.)

Related