Is it possible to pass different args to pods based on their ordinal index in StatefulSets? Didn't find the answer on the StatefulSets documentation. Thanks!
Recommended way, see https://kubernetes.io/docs/tasks/run-application/run-replicated-stateful-application/#statefulset
# Generate server-id from pod ordinal index.
[[ `hostname` =~ -([0-9]+)$ ]] || exit 1
ordinal=${BASH_REMATCH[1]}
# ${ordinal} now holds the replica number
server-id=$((100 + $ordinal))
# Copy appropriate conf.d files from config-map to emptyDir.
if [[ $ordinal -eq 0 ]]; then
# do something
else
# do something else
fi
I don't know of a non-hacky way to do it, but I know a hack that works. First, each pod in a StatefulSet gets a unique predictable name. It can discover that name via the downward API or just by calling hostname
. So I have shell script as then entrypoint to my container and that script gets it's pod/hostname. From there it calls the "real" executable using command line args appropriate for the specific host.
For example, one of my scripts expects the pod name to be mapped into the environment as POD_NAME
via downward api. It then does something like:
#!/bin/bash
pet_number=${POD_NAME##*-}
if [ pet_number == 0 ]
then
# stuff here
fi
# etc.
I found one less hacky
way to pass in ordinal index into container using the lifecycle hooks
containers:
- name: cp-kafka
imagePullPolicy: Always
image: confluentinc/cp-kafka:4.0.0
resources:
requests:
memory: "2Gi"
cpu: 0.5
ports:
- containerPort: 9093
name: server
protocol: TCP
lifecycle:
postStart:
exec:
command: ["/bin/sh", "-c", "export KAFKA_BROKER_ID=${HOSTNAME##*-}"]
env:
- name: KAFKA_ZOOKEEPER_CONNECT
value: zk-cs.default.svc.cluster.local:2181
- name: KAFKA_ADVERTISED_LISTENERS
value: PLAINTEXT://localhost:9093
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With