Kubernetes Helm Chart Template if-condition

In my helm template I want to have the following block:

ports:
  - containerPort: {{ .Values.ports.containerPort | default 8080}}
    name: {{ .Values.ports.name | default "8080tcp02" | quote}}
    protocol: {{ .Values.ports.protocol | default "TCP" | quote}}
          {{- end }}

If in values.yaml file block ports exist, then take values for containerPort, name andprotocol from there. Otherwise, if block ports is absent in values.yaml, then take default values. Now I’m getting nil pointer evaluating interface {}.containerPort, if block ports is absent in values.yaml.

I also tried to do so:

{{- with .Values.ports }}
ports:
  - containerPort: {{ .containerPort | default 8080}}
    name: {{ .name | default "8080tcp02"}}
    protocol: {{ .protocol | default "TCP"}}
{{- end }}

But then If block ports is absent in values.yaml It will absent in result as well. How can I achieve this?

Thanks in advance!

>Solution :

Try if/else block:

ports:
 {{ if .Values.ports }}
  - containerPort: {{ .Values.ports.containerPort | default 8080 }}
    name: {{ .Values.ports.containerPort | default "8080tcp02" | quote }}
    protocol: {{ .Values.ports.protocol | default "TCP" | quote }}
 {{ else }}
  - containerPort: 8080
    name: "8080tcp02"
    protocol: "TCP"
 {{ end }}

Leave a Reply