Whats the difference between the following two network policies? They only differ by spec.ingress.from.podSelector
.
First network policy:
controlplane ~ ➜ cat netpol1.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: ingress-to-nptest-1
namespace: default
spec:
podSelector:
matchLabels:
run: np-test-1
policyTypes:
- Ingress
ingress:
- ports:
- protocol: TCP
port: 80
Second network policy:
controlplane ~ ➜ cat netpol2.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: ingress-to-nptest-2
namespace: default
spec:
podSelector:
matchLabels:
run: np-test-1
policyTypes:
- Ingress
ingress:
- from:
- podSelector: {}
ports:
- protocol: TCP
port: 80
When I run kubectl describe netpol
it suggests a different behaviour, but I can't figure out what the difference is.
In the first case it allows traffic "From: (traffic not restricted by source)":
controlplane ~ ➜ k describe netpol ingress-to-nptest-1
Name: ingress-to-nptest-1
Namespace: default
Created on: 2023-03-16 07:53:04 -0400 EDT
Labels: <none>
Annotations: <none>
Spec:
PodSelector: run=np-test-1
Allowing ingress traffic:
To Port: 80/TCP
From: <any> (traffic not restricted by source)
Not affecting egress traffic
Policy Types: Ingress
In the second case it allows traffic from pods that match "PodSelector:none":
controlplane ~ ➜ k describe netpol ingress-to-nptest-2
Name: ingress-to-nptest-2
Namespace: default
Created on: 2023-03-16 07:54:09 -0400 EDT
Labels: <none>
Annotations: <none>
Spec:
PodSelector: run=np-test-1
Allowing ingress traffic:
To Port: 80/TCP
From:
PodSelector: <none>
Not affecting egress traffic
Policy Types: Ingress
The Kubernetes API reference suggests that this is equivalent to the first network policy:
podSelector: This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods.
Is it correct that in both cases traffic from every source is allowed? Are both network policies equivalent?
After some more research I think I found the answer myself. The Kubernetes API reference states that:
spec.ingress.from: If this field is empty or missing, this rule matches all sources (traffic not restricted by source).
It also states the following on another page:
spec.ingress.from.podSelector: if present but empty, it selects all pods.
spec.ingress.from.namespaceSelector: if present but empty, it selects all namespaces.
As we can also specify spec.ingress.from.namespaceSelector
, it follows that it would be possible to set spec.ingress.from.podSelector
to {}
, but spec.ingress.from.namespaceSelector
to some namespace. This would select all pods from some namespace. If, on the other hand, we would leave spec.ingress.from
empty, we would select all pods from all namespaces.
It follows that both network policies are the same, but only as long as spec.ingress.from.namespaceSelector
is empty as well.