When writing charts with Helm, the Kubernetes package manager, it’s often necessary to incorporate some sort of input validation to ensure deployments go as-planned. I’ll talk about two ways of performing validation – using the ‘required‘ and ‘fail‘ functions.
Required
The better-known function of the two is the required function. According to the Helm docs,
The
required
function gives developers the ability to declare a value entry as required for template rendering. If the entry is empty in values.yml, the template will not render and will return an error message supplied by the developer.
Let’s use the following template as an example:
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ required "Name of ConfigMap is required" .Values.configName }}
data:
file0: |
Learning how to use the required function!
In order to deploy successfully, the ‘configName’ value must be provided, or the deployment will fail with the message “Name of ConfigMap is required“. Provide the value in values.yaml with
configName: my-configmap
or provide the value on the command line with
--set configName=my-configmap
Fail
Another function that comes in handy is the fail function. This function is part of the Sprig library. According to the Sprig documentation,
Unconditionally returns an empty
string
and anerror
with the specified text. This is useful in scenarios where other conditionals have determined that template rendering should fail.
Whereas required checked for a value’s existence, fail can ensure that the provided value is valid. Here’s an example:
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ required "Name of ConfigMap is required" .Values.configName }}
data:
file0: |
Learning how to use the {{ required "Function type required" .Values.functionType }} function!
{{- $valid := list "fail" "required" }}
{{- if not (has .Values.functionType $valid) }}
{{- fail "Invalid function type" }}
{{- end }}
In this case, the functionType value is compared against two strings. If the value is not equal to one of the strings, the chart will fail with the message “Invalid function type“.
With these two functions, input validation should be a breeze!