Confusing Kubernetes semantics in NetworkPolicy yaml spec

9/14/2019

Observe: the field value of ingress under spec.

Case 1: DENY all traffic to an application. Here ingress takes an empty array as its value.

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

Case 2: ALLOW all traffic to an application. Here ingress takes a list item of empty map as its value.

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

I'm just wondering that if I were to read out loud the assignment values of ingress of the above how do I read it?

-- karthiks
kubernetes
kubernetes-networking
kubernetes-networkpolicy
yaml

1 Answer

9/14/2019

YAML has a couple of different ways to write lists (and for that matter most other objects). This might become clearer if we write both using the same list syntax:

# deny-all
ingress: []

# allow-all
ingress: [{}]

Assume that one of these policies is the only one that matches the pod in question. The first policy has no items in the ingress list, the second one. The NetworkPolicySpec API documentation tells us

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.

So in the first case, the policy matches the pod, but there are no ingress rules, and therefore there isn't at least one ingress rule that matches, so traffic is denied.

In the second case there is a single rule, which is an empty NetworkPolicyIngressRule. That has two fields, from and ports, but the documentation for both of those fields says

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

So the empty-object rule matches all sources and all ports; and since there is a matching ingress rule, traffic is allowed.

-- David Maze
Source: StackOverflow