Automating Kubernetes Network Policies with Shell Scripting
The pod was running, but traffic flowed where it shouldn’t. You needed control, not chaos. Kubernetes Network Policies give you that control. Combine them with shell scripting and you can define, deploy, and audit network rules fast—without touching your mouse.
A Kubernetes Network Policy is a resource that sets allowed ingress and egress rules for pods. By default, pods can talk to everything in the cluster. Once you apply a Network Policy, unlisted traffic is blocked. This is critical for isolating services, meeting compliance, and reducing the blast radius of a breach.
You can create and apply a Network Policy using YAML, but doing it by hand for every namespace is slow. Shell scripting lets you automate it. For example:
#!/bin/bash
NAMESPACE=$1
cat <<EOF | kubectl apply -n $NAMESPACE -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
EOF
This script takes a namespace and blocks all ingress and egress traffic. You can extend it to allow only specific ports or CIDRs. By chaining shell scripts, you can roll out standard policies to dozens of namespaces in seconds.
To verify Network Policies, use shell scripts with kubectl get and kubectl describe. You can pipe results into grep or jq to check that the rules match your security requirements. Automating these checks ensures nothing drifts from the intended state.
Common use cases include:
- Deny all by default, then explicitly allow needed traffic.
- Limit pod communication to the same namespace.
- Restrict database pods so they only accept connections from app pods.
- Enforce egress IP allowlists.
Cluster security depends on accuracy and speed. Writing the right Network Policy is only the first step. Shell scripting ensures it’s applied consistently, reviewed regularly, and updated without delay.
See this in action with live Kubernetes network policy demos at hoop.dev and get it running in minutes.