CodingDevOpsAdvanced45 minSaves 1 hour

Kubernetes NetworkPolicy for Zero-Trust with Observability

For platform and security engineers, generate Kubernetes NetworkPolicies to enforce zero-trust segmentation across multi-namespace clusters without disrupting critical observability tools.

This prompt guides platform and security engineers in generating Kubernetes NetworkPolicy manifests. It ensures a zero-trust security posture across multiple namespaces while explicitly preserving crucial observability traffic. The output includes K8s YAML, Helm/Kustomize guidance, and a deployment strategy.

READY-TO-USE PROMPT

Copy Prompt

prompt.txt
Role: Kubernetes Security Architect

Context:
*   You are securing a Kubernetes cluster running multiple applications across various namespaces.
*   The goal is to implement a strict zero-trust network policy model where all traffic is denied by default, and only explicitly permitted traffic is allowed.
*   Crucially, existing observability tools (e.g., Prometheus, Grafana, ELK stack, Jaeger) residing in `{{observability_namespace}}` must continue to function correctly, allowing monitoring and logging traffic from all application namespaces.
*   The cluster uses label-based selectors for services and pods.
*   You need to generate policies for an application named `{{application_name}}` running in one or more namespaces from `{{namespace_list}}`.

Task:
*   Generate a set of Kubernetes NetworkPolicy manifests (YAML) that enforce zero-trust principles for the specified application(s) and namespaces.
*   Provide clear, concise notes on how these policies can be integrated into a GitOps workflow using either Helm or Kustomize.
*   Outline a phased rollout and rollback strategy for these NetworkPolicies.

Constraints:
*   **Zero-Trust Default Deny:** Each NetworkPolicy must implicitly or explicitly deny all ingress and egress traffic by default, only allowing specified exceptions.
*   **Observability Exemption:** Explicitly permit necessary ingress/egress traffic between application pods in `{{namespace_list}}` and services within the `{{observability_namespace}}`. This includes metrics scraping, log forwarding, and tracing.
*   **Application-Specific Rules:** Define specific ingress/egress rules for `{{application_name}}` based on common patterns (e.g., internal service communication, database access, external API calls if specified). Assume internal services communicate via `Service` resources within the cluster.
*   **Namespace Isolation:** Policies should prevent unauthorized cross-namespace communication, allowing only explicitly defined interactions.
*   **Idempotent:** Generated policies should be idempotent, suitable for GitOps.
*   **Human-Readable:** Policies should be well-commented and easy for a platform engineer to understand and modify.
*   **No External IP Dependencies:** Avoid hardcoding external IP addresses unless absolutely necessary and explicitly requested. Focus on Kubernetes-native selectors.

Output:
1.  A YAML block containing all generated Kubernetes `NetworkPolicy` manifests. Each manifest should include `apiVersion`, `kind`, `metadata` (name, namespace, labels), and `spec` (podSelector, policyTypes, ingress, egress).
2.  A Markdown section titled "GitOps Integration Notes (Helm/Kustomize)" detailing how to manage these policies.
3.  A Markdown section titled "Rollout and Rollback Strategy" outlining a safe deployment plan.

Estimated results

DifficultyAdvanced
Setup time45 min
Time saved1 hour
Best modelsChatGPT, Gemini, Claude
Best audienceSoftware, Cybersecurity

Editor's note

Why this prompt matters

Securing Kubernetes clusters often involves balancing strict access control with operational visibility. Platform and security engineers frequently face the challenge of segmenting network traffic to enforce zero-trust principles without inadvertently breaking critical monitoring and logging pipelines. A common scenario involves an application deployed across multiple namespaces, where each instance needs to communicate internally, access shared services like databases, and crucially, report metrics and logs to a centralized observability stack.

This workflow addresses that precise dilemma. It's designed for teams implementing GitOps practices who need to define granular NetworkPolicies. By generating policies that default to deny all traffic while explicitly permitting necessary communication paths, including those for observability, engineers can achieve a strong security posture. This approach ensures that applications can function and be monitored effectively, preventing the "blind spots" that often arise from overly restrictive network configurations. Reach for this workflow when you need to formalize network segmentation for new or existing applications, especially when integrating with a shared observability platform.

Anatomy

Prompt engineering breakdown

Role

