kubernetes statefulsets index/ordinal exposed in template

3/1/2017

Statefulsets direct kubectl/kubernetes to create pods with an index or ordinal following the pod name. If the entity has a name of redis for example and the replication count is 3, then we will get redis-0, redis-1 and redis-2. Is there some way to get access to the index or ordinal? It would be very useful to pass to the startup script for a container. It would be nice if it were available in the downward api. It would be really really nice to use it when trying to line up PVC's to PV's.

Is it possible that there is some secret template variable for this?

Note that I have found a way around it. I am using a script for my command and use the hostname to extract it. But it just seems like a lot of work (and future maintenance).

-- rideswitch
kubectl
kubernetes

1 Answer

1/3/2018

Eventually this should work by adding to the manifest env (I'm told 1.9 onwards but not confirmed yet):

   - name: KAFKA_BROKER_ID
     valueFrom:
       fieldRef:
         fieldPath: metadata.annotations['spec.pod.beta.kubernetes.io/statefulset-index'] 

For now you can 'hack' it like you did using script or using lifecycle events like following:

    lifecycle:
      postStart:
        exec:
          command:
            - "/bin/sh"
            - "-c"
            - "export KAFKA_BROKER_ID=${HOSTNAME##*-}"
-- Mike S.
Source: StackOverflow