How to use range function to keep values in same line in helm

2.6k views Asked by At

I am trying to build configmap data out of values I have in values.yaml.

CASE 1:
values.yaml:
  example: abc xyz 
  servers: IP1 IP2 IP3

I want configmap data something like all the example domain forwarded to servers.

It would be really grateful if someone helps me out. Thanks in advance!!!

1

There are 1 answers

0
David Maze On BEST ANSWER

With the format you currently have, .Values.dns_servers is already a string with space-separated values, which is the format you want out. You don't need to split it to a list and write it out again.

{{- if .Values.dns_servers }}
forward . {{ .Values.dns_servers }}
{{- end }}

Helm contains (almost all of) the extension functions in the Sprig library, not all of which are in the Helm documentation proper. If you do have this as a list, there is a join template function that can combine them together.

{{- $dns_servers := splitList " " .Values.dns_servers }}
{{- if $dns_servers }}
forward . {{ join " " $dns_servers }}
{{- end }}

Rather than a space-separated string, you might find it easier to manipulate these values if you use native YAML lists in your values.yaml file. Any valid YAML list syntax will work here, including formats that put the entire list on one line.

# values.yaml, reformatted to use YAML lists and snakeCase names
dnsDomains: [abc,xyz]
dnsServers:
  - 10.10.10.10
  - 10.10.10.11
  - 10.10.20.20

As one final option, if you're very careful about the whitespace handling, you can put the templating anywhere you want, even in the middle of a line.

{{- with .Values.dnsServers }}
forward .
{{- range . }} {{ . }}{{ end }}
{{- end }}

The important trick with this last example is that the - whitespace control before range also consumes the newline at the end of the previous line. Then inside the range block, repeated once for each element and with no whitespace control, there is a space and a list element. Finally after the very last end there is a newline.

You can double-check this with helm template, which will validate the YAML syntax and print out what got rendered (with --debug it will print it out even if it's invalid YAML).