Caculating the global index for two ranges in Kubernetes Sprig/helm templates? - kubernetes

In a Helm Chart I have to following values
dataCenters:
- name: a
replicas: 3
- name: b
replicas: 2
When generating the template I would like my output to be like the following
server.1 = a-1
server.2 = a-2
server.3 = a-3
server.4 = b-1
server.5 = b-2
I tried this code
{{- $index := 0 -}}
{{ range $dc := .Values.cluster.dataCenters -}}
{{ range $seq := (int $dc.replicas | until) -}}
{{- $index := (add $index 1) -}}
server.{{ $index }}={{ $dc.name }}-{{ $seq }}
{{ end -}}
{{ end -}}
however in helm templates I don't thing you can reassign the value of the index as my 4th line is attempting and because of that I get out
server.1 = a-1
...
server.1 = b-2
How does one calculates the global index 0 to 4 (1 to 5 in my situation) using the Sprig/Helm templating language?

I have a way to do it that involves some trickery, heavily inspired by functional programming experience.
A Go/Helm template takes a single parameter, but the sprig library gives you the ability to create lists, and the text/template index function lets you pick things out of a list. That lets you write a "function" template that takes multiple parameters, packed into a list.
Say we want to write out a single line of this output. We need to keep track of which server number we're at (globally), which replica number we're at (within the current data center), the current data center record, and the records we haven't emitted yet. If we're past the end of the current list, then print the records for the rest of the data centers; otherwise print a single line for the current replica and repeat for the next server/replica index.
{{ define "emit-dc" -}}
{{ $server := index . 0 -}}
{{ $n := index . 1 -}}
{{ $dc := index . 2 -}}
{{ $dcs := index . 3 -}}
{{ if gt $n (int64 $dc.replicas) -}}
{{ template "emit-dcs" (list $server $dcs) -}}
{{ else -}}
server.{{ $server }}: {{ $dc.name }}-{{ $n }}
{{ template "emit-dc" (list (add1 $server) (add1 $n) $dc $dcs) -}}
{{ end -}}
{{ end -}}
At the top level, we know the index of the next server number, plus the list of data centers. If that list is empty, we're done. Otherwise we can start emitting rows from the first data center in the list.
{{ define "emit-dcs" -}}
{{ $server := index . 0 -}}
{{ $dcs := index . 1 -}}
{{ if ne 0 (len $dcs) -}}
{{ template "emit-dc" (list $server 1 (first $dcs) (rest $dcs)) -}}
{{ end -}}
{{ end -}}
Then in your actual resource definition (say, your ConfigMap definition) you can invoke this template with the first server number:
{{ template "emit-dcs" (list 1 .Values.dataCenters) -}}
Copy this all into a dummy Helm chart and you can verify the output:
% helm template .
---
# Source: x/templates/test.yaml
server.1: a-1
server.2: a-2
server.3: a-3
server.4: b-1
server.5: b-2
I suspect this trick won't work well if the number of servers goes much above the hundreds (the Go templating engine almost certainly isn't tail recursive), and this is somewhat trying to impose standard programming language methods on a templating language that isn't quite designed for it. But...it works.

Related

Go template: is there any item in list of objects with a specific attribute value?

