loop in go helm chart templating

12/11/2017

I am trying to loop for a count in a kubernetes helm chart like this:

reaction.mongo_url_big: mongodb://{{ for $mongocount := 0; $mongocount < {{ .Values.mongodbReplicantCount }}; $mongocount++ }}{{ .Values.mongodbReleaseName }}-mongodb-replicaset-{{ $mongocount }}:{{ .Values.mongodbPort }}{{ if $mongocount < {{ .Values.mongodbReplicantCount }} - 1 }},{{ end }}{{ end }}/{{ .Values.mongodbName }}?replicaSet={{ .Values.mongodbReplicaSet }}

However, there is no for available in go templates as they will tell you themselves

I want it to output something like:

 reaction.mongo_url: mongodb://{{ .Values.mongodbReleaseName }}-mongodb-replicaset-0:{{ .Values.mongodbPort }},{{ .Values.mongodbReleaseName }}-mongodb-replicaset-1:{{ .Values.mongodbPort }},{{ .Values.mongodbReleaseName }}-mongodb-replicaset-2:{{ .Values.mongodbPort }}/{{ .Values.mongodbName }}?replicaSet={{ .Values.mongodbReplicaSet }}

The line in my helm chart is here: https://github.com/joshuacox/reactionetes/blob/gymongonasium/reactioncommerce/templates/configmap.yaml#L11

-- thoth
kubernetes
kubernetes-helm

2 Answers

12/12/2017

Use range:

{{ range .Values }}
   {{ .MongodbReleaseName }}
{{ end }}

This will output the .MongodbReleaseName (assuming that's a field) of every item in .Values. The value is assigned to . while within the range so you can simply refer to fields/functions of the individual Values. This is very like a for loop in other templating languages. You can also use it by assigning an index and value.

-- Kenny Grant
Source: StackOverflow

12/12/2017

Notice on the helm tips and tricks page they mention that sprig functions have been added, one of which is until, which can be seen in action here or in my case:

{{- define "mongodb_replicaset_url" -}}
  {{- printf "mongodb://" -}}
  {{- range $mongocount, $e := until (.Values.mongodbReplicaCount|int) -}}
    {{- printf "%s-mongodb-replicaset-%d." $.Values.mongodbReleaseName $mongocount -}}
    {{- printf "%s-mongodb-replicaset:%d" $.Values.mongodbReleaseName ($.Values.mongodbPort|int) -}}
    {{- if lt $mongocount  ( sub ($.Values.mongodbReplicaCount|int) 1 ) -}}
      {{- printf "," -}}
    {{- end -}}
  {{- end -}}
  {{- printf "/%s?replicaSet=%s" $.Values.mongodbName  $.Values.mongodbReplicaSet -}}
{{- end -}}
-- thoth
Source: StackOverflow