98

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?

1
  • 1
    What is the need for reassigning $serviceNamespace variable again. Why can't use (( $serviceNamespace }} - {{ $serviceTag }}? Commented Jul 25, 2017 at 0:49

3 Answers 3

127

For concatenation just use printf:

{{-  $serviceNamespace := printf "%s-%s" .Values.serviceNamespace .Values.serviceTag -}}
Sign up to request clarification or add additional context in comments.

3 Comments

This gives me an error "mapping values are not allowed in this context" on helm install, but still works... ???
Thank you for this. I'm going to post an issue to their github repo which shows how I used this to avoid a string casting issue to int inside a range loop!
or if you want to concatenate string name: {{ .Release.Name }}-mystring-chart
85

You can simply do it like this , with string ":" in middle

"{{ $values.image.repository }}:{{ $values.image.tag }}"

2 Comments

How would you apply a function with a pipe to this then?
@Any1 have you found out how to pass this into a pipe?
41

Update

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

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

Notice the new = operator in $serviceNamespace = print .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 . }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.