I'm using helm (sprig, go templates). I'm trying to build guards to selectively include stuff in my helm chart, but only if one of the components needs them.
So, I have a list:
- name: foo
flag1: true
flag2: false
flag3: false
- name: bar
flag1: false
flag2: true
flag3: false
I want to do something akin to a (pseudocode) list.any(flag), where over a variable length list, if I passed in flag1 or flag2 I'd get back true, but flag3 would get me false. If possible, I'd like to be able to ask about a different flag without repeating myself each time.
Is there a concise way to accomplish this? Can it be done?
The set of things that are and aren't possible in Go templates can be a little mysterious. A named template always returns a string, but an empty string is logically "false", so it should be possible to write a template call like
{{- if (include "list.any" (list .Values.options "flag2")) }}
...
{{- end }}
A template only takes a single parameter, so in the call we've packed the multiple inputs we need into a list. We've also used the Helm-specific include function to invoke a template and get its output as a string.
How can the template work? Template range loops don't have break or return actions or any other way to stop early. If we only want to output the "success" value once, this means we need to manually iterate through the list. For reasonably short lists, a recursive template call works here.
(For this specific thing, outputting yes or yesyesyes would both be non-empty and therefore logically "true", so you could use a range loop here successfully. This would not work for an equivalent list.all, though.)
In the template definition
{{- define "list.any" -}}
...
{{- end -}}
we need to start by unpacking the parameter list
{{- $list := index . 0 -}}
{{- $search := index . 1 -}}
We only do something if the list is non-empty.
{{- if $list -}}
...
{{- end -}}
If it is non-empty, we can split out its first element. We expect that to be a map, so we can look up the requested key in that with the standard index function. This will return nil if the key is absent and false if it's false, both of which are logically false; if it's true then the if test will pass.
{{- if index (first $list) $search -}}
...
{{- else -}}
...
{{- end -}}
If we do find the item, we can write out a success value and not do anything else
yes
If we don't, then we can recursively call ourselves with the remainder of the list.
{{- include "list.any" (list (rest $list) $search) -}}
Combining that all together gives this template (indented for clarity, the - markers will consume all of the whitespace):
{{- define "list.any" -}}
{{- $list := index . 0 -}}
{{- $search := index . 1 -}}
{{- if index (first $list) $search -}}
yes
{{- else -}}
{{- include "list.any" (list (rest $list) $search) -}}
{{- end -}}
{{- end -}}

How can I get data from values.yaml by a specific name? Helm templating question

If I have a values.yaml that looks something like this:
imageName:
portInfo:
numberOfPorts: 11
startingPort: 7980
env:
- name: "MIN_PORT"
value: 7980
- name: "MAX_PORT"
value: 7990
Right now I have a function in _helpers.tpl that takes the .Values.portInfo.numberOfPorts and .Values.portInfo.startingPort and will loop through for each port value something like this into deployments.yaml:
- containerPort: 7980
protocol: TCP
- containerPort: 7981
...
This is what that function looks like:
{{- define "ports.list" -}}
{{- $dbPorts := (.Values.issdbImage.portInfo.numberOfPorts | int) }}
{{- $startingPort := (.Values.issdbImage.portInfo.startingPort | int) }}
{{- range $i := until $dbPorts }}
- containerPort: {{ add $startingPort $i }}
protocol: TCP
{{- end }}
{{- end}}
What I want to do instead is use the function to instead grab the values under MIN_PORT and MAX_PORT and do the same thing.
Is this possible? And, if so, I'd appreciate suggestions on how this can be accomplished.
Thanks!
That env: data structure will be hard to traverse from Helm template code. The values you show can easily be computed, and instead of trying to inject a complete environment-variable block in Helm values, it might be easier to construct the environment variables in your template.
# templates/deployment.yaml -- NOT values.yaml
env:
{{- $p := .Values.imageName.portInfo }}
- name: MIN_PORT
value: {{ $p.startingPort }}
- name: MAX_PORT
value: {{ add $p.startingPort (sub $p.numberOfPorts 1) }}
If you really absolutely can't change the values format, this is possible. Write a helper function to get a value from the .Values.env list:
{{/* Get a value from an association list, like a container env:
array. Each item of the alist is a dictionary with keys
`name:` and `value:`. Call this template with a list of two
items, the alist itself and the key to look up; outputs the
value as a string (an empty string if not found, all values
concatenated together if there are duplicates). */}}
{{- define "alist.get" -}}
{{- $alist := index . 0 -}}
{{- $needle := index . 1 -}}
{{- range $k, $v := $alist -}}
{{- if eq $k $needle -}}
{{- $v -}}
{{- end -}}
{{- end -}}
{{- end -}}
Then in your generator template, you can call this with .Values.env, using the Helm-specific include function to invoke a template and get its result as a string, and then atoi to convert that string to a number.
{{- define "ports.list" -}}
{{- $startingPort := include "alist.get" (list .Values.env "MIN_PORT") | atoi }}
{{- $endingPort := include "alist.get" (list .Values.env "MAX_PORT") | atoi }}
{{- range untilStep $startingPort (add $endingPort 1) 1 -}}
- containerPort: {{ . }}
protocol: TCP
{{ end -}}
{{- end -}}
This approach is both more complex and more fragile than directly specifying the configuration parameters in values.yaml. Helm doesn't have great support for unit-testing complex templates (I've rigged up a test framework using helm template and shunit2 in the past) and there's some risk of it going wrong.

