Mapping a value in Helm 3 to another value

4/10/2020

I'm building a Helm 3 library chart and would like to convert an input value to another value that's based on a preset map.

Say my values.yaml includes the following value:

global:
  environment: production # (production/staging/test/development)

I have the following convention for converting a long environment name to a short one:

production => prod
staging => stage
test => test
development => dev

I would like to use the value stored in .Values.global.environment to generate a deployment name that is prefixed with the short environment name. In this case, it should be mapped to prod-<application_name>.

How can this be achieved with Helm 3?

-- mittelmania
kubernetes-helm

1 Answer

4/10/2020

Add a helper function under templates/_helpers.tpl file.

Unfortunately, there's no switch functionality in go templates so it has to be "dirty" if else

{{/*
Environment name mapping
*/}}
{{- define "my-chart.environment" -}}
{{- if .Values.global.environment -}}
{{- if eq .Values.global.environment "production" -}}
{{- printf "prod" -}}
{{- else if eq .Values.global.environment "staging" -}}
{{- printf "stage" -}}
{{- else if eq .Values.global.environment "test" -}}
{{- printf "test" -}}
{{- else if eq .Values.global.environment "development" -}}
{{- printf "dev" -}}
{{- end -}}
{{- end -}}
{{- end -}}

then, use this template in the my-chart.fullname template

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "my-chart.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
##### ADDITIONAL LINES
{{- if .Values.global.environment -}}
{{- printf "%s-%s-%s" (include "my-chart.environment" .) .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
##### END ADDITIONAL LINES
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}

Test:

/apps/my-chart # helm version
version.BuildInfo{Version:"v3.1.2", GitCommit:"d878d4d45863e42fd5cff6743294a11d28a9abce", GitTreeState:"clean", GoVersion:"go1.13.8"}

/apps/my-chart # cat ./values.yaml
# Default values for my-chart.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

global:
  environment: development

Running helm template . output:

...
...
# Source: my-chart/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dev-RELEASE-NAME-my-chart
...
...
-- Totem
Source: StackOverflow