[SOLVED]: Helm Custom Error on template validation fail

When a new resource is to be created for kubernetes, both kubectl binary and helm will do its due diligence in validating the input value. There are different way to validate and input, one of such way is to use values.schema.json, using fail function, using required function.
In this article we will see how to customize error message in each case when the template validation fails

Helm Template validation  using Required function

The required function is used to ensure that a value is not left blank when a chart’s templates are rendered. It is named as such because it requires a user to provide a value when specified.

Below code snippet shows a sample values.yaml, where value of path is kept as empty

ingress:
    path:

Below code snippet shows the use of required function in the template chart and the custom error message set on the chart

spec:
  type: {{ required "value 'ingress.path' is required" .Values.service.type }}

When we try to see the action by using helm template command, we could see the custom error is shown a saying a error message "value 'ingress.path' is required"

helm template ldh linux-data-hub-sample-chart
Error: execution error at (required-example/templates/service.yaml:6:11): value 'ingress.path' is required

Helm Template validation using Fail function

Fail function immediately fails the execution. This is used along with conditional loop (if/else). The difference between required and fail function is, required function will throw error if the values for the parameter is missing from the values.yaml

Below shows a sample values.yaml under consideration. It can be seen that we have given a typo for Loadbalancer, just to simulate the error

service:
  type: Loadalancer

In the yaml present in the template, we are checking if the service type is Clusterip or Loadbalancer, and it have to fail , if any other service type is mentioned. Below shows the implementation, along with the

{{- $serviceTypes := list "ClusterIP" "LoadBalancer" }}
{{- if has .Values.service.type $serviceTypes }}
  type: {{ .Values.service.type }}
{{- else }}
  {{- fail "value 'service.type' must be either 'ClusterIP' or 'LoadBalancer'" }}
{{- end }}

If we try to do the dry run by executing helm template command, we will see below custom error

$ helm template ldh ldh-sample 
Error: execution error at (<trimmed>): value 'service.type' must be either 'ClusterIP' or 'LoadBalancer'

Also Read

[SOLVED]: Helm Split String by Delimiter

Reference

https://stackoverflow.com/questions/61496709/helm-template-how-raise-exception-in-in-helm-function

Search on LinuxDataHub

Leave a Comment