How to use printf in this Helm template function?

I created this Helm template function in my templates/_helpers.yaml file. It simply gets the gets the value of an array element (the index .Values... part), based on the passed-in environment. It works fine.
{{/*
Function to get min CPU units
*/}}
{{- define "microserviceChart.minCpuUnits" -}}
{{ index .Values.valuesPerEnvironment.cpuUnits ((pluck .Values.environment .Values.environments | first | default .Values.environments.sandbox) | int) | quote }}
{{- end }}
For example, in my values.yaml file
environments:
sandbox: 0
staging: 1
production: 2
valuesPerEnvironment:
cpuUnits: [512, 512, 1024]
so my template function returns "512", "512", "1024" based on my passed-in environment. However, can I use printf to it adds m to these values? In other words, I want it to return "1024m" for production. I tried the following but I get a syntax error
{{/*
Function to get min CPU units
*/}}
{{- define "microserviceChart.minCpuUnits" -}}
{{- printf "%dm" index .Values.valuesPerEnvironment.cpuUnits ((pluck .Values.environment .Values.environments | first | default .Values.environments.sandbox) | int) | quote }}
{{- end }}
Instead of trying to get the arguments in the right order for printf, you could include the m in the template body. You'll also need to make the "..." explicit, instead of using the quote function, to get the m inside the quotes.
Expanded out (note that {{- and -}} will delete whitespace before and after, including newlines):
{{- define "microserviceChart.minCpuUnits" -}}
"
{{- index .Values.valuesPerEnvironment.cpuUnits ((pluck .Values.environment .Values.environments | first | default .Values.environments.sandbox) | int) -}}
m"
{{- end }}
The heck with it. I just made my values.yaml like this, and I get the same result.
environments:
sandbox: 0
staging: 1
production: 2
valuesPerEnvironment:
cpuUnits: [512m, 512m, 1024m]
It'd still be cool to know if I can do this in the function, so if someone answers the actual question, I'll accept that as the answer.

Creating a filtered list using helm template helpers

