Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 445
Joe J Avatar asked Jan 17 '20 22:01

Joe J


People also ask

What is TPL in Helm?

The tpl function allows developers to evaluate strings as templates inside a template. This is useful to pass a template string as a value to a chart or render external configuration files.

How do I override values Yaml in Helm?

You can use a --set flag in your Helm commands to override the value of a setting in the YAML file. Specify the name of the setting and its new value after the --set flag in the Helm command. The --set flag in the above command overrides the value for the <service>. deployment.

What is $_ in Helm?

The $_ is used to suppress undesired output as "set" returns the new dictionary.


1 Answers

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.

like image 54
Torrey Avatar answered Sep 23 '22 05:09

Torrey