4

We have a default deny-all-egress policy for all pods and we have an egress-internet policy like below

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-external-egress-internet
spec:
  podSelector:
    matchLabels:
      egress: internet
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0

Now, if I try to add multiple labels under spec/podselector/matchlabels everything breaks. Is there a way for this network policy to get implemented on pods with label egress: internet OR foo:bar.

A pod with just foo:bar as label should be allowed but it's not working that way.

mbxzxz
  • 366
  • 2
  • 14

3 Answers3

4

Thats tricky because matchLabels does not take multiple key&value pairs and matchExpressions will be ANDed. There are two possible ways (workarounds):

  1. Create another networkpolicy (along with the existing one) where matchLabels contains foo:bar.

    [or]

  2. add a new label(common) to both the workloads and use that in podSelector

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
confused genius
  • 2,876
  • 2
  • 16
  • 29
  • I figured creating seperate network policy was the way to go.. Adding a new label to `nfs-server-provisioner` deployment was not possible because it's coming from helm. I actually spent couple of days debugging and asked the question [here](https://stackoverflow.com/questions/71630442/add-custom-label-for-helm-templates) but no response. – mbxzxz Mar 29 '22 at 06:09
  • podSelector.matchLabels does take multiple key-values. See my answer below – Banoona Mar 11 '23 at 09:17
4

You can add multiple key-values to podSelector.matchLabels.
See https://github.com/ahmetb/kubernetes-network-policy-recipes/blob/master/10-allowing-traffic-with-multiple-selectors.md

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: redis-allow-services
spec:
  podSelector:
    matchLabels:
      app: bookstore
      role: db
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: bookstore
          role: search
    - podSelector:
        matchLabels:
          app: bookstore
          role: api
    - podSelector:
        matchLabels:
          app: inventory
          role: web
Banoona
  • 452
  • 1
  • 4
  • 8
0

I think you can stack the podSelector like

spec:
  podSelector:
    matchLabels:
      egress: internet
  podSelector:
    matchLabels:
      name: newPod
  policyTypes:
  - Egress
  egress:
  - to:
    - ipBlock:
        cidr: 0.0.0.0/0
jianbo
  • 1