Kubernetes Helm, combine two variables with a string in the middle

7/24/2017

I’m trying to change the value of a variable if another variable it set by combining the two with a dash in the middle, I’m not sure of the syntax to do this, I’m thinking of somethings like:

{{- $serviceNamespace := .Values.serviceNamespace -}}
{{- $serviceTag := .Values.serviceTag -}}
{{- if $serviceTag}}
{{- $serviceNamespace := .Values.serviceNamespace  "-" .Values.serviceTag -}}
{{- end}}

Is this correct? if serviceNamespace was hello and serviceTag was 1.0.0 would I end up with serviceNamespace being hello-1.0.0?

-- Simon I
go-templates
kubernetes
kubernetes-helm

2 Answers

7/25/2017

For concatenation just use printf:

{{-  $serviceNamespace := printf "%s-%s" .Values.serviceNamespace .Values.serviceTag -}}
-- abinet
Source: StackOverflow

1/25/2018

Update

It is now possible in the 1.11 version of golang, see commit:

{{- $serviceNamespace := .Values.serviceNamespace -}}
{{- $serviceTag := .Values.serviceTag -}}
{{- if $serviceTag}}
{{- $serviceNamespace = .Values.serviceNamespace  "-" .Values.serviceTag -}}
{{- end}}

Notice the new = operator in $serviceNamespace = .Values.serviceNamespace "-" .Values.serviceTag

Older golang versions

You cannot currently (in golang 1.9, but available in 1.11, see update above) reassign template variables because if introduces a new scope. Until this is fixed (see issue and proposed fix), you can work around this by writing a function:

{{ define "makeServiceNamespace" }}
    {{- if .Values.serviceTag }}
    {{- printf "%s-%s" .Values.serviceNamespace .Values.serviceTag -}}
    {{- else }}
    {{- print .Values.serviceNamespace }}
    {{- end }}
{{- end }}

Then use it like so:

serviceNamespace: {{ template makeServiceNamespace . }}
-- David
Source: StackOverflow