I'm trying to pass a dictionary from one helm template to another but it's resolved to null inside the called template.
Calling template - deployment.yaml
Called template - storageNodeAffinity
I see myDict printed as map inside deployment.yaml but inside storageNodeAffinity it's printed as null.
Eventually I need to pass nodeAffn from the values file.
deployment.yaml
{{- $myDict := dict "cpu" "amd" }}
{{- include "storageNodeAffinity" $myDict | indent 6 }}
{{printf "%q" $myDict}}
storage-affinity.tpl
{{- define "storageNodeAffinity" }}
{{/* {{- $myDict := dict "cpu" "amd" }}*/}}
{{printf "%q" .myDict}}
{{- range $key, $val := .myDict }}
- key: {{ $key }}
operator: In
values:
- {{ $val }}
{{- end }}
{{- end }}
values.yaml
nodeAffn:
disktype: "ssd"
cpu: intel
When you call a template
{{- include "storageNodeAffinity" $myDict -}}
then within the template whatever you pass as the parameter becomes the special variable .. That is, . is the dictionary itself; you don't need to use a relative path to find its values.
{{- define "storageNodeAffinity" }}
{{/* ., not .myDict */}}
{{printf "%q" .}}
{{- range $key, $val := . }}...{{ end -}}
{{- end -}}
I figured it out. The trick is to pass context of the parent variable for the variable you want to use in the called template. So here I'm passing "csAffn" as context and then using "nodeAffn" inside this context, in the called template (_additionalNodeAffinity)
_additionalNodeAffinity.tpl
{{- define "additionalNodeAffinity" }}
{{- range $key, $val := .nodeAffn }}
- key: {{ $key }}
operator: In
values:
- {{ $val }}
{{- end }}
{{- end }}
deployment.yaml
{{- include "additionalNodeAffinity" ( .Values.csAffn )
values.yaml
csAffn:
nodeAffn:
disktype: "ssd"
cpu: "intel"
Related
I am wondering if there is a more efficient way to exclude any yaml keys which do not have a value set.
My current approach is to wrap each key in an if statement...
container:
spec:
{{- if values.spec.x }}
x: {{ values.spec.x }}
{{- end}}
{{- if values.spec.y }}
y: {{ values.spec.y }}
{{- end}}
{{- if values.spec.z }}
z: {{ values.spec.z }}
{{- end}}
e.g.
for each child of container.spec:
if the value != null:
include as child of spec
else:
exclude from spec
I thought about wrapping the above in a _helper.tpl function to try to keep the main template tidy, but it would still include writing multiple if statements.
Is there a better way of doing the above?
Thanks!
You can directly translate that pseudocode into Helm chart logic. The trick is that a Go template range loop is basically equivalent to a "for" loop in most languages. So:
container:
spec:
{{- range $key, $value := .Values.spec }}
{{- if ne $value nil }}
{{ $key }}: {{ $value }}
{{- end }}
{{- end }}
If you can just omit the unused keys from the values, then this becomes simpler and safer. Helm includes a lightly-documented toYaml function that will render an arbitrary structure as YAML, but you can't really do any filtering or other preprocessing before writing it out.
container:
spec:
{{ .Values.spec | toYaml | indent 4 }}
I have a directory structure like this:
helm
|-->mappings
|--> foo
foo1.yaml foo2.yaml
|-->templates
mapping.yaml
values.yaml
where values.yaml
has a value that I need to be a variable due to environment like {{ .Values.data.hostname }}
and in mapping.yaml
{{- $files := .Files }}
{{- range .Values.mappings.foo }}
{{- $genericfilepath := printf "mappings/foo/%s.yaml" . }}
{{ $files.Get $genericfilepath }}
{{- end }}
Currently the mapping.yaml file loops through the designated directory and load the yaml file however I am unable to access the Values variable.
I have also attempted subchart where values.yaml file would be under helm/mappings/foo/values.yaml but it also doesn't resolve or I am not 100% understanding if subchart would be the correct solution to resolve the file path
In the Go text/template language, . is a special "context" variable, and references like .Files or .Values are actually retrieving fields from .. For example, you could write a sample template:
{{- $dot := . -}}
# These both print the same value
dot-values-foo: {{ .Values.foo }}
dollars-dot-values-foo: {{ $dot.Values.foo }}
One of the ways . is special is that the range statement sets . to each item as it iterates through a collection. In your example:
{{/* . is the top item; .Values is valid */}}
{{- range .Values.mappings.foo }}
{{/* . is one of the items in `mappings.foo` */}}
{{- end }}
{{/* . is the top item again */}}
If I need to use . for some special purpose like this, I tend to save the original top item in a variable, and then I can refer to fields in that.
{{- $top := . }}
{{- range .Values.mappings.foo }}
{{- $genericfilepath := printf "mappings/foo/%s.yaml" . }}
{{ $top.Files.Get $genericfilepath }}
{{ index $top.Values.enabled . }}
{{- end }}
In my values config file, I have an array of dictionaries as follows:
connects_to
- name: myname
release: optional release
- name: another name
Note that name will always be provided but release may or may not be. In my template, I have:
{{- if .Values.connects_to }}
app.openshift.io/connects-to: '
{{- range .Values.connects_to -}}
{{- if .release -}}
{{- .release -}}-{{- .name -}},
{{- else -}}
{{- $.Release.Name -}}-{{- .name -}},
{{- end -}}
{{- end -}}
'
{{- end }}
which gives the error:
can't evaluate field release in type interface {}
I have also tried using "hasKey" as follows:
{{- if .Values.connects_to }}
app.openshift.io/connects-to: '
{{- range .Values.connects_to -}}
{{- if hasKey . "release" -}}
{{- .release -}}-{{- .name -}},
{{- else -}}
{{- $.Release.Name -}}-{{- .name -}},
{{- end -}}
{{- end -}}
'
{{- end }}
which gives the error:
wrong type for value; expected map[string]interface {}; got string
How would I accomplish this check without having to specify a value for "release" every time? My helm version:
version.BuildInfo{Version:"v3.2.3+4.el8", GitCommit:"2160a65177049990d1b76efc67cb1a9fd21909b1", GitTreeState:"clean", GoVersion:"go1.13.4"}
This actually works with the "hasKey" approach, there was an error in the values definition.
For people looking for a possible cause for the error (wrong type for value; expected map[string]interface {}; got string).
Given the template
{{- if hasKey .Values.somedict "valueX" -}}
{{- .Values.somedict.valueX -}}
{{- end -}}
And using 2 values.yaml (eg: helm template . --values Values1.yaml --values Values2.yaml).
Values1.yaml:
somedict:
valueA: 1
Values2.yaml:
# Causes error
somedict:
# Works
somedict: {}
# Leaving out "somedict" also work
Regarding #DieterDP 's response https://stackoverflow.com/a/72360797/17143221
I am getting the same issue when using this template.
This can be solved by using parentheses around the optional dict as a mean of null-safety.
template:
# Fails when somedict doesn't exist
{{- if hasKey .Values.somedict "valueX" -}}
{{- .Values.somedict.valueX -}}
{{- end -}}
# Works when somedict doesn't exist
{{- if hasKey (.Values.somedict) "valueX" -}}
{{- .Values.somedict.valueX -}}
{{- end -}}
values.yaml:
# without "somedict"
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?
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 -}}
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:
Keep each key value pair in separate line, in Global Values file for readability:
# values.yaml
--
global:
someMap:
coffee: robusta
origin: Angola
crema: yes
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 -}}
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 -}}
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
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.
For people coming across this question, this functionality works in recent versions of HELM. For me, OPs example works as-is (Helm v3.8.2).
(I came across this question myself due to a mismatched ) in my template.)
I am doing this now:
value: {{ required "A valid .Values.foo entry required!" .Values.foo }}
But to give this same message for all required values in the templates is cumbersome and clutters the templates in my opinion.
Is there a better way where we could define it outside the template \ or a cleaner way to do it within the template itself?
You could do something by taking advantage of range and the fact that null will fail the required check. So in your values.yaml you could have this section for required env vars:
reqEnv:
- name: "VAR1"
value: null
- name: "VAR2"
value: null
And in the env section of the Deployment you then have:
{{- range .Values.reqEnv }}
{{ .name }}: {{ required "A value must be entered for all reqEnv entries" .value }}
{{- end }}
Then the user gets an error unless they set all required values of the reqEnv section in their values file or as paramters. Unfortunately what you lose by doing this is the detail of which var is missing. This could be why the official helm charts seem to prefer using required in the way that you already are.
Define the required values on top of your manifest as variables utilizing the required function.
E.g. deployment.yaml:
{{- $name := .Values.name | required ".Values.name is required." -}}
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ $name }}
....
You can use helm lint with --strict flag to check undefined values
$ helm lint --strict .
==> Linting .
[INFO] Chart.yaml: icon is recommended
[ERROR] templates/: render error in "mychart/templates/service.yaml": template: mychart/templates/service.yaml:10:19: executing "mychart/templates/service.yaml" at <.Values.foo>: map has no entry for key "foo"
Error: 1 chart(s) linted, 1 chart(s) failed
To expose name of missing item to required text you can do something like this:
{{- range $field, $my_key := $data }}
{{- if hasKey $dic1 $my_key }}
{{ $field }}: {{ index $dic1 $my_key | b64enc}}
{{- else if hasKey $dic2 $my_key }}
{{ $field }}: {{ index $dic2 $my_key | b64enc}}
{{- else }}
{{ $field }}: {{ required (printf "key %s is missing" $my_key) nil }}
{{- end }}
{{- end }}
I've come up with an alternative hack trying to solve this problem. It's questionable whether this is actually any better that the built in solution, but I thought it might be worth noting down here as an option.
Add a function to your _helpers.tpl (or wherever):
{{/*
Require and include a value
*/}}
{{- define "require" -}}
{{- $scope := index . 0 -}}
{{- $name := index . 1 -}}
{{required (print "Missing required value: " $name) (index $scope "Values" $name)}}
{{- end}}
Then in your template call it with:
value: {{ include "require" (list . "foo") }}
If a value is missing, it errors with message:
Missing required value: foo
Otherwise, it inserts the value.
Edit: To make this work for nested values, you need a slightly more complex helper:
{{/*
Index a nested component
*/}}
{{- define "indexNested" -}}
{{- $message := index . 0 -}}
{{- $object := index . 1 -}}
{{- $path := (mustRegexSplit "\\." (index . 2) -1) -}}
{{- range $path -}}
{{- if not $object -}}
{{ fail $message }}
{{- end -}}
{{- $object = index $object . -}}
{{- end -}}
{{ required $message $object }}
{{- end}}
{{/*
Require and include a value
*/}}
{{- define "require" -}}
{{- $scope := index . 0 -}}
{{- $name := index . 1 -}}
{{ include "indexNested" (list (print "Missing required value: " $name) $scope.Values $name) }}
{{- end}}
Now you can access the foo.bar value with:
{{ include "require" (list . "foo.bar") }}