CKA Mock EXAM 3 Q16 - network policy issue

Can someone skilful explain to me WHY?:

this is NOT working:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: cyan-np-cka28-trb
namespace: cyan-ns-cka28-trb
spec:
podSelector:
matchLabels:
app: cyan-app-cka28-trb
policyTypes:

  • Ingress
    ingress:
  • from:
    • podSelector:
      matchLabels:
      app: cyan-white-cka28-trb
      ports:
    • protocol: TCP
      port: 80

and when I define additional condition on namespace it is WORKING:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: cyan-np-cka28-trb
namespace: cyan-ns-cka28-trb
spec:
podSelector:
matchLabels:
app: cyan-app-cka28-trb
policyTypes:

  • Ingress
    ingress:
  • from:
    • namespaceSelector:
      matchLabels:
      kubernetes.io/metadata.name: default

      podSelector:
      matchLabels:
      app: cyan-white-cka28-trb
      ports:

    • protocol: TCP
      port: 80

kubernetes documentation do not demand to have at least two conditions defined! why first policy fails to match the traffic?

Hi @AlekseiAnt

It would have been helpful if you had shared the YAML manifests in code blocks; your current content mangles the YAML indentation, making it difficult to understand.

However, I’ll take the chance and try to explain what’s happening :slightly_smiling_face:

Your first policy is set on Pods with labels cyan-app-cka28-trb in cyan-ns-cka28-trb Namespace, to receive traffic ONLY from Pods labeled cyan-white-cka28-trb in the Same namespace on port 80.

Whereas, your second policy, assuming your from block as one element namespaceSelector AND podSelector on Port 80. This policy will allow incoming traffic from cyan-white-cka28-trb from Only the default namespace.

Assuming your second policy looks as follows:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: cyan-np-cka28-trb
  namespace: cyan-ns-cka28-trb
spec:
  podSelector:
    matchLabels:
      app: cyan-app-cka28-trb
  policyTypes:
    - Ingress
  ingress:
    - from:
        - namespaceSelector:
            matchLabels:
              kubernetes.io/metadata.name: default
          podSelector:
            matchLabels:
              app: cyan-white-cka28-trb
      ports:
        - protocol: TCP
          port: 80

Edit: Your second manifest aligns with the Expectation: This app should only be accessible from the cyan-white-cka28-trb pod.

aaahh. Thanks for clarification. So wwhen I do not mention any source namespace in ingress rules - k8s asumes, that it matches traffic only in the namespace of the policy.

Thanks for clarifications!

Other than that. I would recommend this part of the official docs.
It’s subtle, but very crucial.