混淆 NetworkPolicy yaml 规范中的 Kubernetes 语义

Confusing Kubernetes semantics in NetworkPolicy yaml spec

观察:spec.

ingress的字段值

案例 1:拒绝应用程序的所有流量。这里ingress取一个空数组作为它的值。

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: web-deny-all
spec:
  podSelector:
    matchLabels:
      app: web
  ingress: [] # <-- This DENIES ALL traffic

案例 2:允许所有流量到应用程序。这里的 ingress 取一个空 map 的列表项作为它的值。

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: web-allow-all
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: web
  ingress:
  - {}  # <-- This ALLOWS ALL traffic

我只是想知道,如果我要大声朗读上面ingress的分配值,我该如何阅读呢?

YAML 有几种不同的方式来编写列表(以及大多数其他对象)。如果我们使用相同的列表语法编写两者,这可能会变得更清楚:

# deny-all
ingress: []

# allow-all
ingress: [{}]

假设这些策略之一是唯一与所讨论的 pod 匹配的策略。第一个策略在 ingress 列表中没有项目,第二个。 The NetworkPolicySpec API documentation告诉我们

Traffic is allowed to a pod [...] if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod.

因此在第一种情况下,策略与 pod 匹配,但没有入口规则,因此没有至少一个匹配的入口规则,因此流量被拒绝。

在第二种情况下,只有一个规则,它是一个空 NetworkPolicyIngressRule。它有两个字段,fromports,但是这两个字段的文档都说

If this field is empty or missing, this rule matches all [sources or ports]

因此空对象规则匹配所有来源和所有端口;并且由于存在匹配的入口规则,因此允许流量。