Search code examples
kubernetes-helmsprig-template-functions

Encode integer in Helm template


I am working on a set of Helm templates for a web service, which takes as part of it's configuration an integer Id. That Id becomes part of the service endpoints, encoded to a web-safe base64 character set:

0=A
1=B
2=C
...
26=a
...
63=_

Within my Helm template I want to take that integer Id and determine the encoded value, so that I can insert it in an Nginx location block. The actual encoding logic is something like (psuedo-code):

func Encode(int i) {
  byte b = i << 2 # shift integer two bits
  string s = web_base64(b)
  char c = s[0] # return first char only
}

So far the closest I've gotten in Helm is just creating a lookup, like $d := dict "0" "A" "1" "B" "2" "C" ... and then using {{ .Values.Id | toString | get $d }}.

Is there another way?


Solution

  • I finally came up with this:

    {{- with .Values.deployment.Id | int }}
      {{- if eq . 63 }}_
      {{- else if eq . 62 }}-
      {{- else if gt . 51 }}{{- sub . 52 | printf "%c" }}
      {{- else if gt . 25 }}{{- add . 71 | printf "%c" }}
      {{- else }}{{- add . 65 | printf "%c" }}
      {{- end }}
    {{- end }}
    

    Realizing I could do ordinal conversion via printf was the big a-ha moment, and this works great as long as the value for .Id isn't 0. If it is, the entire block just gets skipped. That seems to be a limitation of the with keyword. So, I'm left with this:

    {{- if eq (int .Values.deployment.Id) 63 }}_
    {{- else if eq (int .Values.deployment.Id) 62 }}-
    {{- else if gt (int .Values.deployment.Id) 51 }}{{- sub (int .Values.deployment.Id) 52 | printf "%c" }}
    {{- else if gt (int .Values.deployment.Id) 25 }}{{- add (int .Values.deployment.Id) 71 | printf "%c" }}
    {{- else }}{{- add (int .Values.deployment.Id) 65 | printf "%c" }}
    {{- end }}
    

    Which is still a little ugly, but better than a huge lookup.