Managing Kubernetes Network Policies with Terraform

The cluster was alive, but traffic moved without control. Kubernetes Network Policies change that. They define exactly which Pods can talk to which. Without them, every Pod is a public hallway. With them, you enforce least privilege, layer by layer.

Terraform turns this control into code. Instead of clicking through kubectl commands or YAML files scattered across repos, you declare Kubernetes Network Policies as infrastructure. The same plan that spins up your cluster can set the exact ingress and egress rules it needs.

A Kubernetes Network Policy written in Terraform uses the kubernetes_network_policy resource. You specify namespaces, pod selectors, allowed ports, and protocols. The configuration becomes part of version-controlled infrastructure. Rollbacks are simple. Changes are reviewed in pull requests. Your network security is automated and repeatable.

A simple Terraform snippet for a Network Policy might look like:

resource "kubernetes_network_policy" "deny_all" {
  metadata {
    name      = "deny-all"
    namespace = "default"
  }

  spec {
    pod_selector {}
    policy_types = ["Ingress", "Egress"]
  }
}

This example denies all traffic to all Pods in the default namespace. From there, you add specific rules to allow only the connections you approve. By chaining multiple policies, you shape precise network flows between services.

When managing Kubernetes Network Policies with Terraform, you gain a single source of truth. You remove drift. Any change runs through terraform plan before it goes live. This improves security and auditability. You can reuse modules to enforce policy patterns across namespaces and clusters.

Combine Terraform state management with a GitOps workflow and CI/CD pipelines to make Network Policy enforcement as consistent as your deployments. Whether you run on EKS, GKE, AKS, or bare metal, the approach is the same. The provider API may differ, but the policy model in Kubernetes stays consistent.

Strong isolation, reproducible deployments, and version-controlled security rules are the outcome. Weak or missing policies are the fastest way to expose internal services. Terraform gives you speed without losing discipline.

See Kubernetes Network Policies in action without the setup overhead. Visit hoop.dev and run them live in minutes.