Is there a way to get ordinal index of a pod with in kubernetes statefulset configuration file?

11,498

Solution 1

You could essentially get the unique name of your pod in statefulset as an environment variable, you have to extract the ordinal index from it though

In container's spec:

env:
  - name: cluster.name
    value: k8s-logs
  - name: node.name
    valueFrom:
      fieldRef:
        fieldPath: metadata.name

Solution 2

Right now the only option is to extract index from host name

lifecycle:
  postStart:
    exec:
      command: ["/bin/sh", "-c", "export INDEX=${HOSTNAME##*-}"]
Share:
11,498
Admin
Author by

Admin

Updated on June 07, 2022

Comments

  • Admin
    Admin almost 2 years

    We are on Kubernetes 1.9.0 and wonder if there is way to access an "ordinal index" of a pod with in its statefulset configuration file. We like to dynamically assign a value (that's derived from the ordinal index) to the pod's label and later use it for setting pod affinity (or antiaffinity) under spec.

    Alternatively, is the pod's instance name available with in statefulset configfile? If so, we can hopefully extract ordinal index from it and dynamically assign to a label (for later use for affinity).

  • titou10
    titou10 about 5 years
    Not a correct workaround if the env variable must be set before the entry point is called: kubernetes.io/docs/concepts/containers/… There is no guarantee that the hook will execute before the container ENTRYPOINT
  • BenWhite
    BenWhite almost 4 years
    how would one use the exported INDEX then in the args?
  • lucasvc
    lucasvc about 2 years
    Question asked for ordinal, not whole name.