How to specify not equal selector in kubernetes service definition yaml?

11/18/2019

I am trying to create a service for a set of pods based on certain selectors. For example, the below get pods command retrieves the right pods for my requirement -

kubectl get pods --selector property1=dev,property2!=admin

Below is the extract of the service definition yaml where I am attempting to using the same selectors as above -

apiVersion: v1
kind: Service
metadata:
  name: service1
spec:
  type: NodePort
  ports:
    - name: port1
      port: 30303
      targetPort: 30303
  selector:
    property1: dev
    << property2: ???? >>>

I have tried matchExpressions without realizing that service is not among the resources that support set-based filters. It resulted in the following error -

error: error validating "STDIN": error validating data: ValidationError(Service.spec.selector.matchExpressions): invalid type for io.k8s.api.core.v1.ServiceSpec.selector: got "array", expected "string"; if you choose to ignore these errors, turn validation off with --validate=false

I am running upstream Kubernetes 1.12.5

-- Rakesh N
kubernetes
kubernetes-service

1 Answer

11/19/2019

I've did some test but I am afraid it is not possible. As per docs API supports two types of selectors:

kubeclt allows to use operators like =,== and !=. So it works when you are using $ kubectl get pods --selector property1=dev,property2!=admin.

Configuration which you want to apply would work in set-based option as it supports in, notin and exists:

environment in (production, qa)

tier notin (frontend, backend)

partition

!partition

Unfortunately set-based is supported only by newer resurces as Job, Deployment, Replica Set and Deamon Set but is not supporting services.

More information about this can be found here.

Even if you will set selector in YAML as:

property2: !value 

In service, property2 will be without any value.

Selector: property1=dev,property2=

As additional information , is recognized as AND in services.

As I am not aware how you are managing your cluster, the only thing I can advise is to redefine labels to use only AND as logical operator.

-- PjoterS
Source: StackOverflow