Act as a Kubernetes Security Architect, generating NetworkPolicies to enforce zero-trust segmentation across multi-namespace clusters. The policies must maintain critical observability tool functionality and align with GitOps principles for phased rollout.

Context

The model acts within a multi-application Kubernetes cluster. It understands the need for zero-trust network policies, where traffic is denied by default. It must also account for existing observability tools in `{{observability_namespace}}` and generate policies for `{{application_name}}` across `{{namespace_list}}` using label selectors.

Goal

The primary goal is to generate Kubernetes NetworkPolicy YAML manifests that enforce a zero-trust model. Additionally, it needs to provide guidance on integrating these policies into a GitOps workflow (Helm/Kustomize) and outline a safe rollout and rollback strategy.

Constraints

Key constraints include enforcing a default-deny zero-trust posture, explicitly allowing observability traffic, defining application-specific ingress/egress, ensuring namespace isolation, idempotency, human readability, and using Kubernetes-native selectors instead of external IPs.

Output format

The required output consists of a YAML block containing all NetworkPolicy manifests, followed by a Markdown section for GitOps integration notes, and a separate Markdown section detailing the rollout and rollback strategy.

Why this structure works

This prompt employs strong role priming by assigning the 'Kubernetes Security Architect' persona, which aligns the model's responses with expert-level security considerations. Explicit constraints like 'Zero-Trust Default Deny' and 'Observability Exemption' guide the model to produce precise, functional policies. The structured output specification ensures all necessary components—YAML, GitOps notes, and deployment strategy—are delivered in a usable format.

Pick your version

Prompt variations

BeginnerWorks with any model

When you are new to Kubernetes NetworkPolicies or need a simplified approach for non-critical applications. Focuses on core security concepts without advanced deployment strategies.

prompt.txt
As a Kubernetes NetworkPolicy configurator, create basic NetworkPolicies for the `{{application_name}}` running in `{{namespace}}`. Your main task is to block all network traffic to and from this application by default, only allowing connections to the `{{observability_namespace}}` for monitoring and logging. Also, permit internal communication between pods belonging to `{{application_name}}` within `{{namespace}}`. Provide the YAML manifests for these policies. Focus on clear, simple rules. Assume pods are selected by `app: {{application_name}}`.
ProfessionalBest with claude

For platform and security engineers requiring comprehensive, production-ready NetworkPolicies, including GitOps integration and robust deployment planning for complex environments.

prompt.txt
Role: Kubernetes Security Architect. Context: You are securing a multi-namespace Kubernetes cluster. Implement a zero-trust network model for `{{application_name}}` across `{{namespace_list}}`. Crucially, ensure observability tools in `{{observability_namespace}}` retain full functionality for metrics, logs, and traces. Task: Generate NetworkPolicy YAML manifests enforcing zero-trust, permitting only explicitly defined traffic. Include specific ingress/egress rules for `{{application_name}}` based on common patterns. Provide GitOps integration notes for Helm/Kustomize and a phased rollout/rollback strategy. Constraints: Default deny, observability exemption, namespace isolation, idempotent, human-readable, Kubernetes-native selectors. Output: YAML manifests, GitOps notes, Rollout/Rollback strategy.
Short VersionWorks with any model

For experienced Kubernetes engineers needing a quick draft of zero-trust NetworkPolicies, focusing on the essential technical requirements without extensive contextual framing.

prompt.txt
Generate Kubernetes NetworkPolicy manifests to enforce zero-trust for `{{application_name}}` in `{{namespace_list}}`. All traffic must be denied by default, except for necessary communication with observability services in `{{observability_namespace}}` and specified internal application interactions. The policies should be idempotent, well-commented, and use Kubernetes-native selectors. Also, provide brief notes on GitOps integration (Helm/Kustomize) and a concise rollout plan. Output the YAML and markdown notes.
EnterpriseBest with gemini

When deploying NetworkPolicies in large-scale, regulated environments where compliance, risk management, and stakeholder buy-in are as critical as technical implementation.

prompt.txt
Role: Enterprise Security & Compliance Lead. Context: Implement stringent zero-trust NetworkPolicies for `{{application_name}}` across `{{namespace_list}}` within a regulated Kubernetes environment. Ensure full compliance with internal security baselines and external standards. Maintain critical observability via `{{observability_namespace}}` for audit and incident response. Task: Produce NetworkPolicy YAMLs, focusing on granular control and clear audit trails. Detail integration into our enterprise GitOps framework (Helm/Kustomize), including requirements for peer review and security sign-off. Outline a multi-stage rollout plan incorporating risk assessment, a defined rollback procedure, and stakeholder communication points. Policies must be auditable, idempotent, and explicitly state their default-deny nature.

