18

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).

Jonas
  • 121,568
  • 97
  • 310
  • 388
Raj N
  • 181
  • 1
  • 1
  • 3
  • There's a thread about this as a feature request here: https://github.com/kubernetes/kubernetes/issues/40651 And one that _may_ apply to you: https://github.com/kubernetes/kubernetes/issues/40651#issuecomment-307164995 NOTE: I know _nothing_ of kubernetes – dreynold Jun 07 '18 at 23:54
  • What do you mean by "*... under spec.*"? – Peter Mortensen Jun 12 '18 at 18:05

2 Answers2

16

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

lifecycle:
  postStart:
    exec:
      command: ["/bin/sh", "-c", "export INDEX=${HOSTNAME##*-}"]
Maciek Sawicki
  • 6,717
  • 9
  • 34
  • 48
  • 1
    Not a correct workaround if the env variable must be set before the entry point is called: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/ *There is no guarantee that the hook will execute before the container ENTRYPOINT* – titou10 Mar 04 '19 at 20:37
  • 1
    how would one use the exported INDEX then in the args? – BenWhite Jul 03 '20 at 13:49
12

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
Abhishek Jaisingh
  • 1,614
  • 1
  • 13
  • 23