Kubernetes : How to limit traffic to only two types of pods labeled 'A' and 'B' using a NetworkPolicy

2/15/2021

I have two types of pods A and B

Pod Type A

apiVersion: v1
kind: Pod
metadata:
  name: A
  labels:
    environment: production
spec:
...

Pod Type B

apiVersion: v1
kind: Pod
metadata:
  name: B
  labels:
    environment: production
spec:
...

And a NetworkPolicy (still don't know the proper way to use podselection)

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny-all
spec:
  podSelector: {"A", "B"}
  policyTypes:
  - Ingress
  - Egress

Question : How do I define a single NetworkPolicy to limit traffic to only A & B pods (both ingress & egress) using a 'NetworkPolicy' in Kubernetes

References used : https://kubernetes.io/docs/concepts/services-networking/network-policies/

-- JumbledCode
kubernetes
kubernetes-networkpolicy
kubernetes-pod

1 Answer

2/16/2021

pod selectors do not have or condition on labels. The solution will be to create a common label in both pods - a and b and use pod selector on that common label.

In your question, you should use environment: production as a label to select correct pods. Pod selector works on labels and not the name of the pod.

-- prabodhprakash
Source: StackOverflow