Is it possible to assign low reusable integer ids to Kubernetes pods without using StatefulSet?

Viewed 412

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.

My goal is to use this number as the worker in a twitter-snowflake-like algorithm.

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.

4 Answers

There is no built-in way to do this.

The most straightforward workaround would be a initcontainer. 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):

  1. Connect to the Kubernetes API and select the ownerReference of the current pod

  2. Count the number of pods matching the ownerReference of the current pod, e.g.,

    kubectl get pods -o jsonpath='{range .items[?(.metadata.ownerReferences.uid=)]}{.metadata.name}{end}'

  3. Set the label for your id on the current pod to number of previously selected pods + 1

Having analysed the comments it looks like it can be achieved using StatefulSet, to read more one can visit the official documentation.

In my opinion, Statefulset is the best way to achieve such consistency because of two major reasons,

  • Statefulset is meant to overcome those deployment object's limitations.
  • That's the only built-in way in Kubernetes so far.

However, since I do not have the big picture of what you are working on, I might be thinking wrong in your context. Still, I would like to suggest a simple workaround which can give you a consistent pod name (Not with low id).

You first need to generate an UUID with uuid generator. For example Click here

Then you can add/replace your generated UUID in the suffix of your pod name and just apply. That will give you a consistent pod name.

As far as I know, this cannot be achieved using inbuilt functions as each of the UUID which is getting assigned is unique and there is no way to reuse the previous ID.

You can access pod's uid by kubectl get pods/$POD_NAME -o yaml, it is under metadata.uid. where the commit is made.

Related