I'm trying to use a helm template helper to filter out values from a list in my values.yaml file, based on the value of one of the keys in each list member.
My chart is currently comprised of these files -
values.yaml -
namespaces:
- name: filter
profiles:
- nonProduction
- name: dont-filter
profiles:
- production
clusterProfile: production
templates/namespaces.yaml
apiVersion: v1
kind: List
items:
{{ $filteredList := include "filteredNamespaces" . }}
{{ range $filteredList }}
{{ .name }}
{{- end -}}
templates/_profile-match.tpl
{{/* vim: set filetype=mustache: */}}
{{- define "filteredNamespaces" -}}
{{ $newList := list }}
{{- range .Values.namespaces }}
{{- if has $.Values.clusterProfile .profiles -}}
{{ $newList := append $newList . }}
{{- end -}}
{{ end -}}
{{ $newList }}
{{- end -}}
The problem is that within my helper file, the $newList variable is only populated within the scope of the range loop, and I end up with an empty list returning to the namespaces.yaml template.
Is there any way around this issue? Am I taking the wrong approach for solving this?
For all that Go templates are almost general-purpose functions, they have a couple of limitations. One of those limitations is that they only ever return a string; you can't write basic functional helpers like map or filter because you can't return the resulting list.
The more straightforward approach to doing filtering as you've shown is to move it up to the point of the caller (and possibly repeat the condition if it's needed in multiple places):
items:
{{- range .Values.namespaces }}
{{- if has $.Values.clusterProfile .profiles }}
- {{ .name }}
{{- end }}
{{- end }}
A hacky way to make this work as you have it is to marshal the list to some other string-based format, like JSON:
{{- define "filteredNamespaces" -}}
...
{{ toJson $newList }}
{{- end -}}
{{- range include "filteredNamespaces" . | fromJson -}}...{{- end -}}
Also remember that you can inject Helm values files using the helm install -f option. So rather than listing every permutation of option and then filtering out the ones you don't want, you could restructure this so that namespaces: only contains the list of namespaces you actually want to use, but then you use a different values file for each profile.
I had to deal with a very similar problem. I'm giving a minimal example how to filter and use the generated template as a list (Helm 3).
_helpers.tpl:
{{- define "FilteredList" -}}
{{ $newList := list }}
{{- range .Values.my_list }}
{{ $newList = append $newList .pvc }}
{{- end }}
{{ toJson $newList }}
{{- end }}
pvc.yaml:
{{- range include "FilteredList" . | fromJsonArray }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ . }}
spec:
resources:
requests:
storage: 1G
---
{{- end }}
values.yaml:
my_list:
- name: foo
pvc: pvc-one
- name: foo2
pvc: pvc-two
- name: foo3
pvc: pvc-three
Generates 3 PVC resources as you would expect.
Mind 2 things here, which differ from the question and accepted answer:
When appending and overriding the list, we use = instead of :=. Note the example the Helm 3 docs for "append" provide: $new = append $myList 6.
I actually don't know why = is required, a quick research from my side was without any result.
Recover the list from the JSON string using fromJsonArray. This function is not documented yet which is very unfortunate and the main reason i provide this extra answer. You can find it in Helm's source however.
We faced a similar problem and thanks to the answer provided from nichoio we were able to solve this. Just for google's sake, I'll provide it here as well :)
Our values.yaml included all of our secret references, and we wanted to filter those secrets, based upon which service is currently being deployed.
We added a new array in the values.yaml (named selectedSecrets), which was a list of secrets that are needed for the current deployment. Then, with the help of a function, only the secret references are passed to the deployment, which are included in the selectedSecrets. Please note, that the following function returns the original, complete list of secretRefs if no selectedSecrets are present.
{{- define "FilteredSecrets" -}}
{{ $result := .Values.secretRefs }}
{{ $selectedSecrets := .Values.selectedSecrets }}
{{- if gt (len $selectedSecrets) 0 -}}
{{ $result = list }}
{{ range $secret := .Values.secretRefs }}
{{ if has $secret.name $selectedSecrets }}
{{ $result = append $result $secret }}
{{- end -}}
{{- end }}
{{- end -}}
{{ toJson $result }}
{{- end }}
The relevant part from the deployment:
containers:
- env:
{{- range include "FilteredSecrets" . | fromJsonArray }}
{{- range $env := .envs }}
- name: {{ $env.name }}
valueFrom:
secretKeyRef:
key: {{ $env.name }}
name: {{ .name }}
optional: {{ $env.optional }}
{{- end }}
{{- end }}

Helm optional nested variables

