Review NetworkPolicy pod selection

Verify that the policy selects the intended namespace and pods.

Description

pod_selector selects Pods only in the NetworkPolicy’s namespace. An empty selector matches all of them. A policy created for future Pods can have no current matches.

Potential impact

A wrong label can leave intended Pods unrestricted by this policy or interrupt legitimate connections to other Pods.

Remediation

Compare match_labels and match_expressions with the actual labels. Check network-plugin support, then set policy_types and the required ingress or egress rules. Test required and blocked connections with the allow rules of all applicable policies in effect.

Examples

These excerpts compare selectors only. Supply the Pod spec and the policy types and traffic rules needed for deployment.

Before

hcl
resource "kubernetes_network_policy" "example" {
  metadata {
    name      = "terraform-example-network-policy"
    namespace = "default"
  }

  spec {
    pod_selector {
      match_labels = {
        app = "ngnix"
      }
    }
  }
}

After

hcl
resource "kubernetes_pod" "example" {
  metadata {
    name = "terraform-example"

    labels = {
      app = "ngnix2"
    }
  }
}

resource "kubernetes_network_policy" "example" {
  metadata {
    name      = "terraform-example-network-policy"
    namespace = "default"
  }

  spec {
    pod_selector {
      match_labels = {
        app = "ngnix2"
      }
    }
  }
}

Explanation:

  • Before: The selector looks for app = "ngnix" in default. Check whether any such Pods exist.
  • After: The Pod and selector both use app = "ngnix2". The Pod must also be created in the policy’s default namespace to match.

References