Use ternary condition in Helm

0
15974
Use ternary condition in Helm
Use ternary condition in Helm

In this post, I will show you how to use ternary condition in Helm to render inline values into the templates.

Let say we have this following template:

{{- define "scheme" -}}
{{- if .Values.secured }}https{{ else }}http{{ end }}
{{- end -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: mychart-configmap
data:
  url: {{ template "scheme" . }}://blog.petehouston.com

The data.url value is rendered based on the value returned by scheme, but it seems to have only two conditions and we want to transform it into an inline rendering, I mean inject it directly into the data.url without defining extra template variable at the top.

We can do that by performing inline condition like this:

apiVersion: v1
kind: ConfigMap
metadata:
  name: mychart-configmap
data:
  url: {{ if .Values.secured }}https{{ else }}http{{ end }}://blog.petehouston.com

It works! However, in reality, the condition will be more complicated and the returning values are longer than this. Reading a line with tons of {{ }} pairs is quite troublesome.

To simplify, we can use the ternary function provided by Helm based on the Sprig library.

We can re-write the above template like this:

{{- $scheme := ternary "https" "http" .Values.secured -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: mychart-configmap
data:
  url: {{ $scheme }}://blog.petehouston.com

We can also render the $scheme directly into data.url:

apiVersion: v1
kind: ConfigMap
metadata:
  name: mychart-configmap
data:
  url: {{ ternary "https" "http" .Values.secured }}://blog.petehouston.com

Also, if the logical flow doesn’t make sense to the eyes, you can use the pipe | :

apiVersion: v1
kind: ConfigMap
metadata:
  name: mychart-configmap
data:
  url: {{ .Values.secured | ternary "https" "http" }}://blog.petehouston.com

That’s how you use ternary condition in Helm to render values in-place in Helm templates.

Have fun!