Kubernetes CKA sample exam question 84 with answer

Question
Deploy a network policy called allow-only-namespace in webapp namespace. Make sure it allows ALL traffic ONLY from dev namespace.
Policy should NOT allow communication between pods in same namespace.
Traffic ONLY from dev namespace is allowed on ALL ports
Edit necessary dependent resources.

Answer
You need to label the namespace with name=dev.

kubectl edit ns dev
Add to metadata.labels:
name: dev
By default, namespaces are not labelled with their names.
Task is to allow traffic only from dev namespace, so we have to use namespaceSelector block.
Since traffic is allowed on ALL ports, we don’t need to specify port block.
An empty podSelector selects all pods in the namespace:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-only-namespace
  namespace: webapp
spec:
  podSelector: {}
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          name: dev
Apply and verify:
kubectl apply -f  np.yaml
kubectl -n webapp describe netpol allow-only-namespace