How to validate Helm values that are not present in values.yaml

2/2/2020

Input

I'm writing a helm chart containing following values.yaml:

backend:
  container:
    resources: {}
  hpa:
    enabled: false
    targetCPUUtilizationPercentage: 50

Then in a template file a deployment definition looks like:

template:
  spec:
    containers:
      - name: "some-name"
        image: "some-repo/some-image:latest"
        resources:
          {{- toYaml .Values.backend.container.resources | nindent 12 }}

Problem

On default I disable the Horizontal Pod Autoscaler (backend.hpa.enabled=false), but if user enables it, I want to be sure that property backend.container.resources.requests.cpu is specified. Otherwise HPA wouldn't work. So I would like to throw exception in that case. How to implement such a validation check?

Attempt 1

I tried to write HPA template in following wrapper:

{{- if .Values.backend.hpa.enabled -}}
{{- if required "Specify requests!" .Values.backend.container.resources.requests.cpu -}}
...
{{- end -}}
{{- end -}}

But it throws nil exception on parsing template when backend.container.resources.requests.cpu is not specified (even if backend.hpa.enabled=false).

Attempt 2

If I replace values.yaml with the following fragment, then kubernetes will not allow to set such cpu value (illegal format, null is invalid too). Is that something that I can assign to a cpu field, that will be considered as default value in kubernetes? I think it could be not very elegant, but feasible solution.

backend:
  container:
    resources:
      requests:
        cpu: ""
  hpa:
    enabled: false
    targetCPUUtilizationPercentage: 50
-- Anton Shelenkov
kubernetes
kubernetes-helm

1 Answer

2/2/2020

In Helm 3 you can use JSON Schema Validation, you can read about it here. You can use the IF condition there.

I wouldn't try to make the validation in the chart itself, because it will make your helm chart more complex.

-- RafaƂ Leszko
Source: StackOverflow