Typo caused difference in NetworkPolicy yaml file

Check following two networkpolicy
yaml file, np1.yaml
and np2.yaml
:
# np1.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: np
namespace: space1
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: space2
ports:
- port: 53
protocol: UDP
- port: 53
protocol: TCP
# np2.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: np
namespace: space1
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: space2
- ports:
- port: 53
protocol: TCP
- port: 53
protocol: UDP
Looks similar, but a tiny typo here caused some different results. If we check carefully will find that in the np2.yaml
, it gives two separated restrictions on egress:
allows traffic to all pods in the namespace
space2
without specifying any ports.allows traffic to any destination on ports 53 (TCP and UDP) -- DNS traffic.
The "-
" indicates separate rules in YAML. In the np1.yaml
, the two rules are logically OR
: Traffic matches if it satisfies either the first rule (namespace match) or the second rule (ports match).
While in the np2.yaml
, the to
and ports
are part of a single rule, which requires traffic to satisfy both constraints (namespace match and port match), literally it's an AND
relationship.
In Summary, in np1.yaml
it has two rules: egress.to
and egress.ports
; in np2.yaml
there only one rule: egress.to
, but under to
field, there is a egress.to
.ports
field.
Subscribe to my newsletter
Read articles from Cheedge Lee directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Cheedge Lee
Cheedge Lee
Some blogs are from my previous blogs, even though I have renovated and checked before migration, but there may be still some parts out of date. (https://blog.sina.com.cn/u/1784323047 or https://blog.csdn.net/li_6698230?type=blog, if they're still accessible.)