What you'll get

Expected output

# NetworkPolicy for my-app in app-dev namespace --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-default-deny-app-dev namespace: app-dev spec: podSelector: matchLabels: app: my-app policyTypes: - Ingress - Egress # By omitting ingress/egress rules, all traffic is denied by default.

--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-allow-observability-egress-app-dev namespace: app-dev spec: podSelector: matchLabels: app: my-app policyTypes: - Egress egress: - to: - namespaceSelector: matchLabels: name: monitoring # Allow egress to the monitoring namespace podSelector: {} # Allow to all pods in monitoring namespace ports: - protocol: TCP port: 9090 # Example: Prometheus metrics port - protocol: TCP port: 24224 # Example: Fluentd log forwarding port - protocol: TCP port: 14268 # Example: Jaeger agent/collector port

--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-allow-self-ingress-app-dev namespace: app-dev spec: podSelector: matchLabels: app: my-app policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: app: my-app # Allow ingress from other my-app pods in the same namespace ports: - protocol: TCP port: 8080 # Example: Internal application communication port

--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-allow-db-egress-app-dev namespace: app-dev spec: podSelector: matchLabels: app: my-app policyTypes: - Egress egress: - to: - namespaceSelector: matchLabels: name: data # Allow egress to the data namespace podSelector: matchLabels: app: db-service # Allow egress to the db-service pods ports: - protocol: TCP port: 5432 # Example: PostgreSQL port

# NetworkPolicy for my-app in app-prod namespace --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-default-deny-app-prod namespace: app-prod spec: podSelector: matchLabels: app: my-app policyTypes: - Ingress - Egress

--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-allow-observability-egress-app-prod namespace: app-prod spec: podSelector: matchLabels: app: my-app policyTypes: - Egress egress: - to: - namespaceSelector: matchLabels: name: monitoring podSelector: {} ports: - protocol: TCP port: 9090 - protocol: TCP port: 24224 - protocol: TCP port: 14268

--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-allow-self-ingress-app-prod namespace: app-prod spec: podSelector: matchLabels: app: my-app policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: app: my-app ports: - protocol: TCP port: 8080

--- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: my-app-allow-db-egress-app-prod namespace: app-prod spec: podSelector: matchLabels: app: my-app policyTypes: - Egress egress: - to: - namespaceSelector: matchLabels: name: data podSelector: matchLabels: app: db-service ports: - protocol: TCP port: 5432

GitOps Integration Notes (Helm/Kustomize)

Helm: For Helm, these NetworkPolicy manifests can be placed directly into the templates/ directory of your application's Helm chart.

  • Parameterization: Use Helm's templating capabilities to make namespace and observability_namespace configurable via values.yaml. For example, namespace: {{ .Release.Namespace }} and name: {{ .Values.observabilityNamespace }}.
  • Conditional Deployment: You might include a values.yaml flag (e.g., networkPolicies.enabled: true) to conditionally deploy these policies, allowing for environments where they might not be needed or are managed externally.
  • Dependencies: If observability or database services are managed by separate charts, ensure proper dependency management or coordinate deployments to avoid policy enforcement issues before target services are ready.

Kustomize: With Kustomize, these policies can be managed as base resources and then overlaid for specific environments.

  • Base: Place all generated YAML files in a base/network-policies/ directory.
  • Overlays: Create overlays/app-dev/ and overlays/app-prod/ directories. In each overlay's kustomization.yaml, reference the base policies and apply namespace transformations if needed (though the policies are already namespaced here).
  • Common Labels: Use commonLabels in kustomization.yaml to add environment-specific labels to the policies for easier identification.
  • Patches: If minor modifications are needed per environment (e.g., adding an extra port), use JSON or Strategic Merge Patches.

Rollout and Rollback Strategy

