Define a variable in Helm template
Asked Answered
T

1

15

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?

Taeniasis answered 27/5, 2019 at 10:37 Comment(0)
M
34

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" .) -}}
Mulish answered 27/5, 2019 at 10:49 Comment(2)
Nice 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.)Americanism
https://mcmap.net/q/542368/-is-it-possible-to-define-variables-use-if-else-condition-in-helm-chart is a nice explanationCahilly

© 2022 - 2024 — McMap. All rights reserved.