Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a variable in Helm template

I need to define a variable based on an if statement and use that variable multiple times. In order not to repeat the if I tried something like this:

{{ if condition}}
    {{ $my_val = "http" }}
{{ else }}
    {{ $my_val = "https" }}
{{ end }}
{{ $my_val }}://google.com

However this returns an error:

Error: render error in "templates/deployment.yaml":
template: templates/deployment.yaml:30:28:
executing "templates/deployment.yaml" at
<include (print $.Template.BasePath "/config.yaml") .>: error calling
include: template: templates/config.yaml:175:59:
executing "templates/config.yaml" at <"https">: undefined variable: $my_val

Ideas?

like image 339
Moshe Avatar asked May 27 '19 10:05

Moshe


People also ask

What does {{ }} mean in Helm?

The Helm template syntax is based on the Go programming language's text/template package. The braces {{ and }} are the opening and closing brackets to enter and exit template logic.

What is define in Helm chart?

Helm uses a packaging format called charts. A chart is a collection of files that describe a related set of Kubernetes resources. A single chart might be used to deploy something simple, like a memcached pod, or something complex, like a full web app stack with HTTP servers, databases, caches, and so on.

How do I set Helm value?

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.


1 Answers

The most direct path to this is to use the ternary function provided by the Sprig library. That would let you write something like

{{ $myVal := ternary "http" "https" condition -}}
{{ $myVal }}://google.com

A simpler, but more indirect path, is to write a template that generates the value, and calls it

{{- define "scheme" -}}
{{- if condition }}http{{ else }}https{{ end }}
{{- end -}}

{{ template "scheme" . }}://google.com

If you need to include this in another variable, Helm provides an include function that acts just like template except that it's an "expression" rather than something that outputs directly.

{{- $url := printf "%s://google.com" (include "scheme" .) -}}
like image 172
David Maze Avatar answered Sep 22 '22 17:09

David Maze