Rollout Strategy (Phased Approach):

  1. Audit Mode (Optional but Recommended): If your CNI supports it (e.g., Calico's doNotTrack or allow-all with logging), deploy policies in a "log-only" or "audit" mode first. This allows you to observe what traffic *would* be blocked without actually enforcing it, helping identify missing rules.
  2. Staging Environment Deployment: Apply the NetworkPolicies to a non-production staging environment first. Thoroughly test all application functionalities, internal communications, and especially observability integrations (metrics, logs, traces). Verify that all expected traffic flows are permitted and unexpected traffic is blocked.
  3. Gradual Production Deployment:

* Phase 1 (Observability First): Deploy only the my-app-allow-observability-egress-* policies to production. This ensures that even if subsequent policies cause issues, you retain visibility into your application's health. * Phase 2 (Internal & DB): Deploy my-app-allow-self-ingress-* and my-app-allow-db-egress-* policies. Monitor closely for any disruptions to application functionality or database connectivity. * Phase 3 (Default Deny): Finally, deploy the my-app-default-deny-ingress-egress-* policies. This is the most impactful step, as it will block all traffic not explicitly allowed by the previous policies. Monitor all application metrics, logs, and user-facing functionality immediately after deployment.

  1. Continuous Monitoring: After full deployment, maintain vigilant monitoring for any NetworkPolicy related drops or unexpected application behavior.

Rollback Strategy:

  1. Immediate Reversal: If any critical issues arise during a deployment phase, the primary rollback strategy is to immediately delete the problematic NetworkPolicy resources. This can be done via kubectl delete -f <policy-file.yaml> or by reverting the Git commit in your GitOps repository and letting the reconciler apply the change.
  2. Gradual Removal (if needed): In complex scenarios, you might need to remove policies in reverse order of their deployment, starting with the default-deny and then specific allow policies, to isolate the problematic rule.
  3. Pre-computed Rollback Manifests: For critical applications, consider having pre-computed "rollback" manifests (e.g., an allow-all policy for the application's namespace) ready to apply instantly if a policy causes a severe outage, providing a quick "circuit breaker."
  4. Version Control: Ensure all NetworkPolicy changes are version-controlled. This allows for easy identification of the last working state and simplifies reverting to it.

Under the hood

Why this prompt works

This prompt structure effectively guides the model to produce actionable, secure, and operationally sound Kubernetes NetworkPolicies. The initial role priming as a "Kubernetes Security Architect" sets the appropriate tone and expertise level, ensuring the output reflects best practices rather than generic YAML.

The explicit constraints are crucial for achieving the desired zero-trust posture while maintaining observability. By specifically demanding "Zero-Trust Default Deny" and "Observability Exemption," the prompt forces the model to balance security with operational reality. The constraint on "Namespace Isolation" prevents common misconfigurations where policies might inadvertently allow broad cross-namespace communication.

Furthermore, the request for structured output (YAML manifests, GitOps notes, and a rollout/rollback strategy) ensures a comprehensive solution. This goes beyond merely generating YAML; it provides the necessary context for integrating these policies into a production environment. A one-liner prompt would likely produce only a basic policy, missing the critical considerations for deployment, management, and operational safety that platform and security engineers require. The detailed output format acts as a checklist, ensuring all necessary components for a successful implementation are addressed.

Model fit

Best AI models for this prompt

Claude

Claude excels at generating structured YAML output and following complex, multi-part instructions. Its strength lies in maintaining context across numerous constraints, which is crucial for balancing zero-trust enforcement with observability exemptions. It can sometimes be verbose in explanations, so directness in the prompt is beneficial. See the full Claude hub for deeper guidance.

ChatGPT

ChatGPT is proficient at translating natural language requirements into functional Kubernetes manifests. It handles the logical flow of NetworkPolicy rules well, especially when defining ingress and egress for specific services. While generally reliable, verify its output for edge cases in highly granular policy definitions. See the full ChatGPT hub for deeper guidance.

Gemini

Gemini demonstrates strong capabilities in understanding and applying security principles to infrastructure as code. It can produce accurate NetworkPolicy definitions and adapt to specified cluster architectures and service interactions. Review its output carefully for adherence to all zero-trust and observability constraints, as occasional oversight may occur with intricate dependencies. See the full Gemini hub for deeper guidance.

When to use

  • When implementing strict network segmentation for microservices.
  • For achieving compliance requirements like PCI DSS or HIPAA in multi-tenant environments.
  • To reduce the attack surface for sensitive applications by strictly controlling network flow.
  • After a security audit recommends stronger, explicit network controls.
  • When migrating from a permissive network model to a zero-trust architecture.

When not to use

  • In early development environments where rapid iteration is prioritized over strict network controls.
  • If your cluster's CNI plugin does not fully support Kubernetes NetworkPolicy enforcement.
  • When network traffic patterns are highly volatile and unpredictable, leading to frequent policy updates.
  • As a primary solution for securing inter-cluster or hybrid cloud communication.

Get more from it

Pro tips

  • 1

    Start with `policyTypes: [Ingress]` before adding `Egress` to avoid immediately disrupting all outgoing traffic.

  • 2

    Implement a separate `NetworkPolicy` specifically for observability exemptions; this keeps application logic clean and focused.

  • 3

    Use `kubectl describe networkpolicy` and CNI-specific logs to debug blocked traffic effectively, preventing prolonged outages.

  • 4

    Define a clear, consistent label strategy for pods and namespaces early to ensure uniform policy application and simplify management.

  • 5

    Automate policy generation where possible from service definitions to maintain consistency and reduce manual configuration errors.

  • 6

    Test policies thoroughly in a staging environment using actual application traffic to catch unforeseen communication blocks before production.

  • 7

    Use distinct `NetworkPolicy` resources for each microservice or component to simplify auditing and prevent policy rule sprawl.

Don't ship this

Common mistakes

  • Forgetting to add `policyTypes: [Ingress, Egress]` leading to partial enforcement or unexpected traffic flow.

    Fix — Always define both `policyTypes` explicitly unless intentionally limiting the policy scope for a specific reason.

  • Overlooking essential cluster services like `kube-dns` or `kube-api-server` access, breaking core Kubernetes functions.

    Fix — Explicitly permit egress to the cluster DNS service and the Kubernetes API server for all pods requiring it.

  • Applying policies too broadly with generic selectors, inadvertently disrupting critical services in other namespaces.

    Fix — Use precise `podSelector` and `namespaceSelector` combinations to target policies exactly where needed.

  • Not testing policies thoroughly before production, leading to unexpected service disruptions post-deployment.

    Fix — Implement a rigorous testing phase in a non-production environment, simulating real-world traffic patterns.

  • Hardcoding IP addresses instead of using Kubernetes service names or selectors for internal communication.

    Fix — Rely on `podSelector`, `namespaceSelector`, and `service` DNS for internal traffic; use `ipBlock` only for external CIDRs.

  • Inadvertently blocking observability agent traffic, creating blind spots in monitoring and logging.

    Fix — Double-check observability namespace policies and ensure necessary ingress/egress is permitted for all agents.

People also ask

Frequently asked questions

Q.Will these policies work with any CNI plugin?

Kubernetes NetworkPolicies are a standard API. Most common CNIs like Calico, Cilium, or Weave Net implement them. Ensure your chosen CNI has NetworkPolicy enforcement enabled and properly configured for your cluster before deployment.

Q.How do I handle external internet access for specific pods?

For external internet access, define an egress rule in your NetworkPolicy with an ipBlock for 0.0.0.0/0. Crucially, use the except field within this ipBlock to exclude your cluster's internal CIDRs to maintain zero-trust internally.

Q.What if my application uses hostPort?

NetworkPolicy operates at the pod IP level, not the host network interface directly. Policies applied to pods using hostPort will still govern traffic to the pod's IP. hostPort itself isn't directly controlled by NetworkPolicy.

Q.Can I use this for inter-cluster communication?

Kubernetes NetworkPolicy is designed for intra-cluster communication. For inter-cluster traffic, you typically rely on external firewalls, VPNs, or service meshes that span multiple clusters, rather than native NetworkPolicy.

Q.How often should I review my NetworkPolicies?

Review policies whenever application architectures change, new services are deployed, or after security audits. A quarterly review cycle is a good baseline to ensure they remain accurate, effective, and free of stale rules.

Q.What's the best way to visualize these policies?

Tools like Calico's network viewer, Cilium's Hubble, or commercial solutions offer visualization of NetworkPolicy rules and their impact. These tools help identify overlaps, gaps, and understand traffic flow more intuitively.

Q.How do I debug a blocked connection?

Start by checking the CNI logs for NetworkPolicy drop events. Use kubectl describe networkpolicy to verify policy application. Temporarily relax policies in a test environment, or use network debugging tools like tcpdump from within pods.

Version 1.0Last reviewed July 20, 2026
Reviewed by PromptInFlow Editorial Team