Helm - Adding a character only if value is present

12/19/2019

I have created a helm chart, Below is the snippet of the chart.

I will get value of gateway.contextpath from my values file.

prefix: /{{ .Release.Name }}/{{ .Values.gateway.contextpath}}/

There are few instances where gateway.contextpath are passed and few instances where the values are not passed. When values are passed, I get output as below

prefix: /sample/hello/

However, When the values are not passed, I see that / is added.

prefix: /sample//

Is it possible to control adding / based on the values file?

-- Sunil Gajula
kubernetes-helm

2 Answers

12/19/2019

You can define a function in _helpers.tpl, something like below

{{- define "superchart.getPath" -}}
{{- if .Values.gateway -}}
{{- if .Values.gateway.contextpath -}}
{{- printf "/%s/%s/" .Release.Name .Values.gateway.contextpath -}}
{{- else -}}
{{- printf "/%s/" .Release.Name -}}
{{- end -}}
{{- else -}}
{{- printf "/%s/" .Release.Name -}}
{{- end -}}
{{- end -}}

And use it in your deployment.yaml (or any other file)

prefix: {{ include "superchart.getPath" . }}

-- edbighead
Source: StackOverflow

12/19/2019

The Go text/template language has {{ if }}...{{ end }} conditionals and you can put almost arbitrary content inside of those. The direct approach to what you've shown could be

prefix: /{{ .Release.Name -}}
  {{- if .Values.gateway.contextpath -}}
    /{{ .Values.gateway.contextpath -}}
  {{- end -}}
  /

Wherever there's a - inside the curly braces, it causes the template engine to consume all of the whitespace adjacent to it, so this should appear in a single string (even though it's written over five lines).

(Remember that you can use the helm template command to render a chart without actually submitting it to Kubernetes, which is helpful for debugging.)

The aesthetics of the template file can be tricky; there are other ways you can rearrange this to possibly be more readable. Another alternative using a temporary variable:

{{- $p := .Values.gateway.contextpath }}
prefix: /{{ .Release.Name }}{{ if $p }}/{{ $p }}{{ end }}/

@edbighead's answer breaking this out into a completely separate template is a good approach too: the /path/part URL layout is fairly visible there, compared to my suggestions here.

-- David Maze
Source: StackOverflow