Define a variable in Helm template
15,716
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" .) -}}
Author by
Moshe
Devops for pay, Frontend for fun. I have a sweet corgi at home named Johnny :) My site
Updated on October 01, 2022Comments
-
Moshe over 1 year
I need to define a variable based on an
if
statement and use that variable multiple times. In order not to repeat theif
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?
-
Samuel Åslund over 2 yearsNice solution to that problem, but could you say something about the generic problem of how variables are scoped? (I want to append values inside a loop to a list I want to use outside that loop.)