Helm: generate comma separated list

耗尽温柔 提交于 2019-12-03 13:31:59

I faced with the same problem and your solution with dictionary saved my day. It's a good workaround and it can be just a little simpler:

{{- define "zkservers" -}}
{{- $zk := dict "servers" (list) -}}
{{- range int . | until -}}
{{- $noop := printf "zk-%d.zookeeper" . | append $zk.servers | set $zk "servers" -}}
{{- end -}}
{{- join "," $zk.servers -}}
{{- end -}}

Another quick way of doing it:

{{- define "helm-toolkit.utils.joinListWithComma" -}}
{{- $local := dict "first" true -}}
{{- range $k, $v := . -}}{{- if not $local.first -}},{{- end -}}{{- $v -}}{{- $_ := set $local "first" false -}}{{- end -}}
{{- end -}}

If you give this input like:

test:
- foo
- bar

And call with:

{{ include "helm-toolkit.utils.joinListWithComma" .Values.test }}

You'll get the following rendered:

foo,bar

This is from OpenStack-Helm's Helm-toolkit chart, which is a collection of utilities for similar purposes.

I got it working using:

{{- define "zkservers" -}}
{{- $dot := dict "nodes" (int .) "servers" (list) -}}
{{- template "genservers" $dot -}}
{{- join "," $dot.servers -}}
{{- end -}}

{{- define "genservers" -}}
{{- range until .nodes -}}
{{- $noop := print "zk-" . ".zookeeper" | append $.servers | set $ "servers" -}}
{{- end -}}
{{- end -}}

Seems a little bit verbose for what should normally be a simple one/two liner :)

I was doing the same but on elasticsearch helm chart. Please find my example

values.yml:

...
replicaCount: 3
...

StatefulSets.yaml:

...
      containers:
        - name: {{ .Chart.Name }}
          image: "{{ .Values.registry_address }}/{{ .Values.image.name }}:{{ .Chart.AppVersion }}"
          env:
            - name: ELASTICSEARCH_CLUSTER_NAME
              value: "{{ .Values.env.ELASTICSEARCH_CLUSTER_NAME }}"
            - name: ELASTICSEARCH_DISCOVERY_ZEN_PING_UNICAST_HOSTS
              value: "{{ template "nodes" .Values }}"
...

_helpers.tpl:

{{/* vim: set filetype=mustache: */}}

{{- define "nodes" -}}
{{- $nodeCount := .replicaCount | int }}
  {{- range $index0 := until $nodeCount -}}
    {{- $index1 := $index0 | add1 -}}
elasticsearch-{{ $index0 }}.elasticsearch{{ if ne $index1 $nodeCount }},{{ end }}
  {{- end -}}
{{- end -}}

This produces a comma separated list:

...
            - name: ELASTICSEARCH_DISCOVERY_ZEN_PING_UNICAST_HOSTS
              value: "elasticsearch-0.elasticsearch,elasticsearch-1.elasticsearch,elasticsearch-2.elasticsearch"

...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!