Search code examples
kubernetes-helm

Helm template not rendering correct condition


I have to 2 different values in my helm chart and a combination of them decided whether a file is generated or not. The 2 values are

cluster: test
networkpolicy: true

I need to generate a NetworkPolicy based on 4 different cases.

Case          |  1   |   2   |  3   |  4 
--------------------------------------------
cluster       | test | test  | prod | prod
networkpolicy | true | false | true | false
--------------------------------------------
Outcome       | true | false | true | fail

The above table shows the out come I want. Here is my code in _helpers.tpl file

{{- define "jenkins.networkpolicy" -}}
{{- if eq .Values.cluster "prod" -}}
  {{- if .Values.networkpolicy -}}
    {{- "true" -}}
  {{- else -}}
    {{- fail "Network policy cannot be disabled in prod" -}}
  {{- end -}}
{{- else -}}
  {{- if .Values.networkpolicy -}}
    {{- "true" -}}
  {{- else -}}
    {{- "false" -}}
  {{- end -}}
{{- end -}}

{{- end -}}

and im calling it in my networkpolicy.yaml file like this

{{- if (include "jenkins.networkpolicy" .) }}
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
.
.
{{- end }}

The above code works fine for 3 out of 4 cases. Case #2 does not work. It should not be templating/ignoring the file but it still generates it. Any idea what I am missing here ?

✗ helm template . -f ./values.yaml --set environment.id=test --set cluster=test --set networkpolicy=false | head -10
---
# Source: jkmaster-networkpolicy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-jkmaster-networkpolicy
spec:
  podSelector:
    matchLabels:
      app: test-jkmaster # label of pod to isolate

Solution

  • Your helper functions returns a non empty string with either "true" or "false" value

    Look at the docs when if statement is evaluated as false

    A pipeline is evaluated as false if the value is:

    • a boolean false
    • a numeric zero
    • an empty string
    • a nil (empty or null) an empty collection (map, slice, tuple, dict, array)

    A string "false" is evaluated as boolean true

    Replacing "false" with empty string "" makes your code working as expected

    {{- define "jenkins.networkpolicy" -}}
    {{- if eq .Values.cluster "prod" -}}
      {{- if .Values.networkpolicy -}}
        {{- "true" -}}
      {{- else -}}
        {{- fail "Network policy cannot be disabled in prod" -}}
      {{- end -}}
    {{- else -}}
      {{- if .Values.networkpolicy -}}
        {{- "true" -}}
      {{- else -}}
        {{- "" -}}
      {{- end -}}
    {{- end -}}
    
    {{- end -}}