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"
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
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.
Now you can use Helm-specific
include
to evaluate that template, capturing the result in a string, and remove the trailing comma.The Sprig support library includes a
join
function, and this is also present in Helm, so in principle you canjoin "," $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.When iterating through the hosts, you can also get access to the index, and use this to conditionally prepend a comma
Another option is to use the
join
function as David suggested, but to pre-create a temporary list holding the hostname+ports