<p>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.</p>

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

<pre><code>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
</code></pre>

Stranger B.
<p>You can't do this in the way you're describing.</p>

<p>Probably the best path is to change your Deployment into a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/" rel="noreferrer">StatefulSet</a>.  Each pod launched from a StatefulSet has an <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-identity" rel="noreferrer">identity</a>, and each pod's hostname gets set to the name of the StatefulSet plus an index.  If your <code>launch</code> command looks at <code>hostname</code>, it will see something like <code>name-0</code> and know that it's the first (index 0) pod in the StatefulSet.</p>

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

<pre><code>{{ 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 -}}
</code></pre>

<p>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 <code>helm template</code>.  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.</p>
