Adding news lines when defining collection

3/29/2019

I am trying to define a collection (dict), and I would like to add a new line on each definition (for readability), Eg:

{{ $deployment := dict 
"Release" .Release 
"Chart" .Chart 
"Values" .Values }}

But when I do this, helm respond a parse error :

Error: parse error in "XXX": template: XXX:2: unclosed action
Error: UPGRADE FAILED: parse error in "XXX": template: XXX:2: unclosed action

Is there a way in HELM to do this?

-- Ngob
kubernetes
kubernetes-helm
yaml

3 Answers

11/4/2019

I achieved this by defining the dict first and then setting one key per line.

{{- $myDict := dict "" "" -}}
{{- $_ := set $myDict "myKey1" "myValue1" -}}
{{- $_ := set $myDict "myKey2" "myValue2" -}}
{{- $_ := set $myDict "myKey3" "myValue3" -}}
{{- $_ := set $myDict "myKey4" "myValue4" -}}

Bonus Tip: Since dict get function is available seemingly in only helm3 and later, you can use this hack to get a value from a dict to a string.

{{/* Hack needed until helm 3 which has 'get' for 'dict' */}}
{{- $myValue3Var := pluck "myKey3" $myDict | first -}}
-- yosefrow
Source: StackOverflow

3/29/2019

It seems it's impossible to do so. The Helm templating system is basically the Go templating system. As stated in the Go templating docs:

Except for raw strings, actions may not span newlines, although comments can.

-- yanivoliver
Source: StackOverflow

3/29/2019

TLDR;

It's impossible to declare dict in multiline way, like with Perl fat comma operator.
Please check the reference of "Sprig: Template functions for Go templates."

Instead you could use this sort of hacky way to achieve similar result:

  1. Keep each key value pair in separate line, in Global Values file for readability:
# values.yaml
  -- 
  global:
  someMap:
    coffee: robusta
    origin: Angola
    crema: yes
  1. Define helper template in _helpers.tpl:
{{- define "mychart.labels.standard"}}
{{- $global := default (dict) .Values.global.someMap -}}
Release: {{ .Release.Name | quote }}
Chart: {{ .Chart.Name }}
Values:
{{- $global := default (dict) .Values.global.someMap -}} 
{{- range $key, $value := $global }}
  {{ $key }}: {{ $value }}
{{- end }}
{{- end -}}
  1. Include it in another template:
helm_data:
  {{- $global := default (dict) .Values.global -}}
  {{- range $key, $value := $global }}
    {{ $key }}: {{ $value }}
  {{- end }}
  {{ include "mychart.labels.standard" . | nindent 0 -}}
  1. Render it to verify the result (helm template --name dict-chart .)
---
# Source: mychart/templates/data_type.yaml
helm_data:
    someMap: map[crema:true origin:Angola coffee:robusta]
  
Release: "dict-chart"
Chart: mychart
Values:
    coffee: robusta
    crema: true
    origin: Angol
-- Nepomucen
Source: StackOverflow