1. Answers
  2. Configuring Kubernetes Network Policies

How do I configure a Kubernetes networking.k8s.io networkpolicy with Pulumi?

In this guide, we will configure a Kubernetes NetworkPolicy using Pulumi. Network policies are used to control the communication between pods within a Kubernetes cluster. We will create a NetworkPolicy that allows ingress traffic to specific pods based on labels and restricts all other traffic.

Key Points

  • Define a NetworkPolicy to control pod traffic.
  • Use podSelector to specify the pods to which the policy applies.
  • Use ingress and egress rules to allow or deny traffic.

Pulumi Program

import * as pulumi from "@pulumi/pulumi";
import * as k8s from "@pulumi/kubernetes";

// Create a new Kubernetes namespace
const namespace = new k8s.core.v1.Namespace("example-namespace", {
    metadata: { name: "example-namespace" },
});

// Define a NetworkPolicy
const networkPolicy = new k8s.networking.v1.NetworkPolicy("example-network-policy", {
    metadata: {
        namespace: namespace.metadata.name,
        name: "example-network-policy",
    },
    spec: {
        podSelector: {
            matchLabels: {
                role: "db",
            },
        },
        policyTypes: ["Ingress"],
        ingress: [{
            from: [{
                podSelector: {
                    matchLabels: {
                        role: "frontend",
                    },
                },
            }],
            ports: [{
                protocol: "TCP",
                port: 3306,
            }],
        }],
    },
});

export const networkPolicyName = networkPolicy.metadata.name;
export const namespaceName = namespace.metadata.name;

Explanation

  1. Namespace Creation: We start by creating a new Kubernetes namespace called example-namespace.
  2. NetworkPolicy Definition: We define a NetworkPolicy named example-network-policy within the example-namespace.
    • Pod Selector: The policy applies to pods with the label role: db.
    • Policy Types: The policy type is set to Ingress to control incoming traffic.
    • Ingress Rules: The ingress rule allows traffic from pods with the label role: frontend on TCP port 3306.

Summary

In this guide, we configured a Kubernetes NetworkPolicy using Pulumi. The NetworkPolicy allows ingress traffic to pods labeled role: db from pods labeled role: frontend on TCP port 3306, while restricting all other traffic. This ensures controlled and secure communication between pods within the Kubernetes cluster.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up