Helm 'if' condition in one line
Asked Answered
N

1

9

I was trying to put the if condition in a single line of the helm template:

- name: ENV_VARIABLE
  value: {{- if .Values.condition }}"Value1"{{- else }}"Value2"{{- end }}

However, I'm getting error:

Error: YAML parse error on chart/templates/deployment.yaml: error converting YAML to JSON: yaml: line NN: could not find expected ':'

So I've ended up with multi-line condition:

- name: ENV_VARIABLE
{{- if .Values.condition }}
  value: "Value1"
{{- else }}
  value: "Value2"
{{- end }}
  

which is working fine, but is very uncompact.

Is there a way to use one-liner if condition in helm?

Nodababus answered 2/6, 2022 at 7:46 Comment(0)
B
12

What you do works, but you use the leading hyphen, which removes all preceding whitespace.

The below will render as value:foo due to the hyphen.

value: {{- "foo" }}

If you remove the hyphen, it should work.

That said, there is also the ternary function which could fit here.

ternary

The ternary function takes two values, and a test value. If the test value is true, the first value will be returned. If the test value is empty, the second value will be returned. This is similar to the c ternary operator.

true test value

ternary "foo" "bar" true
or

true | ternary "foo" "bar"

- name: ENV_VARIABLE
  value: {{ .Values.condition | ternary "value1" "value2" | quote }}
Blacking answered 2/6, 2022 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.