<p>I know each pod gets a (unique) UUID, but is it possible to also give it, automatically, a low id number, that can be reusable as long as no two pods use them at the same time? So if pod 4 dies, the next time a pod is started gets 4. There can be gaps from time to time.</p>
<p>My goal is to use this number as the worker in a twitter-snowflake-like algorithm.</p>
<p>I'd like to achieve that without using StatefulSet, since it comes with a bunch of limitations and complexity that I'd rather not add to a big deployment.</p>

<p>There is no built-in way to do this.</p>
<p>The most straightforward workaround would be a <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" rel="noreferrer">initcontainer</a>. On the pod start, the initcontainer runs before the start of the original containers, determines this id, and sets it to the pod. This initcontainer would run the following steps (in bash or the language of your choice):</p>
<ol>
<li><p><a href="https://kubernetes.io/docs/tasks/run-application/access-api-from-pod/" rel="noreferrer">Connect to the Kubernetes API</a> and select the <code>ownerReference</code> of the current pod</p>
</li>
<li><p>Count the number of pods matching the <code>ownerReference</code> of the current pod, e.g.,</p>
<p>kubectl get pods -o jsonpath='{range .items[?(.metadata.ownerReferences.uid=)]}{.metadata.name}{end}'</p>
</li>
<li><p><a href="https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#label" rel="noreferrer">Set the label</a> for your id on the current pod to <code>number of previously selected pods + 1</code></p>
</li>
</ol>