How do I make an optional block in the values file and then refer to it in the template?
For examples, say I have a values file that looks like the following:
# values.yaml
foo:
bar: "something"
And then I have a helm template that looks like this:
{{ .Values.foo.bar }}
What if I want to make the foo.bar in the values file optional? An error is raised if the foo key does not exist in the values.
I've tried adding as an if conditional. However, this still fails if the foo key is missing:
{{ if .Values.foo.bar }}
{{ .Values.foo.bar }}
{{ end }}
Any thoughts are much appreciated.
Simple workaround
Wrap each nullable level with parentheses ().
{{ ((.Values.foo).bar) }}
Or
{{ if ((.Values.foo).bar) }}
{{ .Values.foo.bar }}
{{ end }}
How does it work?
Helm uses the go text/template and inherits the behaviours from there.
Each pair of parentheses () can be considered a pipeline.
From the doc (https://pkg.go.dev/text/template#hdr-Actions)
It is:
The default textual representation (the same as would be printed by fmt.Print)...
With the behaviour:
If the value of the pipeline is empty, no output is generated... The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.
As such, by wrapping each nullable level with parentheses, when they are chained, the predecessor nil pointer gracefully generates no output to the successor and so on, achieving the nested nullable fields workaround.
Most charts will default the parent object to a empty map in values.yaml so it always exists.
foo: {}
Then {{ if .Values.foo.bar }} works.
If that's not possible, test both keys:
{{ if .Values.foo }}
{{ if .Values.foo.bar }}
{{ .Values.foo.bar }}
{{ end }}
{{ end }}
Using the and function doesn't work in this case due to and evaluating all parameters, even if the first is falsey.
There is also the hasKey function included from sprig if you ever need to check the existence of a falsey or empty value:
{{ if hasKey .Values.foo "bar" }}
A technique I've used successfully is to use a variable to hold the value of the outer block, which then can use templating constructs like default and Sprig's dict helper.
{{- $foo := .Values.foo | default dict -}}
Bar is {{ $foo.bar | default "not in the values file" }}
This provides a fallback dictionary if foo isn't in the file, so then $foo is always defined and you can look up $foo.bar in it.
Use with
Look at the with operator. This limits the current scope to the level of .Values.foo, and the block is silently ignored if .foo is missing:
{{- with .Values.foo }}
{{- .bar }}
{{- end }}
There is a new function implemented in sprig called dig that just does fix this issue, see here http://masterminds.github.io/sprig/dicts.html .
Is not yet released so even less likely to be in helm soon.
Meanwhile I have modified #Samuel solution to mimic the new dig function.
{{- define "dig" -}}
{{- $mapToCheck := index . "map" -}}
{{- $keyToFind := index . "key" -}}
{{- $default := index . "default" -}}
{{- $keySet := (splitList "." $keyToFind) -}}
{{- $firstKey := first $keySet -}}
{{- if index $mapToCheck $firstKey -}} {{/* The key was found */}}
{{- if eq 1 (len $keySet) -}}{{/* The final key in the set implies we're done */}}
{{- index $mapToCheck $firstKey -}}
{{- else }}{{/* More keys to check, recurse */}}
{{- include "dig" (dict "map" (index $mapToCheck $firstKey) "key" (join "." (rest $keySet)) "default" $default) }}
{{- end }}
{{- else }}{{/* The key was not found */}}
{{- $default -}}
{{- end }}
{{- end }}
and you can call it like this
$regKey := include "dig" (dict "map" .Values "key" "global.registryKey" "default" "")
I searched around for an answer to this same question, and couldn't find anything out there. It seems you have to use a custom function, so I wrote one. Here is what I came up with. It works for my use cases, feedback/improvements are welcome.
_helpers.tpl
{{- define "hasDeepKey" -}}
{{- $mapToCheck := index . "mapToCheck" -}}
{{- $keyToFind := index . "keyToFind" -}}
{{- $keySet := (splitList "." $keyToFind) -}}
{{- $firstKey := first $keySet -}}
{{- if index $mapToCheck $firstKey -}}{{*/ The key was found */}}
{{- if eq 1 (len $keySet) -}}{{*/ The final key in the set implies we're done */}}
true
{{- else }}{{*/ More keys to check, recurse */}}
{{- include "hasDeepKey" (dict "mapToCheck" (index $mapToCheck $firstKey) "keyToFind" (join "." (rest $keySet))) }}
{{- end }}
{{- else }}{{/* The key was not found */}}
false
{{- end }}
{{- end }}
values.yaml:
{{- if eq "true" (include "hasDeepKey" (dict "mapToCheck" .Values "keyToFind" "foo.bar")) }}
bar: {{- .Values.foo.bar }}
{{- end }}