How to get a pod index inside a helm chart

7/13/2019

I'm deploying a Kubernetes stateful set and I would like to get the pod index inside the helm chart so I can configure each pod with this pod index.

For example in the following template I'm using the variable {{ .Values.podIndex }} to retrieve the pod index in order to use it to configure my app.

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: {{ .Values.name }}
spec:
  replicas: {{ .Values.replicaCount }}
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 50%
  template:
    metadata:
      labels:
        app: {{ .Values.name }}
    spec:
      containers:
        - image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
          imagePullPolicy: Always
          name: {{ .Values.name }}
          command: ["launch"],
          args: ["-l","{{ .Values.podIndex }}"]
          ports:
            - containerPort: 4000
      imagePullSecrets:
        - name: gitlab-registry
-- Stranger B.
kubernetes
kubernetes-helm

1 Answer

7/14/2019

You can't do this in the way you're describing.

Probably the best path is to change your Deployment into a StatefulSet. Each pod launched from a StatefulSet has an identity, and each pod's hostname gets set to the name of the StatefulSet plus an index. If your launch command looks at hostname, it will see something like name-0 and know that it's the first (index 0) pod in the StatefulSet.

A second path would be to create n single-replica Deployments using Go templating. This wouldn't be my preferred path, but you can

{{ range $podIndex := until .Values.replicaCount -}}
---
apiVersion: v1
kind: Deployment
metadata:
  name: {{ .Values.name }}-{{ $podIndex }}
spec:
  replicas: 1
  template:
    spec:
      containers:
        - name: {{ .Values.name }}
          command: ["launch"]
          args: ["-l", "{{ $podIndex }}"]
{{ end -}}

The actual flow here is that Helm reads in all of the template files and produces a block of YAML files, then submits these to the Kubernetes API server (with no templating directives at all), and the Kubernetes machinery acts on it. You can see what's being submitted by running helm template. By the time a Deployment is creating a Pod, all of the template directives have been stripped out; you can't make fields in the pod spec dependent on things like which replica it is or which node it got scheduled on.

-- David Maze
Source: StackOverflow