3

I have a statefulset and I need to know what is the current replica count from inside the pod. To do so, I tried:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: sample-mariadb
  namespace: demo
spec:
  replicas: 3
  template:
    spec:
      containers:
      - env:
        - name: REPLICAS
          valueFrom:
            fieldRef:
              apiVersion: v1
              fieldPath: spec.replicas

and got this error:

Warning FailedCreate 4m15s (x17 over 9m43s) statefulset-controller create Pod sample-mariadb-0 in StatefulSet sample-mariadb failed error: Pod "sample-mariadb-0" is invalid: spec.containers[1].env[3].valueFrom.fieldRef.fieldPath: Invalid value: "spec.replicas": error converting fieldPath: field label not supported: spec.replicas

How can I get current replica count from inside the pod?

Alif Biswas
  • 348
  • 1
  • 7
  • 1
    That field is not available in the downward API https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/ – Jonas Jul 13 '21 at 08:00

2 Answers2

3

You can only send the fields that are part of Pod specification. The spec.replicas field is part of StatefulSet specification not the underlying pod's. The template part of a StatefulSet is the pod specification. Hence, you are getting this error.

Emruz Hossain
  • 4,764
  • 18
  • 26
0

I have looked for a solution, and the alternatives I could find is:

  1. Setting the same environment variable
- name: REPLICAS
  value: "3"
  1. Or you can update the value of the replicas as template variable. Example updating it as template.yaml:
replicas: ${num_replicas}
spec:
 - name: REPLICAS
   value: ${num_replicas}
export num_replicas=3
cat template.yaml | envsubst > dapi-stateful.yaml
Antoine
  • 1,393
  • 4
  • 20
  • 26