Allow traffic where from-pod label equals to-pod label

1/19/2019

I'm trying to setup a network policy in kubernetes where a generic group of pods having the same label value for a key are allowed to have traffic on one port.

Say there are:

Pod A:
 labels:
  meshId="d5ea1b48"

and

Pod B:
 labels:
  meshId="d5ea1b48"

and more pods having the same label meshId=d5ea1b48. The mesh represents a mesh network in which simply all included pods are allowed to have traffic on one port.

My goal interpreted in yaml:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: example
spec:
  podSelector:
    matchLabels:
      meshId: %meshId of from-pod%
  ingress:
  - ports:
    - port 1234
    - protocol: TCP
  - from:
      - podSelector:
          matchLabels:
            meshId: %meshId of to-pod%

So if I am not wrong this config says: I want to deny incoming traffic on port 1234 for those who does not have the same meshId.

Is there a way of creating a kubernetes NetworkPolicy once for all possible meshIds? How would such solution look in yaml?

I don't want to create a new NetworkPolicy for every new meshId because there will be a ton of them and I also think that would harm the performance of the cluster network if there are like 50.000+ NetworkPolicies.

-- Robin Brämer
kubernetes
kubernetes-networkpolicy
networking
policy

1 Answer

1/20/2019

There is no way to generalize label selectors in a manner you have put forth. Note that Network Policies are meant to harden the base so that only bonafide traffic gets in and out.

I would also like to point you to the fact that why would you even end up with 50000's additional policies. This means that you have bad selector strategy for pods. Think of changing this rather than the other way around. You are almost there to get this going!

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1    
metadata:
 name: example
spec:
 podSelector:
  matchLabels:
   meshId: value1
 ingress:
 - ports:
  - port 1234
  - protocol: TCP
 - from:
  - podSelector:
      matchLabels:
        meshId: value1
-- Raunak Jhawar
Source: StackOverflow