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?
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" .) -}}