Home > Net >  Kubernetes Helm Chart Template if-condition
Kubernetes Helm Chart Template if-condition

Time:07-29

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!

EDIT:

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

Now it works with if statement, but not with with statement.

CodePudding user response:

Try if/else block:

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

Loop thru the ports:

 ports:
 {{- if .Values.ports }}
 {{- range $content := .Values.ports }}
  - containerPort: {{ $content.containerPort | default 8080 }}
    name: {{ $content.name | default "8080tcp02" }}
    protocol: {{ $content.protocol | default "TCP" }}
 {{- end }}
 {{- else }}
  - containerPort: 8080
    name: "8080tcp02"
    protocol: "TCP"
 {{- end }}
  • Related