Search code examples
mongodbkuberneteskubernetes-helm

helm range loop over values array onliner to get comma separated values list


I am new to helm chart , attempting to form my connection string to connect to mongodb cluster, here is my Values.yaml file:

mongos:
  - mongos1
  - mongos2

Here is my Template.yaml:

 uri: {{ "mongodb://" -}} {{ range $value := .Values.mongos }} {{-  printf "%s:27017" $value  -}} {{- end }}

But cannot figure out how to add the commas , here is current result:

  uri: mongodb://mongos1:27017mongos2:27017

It needs to look as follow:

  uri: "mongodb://mongos1:27017,mongos2:27017/?authSource=admin"

Playground

Please, advice how to add the commas between the host:port so it get correct list if I add arbitrary number of mongos in the values.yaml in the future?


Solution

  • When iterating through the hosts, you can also get access to the index, and use this to conditionally prepend a comma

    
    uri: {{ "mongodb://" -}} {{ range $i, $value := .Values.mongos }} {{- if $i -}},{{- end }} {{-  printf "%s:27017" $value  -}} {{- end }}
    
    

    Another option is to use the join function as David suggested, but to pre-create a temporary list holding the hostname+ports

    {{ $hostsAndPorts := list }}
    {{ range .Values.mongos }}
      {{ $hostAndPort := printf "%s:27017" . }}
      {{ $hostsAndPorts = append $hostAndPort }}
    {{ end }}
    
    ...
    
    
    uri: {{ "mongodb://" }}{{ $hostsAndPorts | join "," }}{{ "/?authSource=admin" }}