Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop in go helm chart templating [closed]

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, go templates seem to be lacking a means of rendering a 'for' loop, by design

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

like image 313
thoth Avatar asked Dec 04 '22 20:12

thoth


2 Answers

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.

like image 113
Kenny Grant Avatar answered Dec 28 '22 21:12

Kenny Grant


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 -}}
like image 28
thoth Avatar answered Dec 28 '22 21:12

thoth