skip to Main Content

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?

2

Answers


  1. I might write a helper template that takes in the list of host names, appends a port number and a comma to each, and returns the resulting string. So long as there is at least one host name, this string is guaranteed to end with an unwanted comma, which is important.

    {{- define "mongo.hosts" -}}
    {{- range . -}}
    {{ . }}:27017,
    {{- end -}}
    {{- end -}}
    

    Now you can use Helm-specific include to evaluate that template, capturing the result in a string, and remove the trailing comma.

    url: mongodb://{{ include "mongo.hosts" .Values.mongos | trimSuffix "," }}
    

    The Sprig support library includes a join function, and this is also present in Helm, so in principle you can join "," $hostsAndPorts. But you need to get a list of strings as its input, and it’s a little bit tricky to transform one list of strings to another in the template language.

    Login or Signup to reply.
  2. 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" }}
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search