Using affinity to keep two kubernetes pods apart with unknown label values

457 views Asked by At

Imagine I have some pods I need on separate k8s nodes, I could use something like this if I know both pods have a label my/label=somevalue

affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 2
        podAffinityTerm:
          labelSelector:
            matchLabels:
              my/label: somevalue

I have some pods I need separated, according to multiple values of the same label, which doesn't known up-front (it's a shared key which is calculated by an operator).

Is there a way of specifying a podAffinityTerm which applies to any pods sharing the same value of my.label, regardless of the actual value?

E.g.

Pod a has my/label=x
Pod b has my/label=x
Pod c has my/label=y
Pod d has my/label=y

I'd need pods a & b separated from each other, and pods c & d separated form each other, but e.g. a and d can coexist on the same node

1

There are 1 answers

1
Mikołaj Głodziak On BEST ANSWER

As far as I know, there is no built-in way to specify affinity without knowing label values. At the stage of creating a pod you need to provide both key and value. In order for affinity to work properly, you need to know this value at the time of creation and put it in the appropriate yaml file.

Theoretically, you could create a custom script, e.g. in bash, which will take your value for you

its a sharding key which is calculated by an operator

and then replace it in yaml files. This way it will be set correctly when creating pod.

Additionally, you can also have a look at Well-Known Labels, Annotations and Taints.

Depending on your exact situation, you can try to solve the problem with them. See also this page. There you will find everything about assigning pod to nodes.