<p><strong>Input</strong></p>

<p>I'm writing a helm chart containing following values.yaml:</p>

<pre><code>backend:
  container:
    resources: {}
  hpa:
    enabled: false
    targetCPUUtilizationPercentage: 50
</code></pre>

<p>Then in a template file a deployment definition looks like:</p>

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

<p><strong>Problem</strong></p>

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

<p><strong>Attempt 1</strong></p>

<p>I tried to write HPA template in following wrapper:</p>

<pre><code>{{- if .Values.backend.hpa.enabled -}}
{{- if required "Specify requests!" .Values.backend.container.resources.requests.cpu -}}
...
{{- end -}}
{{- end -}}
</code></pre>

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

<p><strong>Attempt 2</strong></p>

<p>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.</p>

<pre><code>backend:
  container:
    resources:
      requests:
        cpu: ""
  hpa:
    enabled: false
    targetCPUUtilizationPercentage: 50
</code></pre>

<p>In Helm 3 you can use JSON Schema Validation, you can read about it <a href="https://helm.sh/docs/topics/charts/#schema-files" rel="nofollow noreferrer">here</a>. You can use the <a href="https://json-schema.org/understanding-json-schema/reference/conditionals.html#applying-subschemas-conditionally" rel="nofollow noreferrer">IF condition there</a>.</p>

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