How to add multiple ports in Helm service template?

4.5k views Asked by At

How can I make below snippet to support multiple ports? The template should print multiple individual port sections.

The template I currently have is:

apiVersion: v1
kind: Service
metadata:
  name: {{ include "myapp.fullname" . }}
  labels:
    {{- include "myapp.labels" . | nindent 4 }}
spec:
  type: {{ .Values.service.type }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: {{ .Values.service.targetPort }}
      protocol: UDP
      name: port1
  selector:
    {{- include "myapp.selectorLabels" . | nindent 4 }}

The expected output in the service spec should look like:

ports:
-  name: ex1
   port: 100
   protocol: TCP
   targetPort: 80
-  name: ex2
   port: 101
   protocol: TCP
   targetPort: 8080
-  name: ex3
   port: 103
   protocol: TCP
   targetPort: 5555
1

There are 1 answers

0
Wray27 On

Helm has flow control. The range keyword provides a "for each"-style loop.

apiVersion: v1
kind: Service
metadata:
  name: {{ include "myapp.fullname" . }}
  labels:
    {{- include "myapp.labels" . | nindent 4 }}
spec:
  type: {{ .Values.service.type }}
  ports:
    {{- range .Values.ports }}
    - port: {{ .port }}
      targetPort: {{ .targetPort }}
      protocol: {{ .protocol }}
      name: {{ .name }}
    {{- end }}
  selector:
    {{- include "myapp.selectorLabels" . | nindent 4 }}