Khumar
Khumar

Reputation: 336

Service creation loop using range function in Helm

I am trying to create k8s service of type load balancer using range loop in helm.I need to create k8s service pointing to dedicated POD.I have deployed 3 pods, up and running.I am trying to create 3 services pointing to 3 different pods.

{{- $replicas := .Values.replicaCount | int -}}
{{- $namespace := .Release.Namespace  }}
{{- range $i,$e := until $replicas }}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-{{ $i }}
  name: service-{{ $i }}
  namespace: {{ $namespace  }}
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: {{  . | printf ".Value.ports.port_%d" | int }}
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-{{ $i }}
  type: LoadBalancer
{{- end }}

my values.yaml

ports:
  port_1: 30001
  port_2: 30002
  port_3: 30003
replicaCount: 3

dry-run is giving below put:

# Source: t1/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-0
  name: service-0
  namespace: xyz
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: 0
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-0
  type: LoadBalancer
---
# Source: t1/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-1
  name: service-1
  namespace: xyz
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: 0
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-1
  type: LoadBalancer
---
# Source: t1/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-2
  name: service-2
  namespace: xyz
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: 0
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-2
  type: LoadBalancer

I need port number pointing to correct port in according to values.yaml file.For service-0,service-1,service-2 I need 30001,30002,30002 ports assigned.Please suggest.Thank you !!

Upvotes: 0

Views: 1977

Answers (1)

David Maze
David Maze

Reputation: 159530

To do the dynamic lookup in the port list, you need to use the index function. This is part of the standard Go text/template language and not a Helm extension:

port: {{ index .Values.ports (add $i 1 | printf "port_%d") }}

This could be slightly simpler if you change the list of ports to be a list and not a map:

# values.yaml
ports:
  - 30001
  - 30002
  - 30003
replicaCount: 3
port: {{ index .Values.ports $i }}

If you didn't require access to specific pods from outside the cluster, a StatefulSet creates a cluster-internal DNS name for each pod on its own, and you could avoid this loop entirely.

Upvotes: 2

Related Questions