1
votes

I created this Helm template function in my templates/_helpers.yaml file. It simply gets the gets the value of an array element (the index .Values... part), based on the passed-in environment. It works fine.

{{/*
Function to get min CPU units
*/}}
{{- define "microserviceChart.minCpuUnits" -}}
{{ index .Values.valuesPerEnvironment.cpuUnits ((pluck .Values.environment .Values.environments | first | default .Values.environments.sandbox) | int) | quote }}
{{- end }}

For example, in my values.yaml file

environments:
  sandbox: 0
  staging: 1
  production: 2
valuesPerEnvironment:
  cpuUnits: [512, 512, 1024]

so my template function returns "512", "512", "1024" based on my passed-in environment. However, can I use printf to it adds m to these values? In other words, I want it to return "1024m" for production. I tried the following but I get a syntax error

{{/*
Function to get min CPU units
*/}}
{{- define "microserviceChart.minCpuUnits" -}}
{{- printf "%dm" index .Values.valuesPerEnvironment.cpuUnits ((pluck .Values.environment .Values.environments | first | default .Values.environments.sandbox) | int) | quote }}
{{- end }}
2

2 Answers

1
votes

The heck with it. I just made my values.yaml like this, and I get the same result.

environments:
  sandbox: 0
  staging: 1
  production: 2
valuesPerEnvironment:
  cpuUnits: [512m, 512m, 1024m]

It'd still be cool to know if I can do this in the function, so if someone answers the actual question, I'll accept that as the answer.

0
votes

Instead of trying to get the arguments in the right order for printf, you could include the m in the template body. You'll also need to make the "..." explicit, instead of using the quote function, to get the m inside the quotes.

Expanded out (note that {{- and -}} will delete whitespace before and after, including newlines):

{{- define "microserviceChart.minCpuUnits" -}}
"
{{- index .Values.valuesPerEnvironment.cpuUnits ((pluck .Values.environment .Values.environments | first | default .Values.environments.sandbox) | int) -}}
m"
{{- end }}