Global variables in helm templating language to avoid repetition

10/4/2019

I am new to helm and helm templating language. I have the following in my _helper.tpl:

{{/*
Get couchdb password
*/}}
{{- define "couchdb.password" -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- printf "'@refsec/couchdb-%s/adminPassword'" $name -}}
{{- end -}}

{{/* 
Get couchdb username 
*/}}
{{- define "couchdb.username" -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- printf "'@refsec/couchdb-%s/adminUsername'" $name -}}
{{- end -}}

But there is an issue with this piece of code. REPETTION!! As you see this line is repeated 2 times: {{- $name := default .Chart.Name .Values.nameOverride -}}

Can I define a global variable for these casesa and use it over and over without repetition?

-- Learner
kubernetes
kubernetes-helm

1 Answer

10/5/2019

In principle you can define a template just for that one line

{{- define "couchdb.chart.name" -}}
{{- default .Chart.Name .Values.nameOverride -}}
{{- end -}}

But the syntax to invoke it isn't actually much shorter

{{- define "couchdb.password" -}}
{{- $name := include "couchdb.chart.name" . -}}
{{- printf "'@refsec/couchdb-%s/adminPassword'" $name -}}
{{- end -}}

{{- define "couchdb.username" -}}
{{- printf "'@refsec/couchdb-%s/adminUsername'" (include "couchdb.chart.name" .) -}}
{{- end -}}

I'm pretty sure the Go text/template language doesn't have global variables in the form you're suggesting here. The documentation describes variable syntax and invocation, but contains the slightly cryptic note

A template invocation does not inherit variables from the point of its invocation.

and I think from reading other context there's not "global scope" so much as "a main template".

In any case, I've never seen a global variable in a Helm chart, and even variables in the form you show in the question are a little bit unusual.

-- David Maze
Source: StackOverflow