Use namespace rules in policy

Big picture

Use Calico network policies to reference pods in other namespaces.

Value

Kubernetes namespaces let you group/separate resources to meet a variety of use cases. For example, you can use namespaces to separate development, production, and QA environments, or allow different teams to use the same cluster. You can use namespace selectors in Calico network policies to allow or deny traffic to/from pods in specific namespaces.

Features

This how-to guide uses the following Calico features:

NetworkPolicy with namespaceSelector

How to

Control traffic to/from endpoints in a namespace

In the following example, ingress traffic is allowed to endpoints in the namespace: production with label color: red, and only from a pod in the same namespace with color: blue, on port 6379.

  1. apiVersion: projectcalico.org/v3
  2. kind: NetworkPolicy
  3. metadata:
  4. name: allow-tcp-6379
  5. namespace: production
  6. spec:
  7. selector: color == 'red'
  8. ingress:
  9. - action: Allow
  10. protocol: TCP
  11. source:
  12. selector: color == 'blue'
  13. destination:
  14. ports:
  15. - 6379

To allow ingress traffic from endpoints in other namespaces, use a namespaceSelector in the policy rule. A namespaceSelector matches one or more namespaces based on the labels that are applied on the namespace. In the following example, ingress traffic is also allowed from endpoints with color: blue in namespaces with shape: circle.

  1. apiVersion: projectcalico.org/v3
  2. kind: NetworkPolicy
  3. metadata:
  4. name: allow-tcp-6379
  5. namespace: production
  6. spec:
  7. selector: color == 'red'
  8. ingress:
  9. - action: Allow
  10. protocol: TCP
  11. source:
  12. selector: color == 'blue'
  13. namespaceSelector: shape == 'circle'
  14. destination:
  15. ports:
  16. - 6379

Use Kubernetes RBAC to control namespace label assignment

Network policies can be applied to endpoints using selectors that match labels on the endpoint, the endpoint’s namespace, or the endpoint’s service account. By applying selectors based on the endpoint’s namespace, you can use Kubernetes RBAC to control which users can assign labels to namespaces. This allows you to separate groups who can deploy pods from those who can assign labels to namespaces.

In the following example, users in the development environment can communicate only with pods that have a namespace labeled, environment == "development".

  1. apiVersion: projectcalico.org/v3
  2. kind: GlobalNetworkPolicy
  3. metadata:
  4. name: restrict-development-access
  5. spec:
  6. namespaceSelector: 'environment == "development"'
  7. ingress:
  8. - action: Allow
  9. source:
  10. namespaceSelector: 'environment == "development"'
  11. egress:
  12. - action: Allow
  13. destination:
  14. namespaceSelector: 'environment == "development"'

Additional resources