All Products
Search
Document Center

Container Compute Service:Manage agent network access with TrafficPolicy

Last Updated:Aug 28, 2026

TrafficPolicy controls network access for agent applications in ACS clusters. It supports priority-based multi-level network policies with matching methods such as CIDR, Service, and FQDN for fine-grained management of pod ingress and egress traffic.

How it works

TrafficPolicy and GlobalTrafficPolicy

ACS clusters provide two types of network policy resources:

Resource type

Scope

Use cases

TrafficPolicy

Namespace-level. Applies to pods with specific labels within a namespace.

Fine-grained network rules for specific applications.

GlobalTrafficPolicy

Cluster-level. Applies to pods with specific labels across the entire cluster.

Cluster-wide security baseline, such as blocking metadata service access.

Important

TrafficPolicy controls network access by configuring ACL rules inside the network namespace. A container that holds elevated privileges such as NET_ADMIN, SYS_ADMIN, CAP_SETUID, CAP_SETGID, privileged, or root can bypass ACL policies. Therefore, in Agent Sandbox scenarios, you must assign a dedicated security group to each sandbox to provide fallback isolation at the network layer. To achieve defense in depth, also combine GlobalTrafficPolicy ingress rules with security group inbound rules to prevent sandboxes from accessing non-sandbox workloads.

Policy enforcement rules

TrafficPolicy evaluates rules according to the following principles:

  1. Priority-based ordering: Priority ranges from 1 to 1000, with lower values indicating higher priority. Higher-priority policies are evaluated first.

  2. Sequential matching within the same priority: Rules within a policy are matched from top to bottom in the order they are defined.

  3. First-match termination: Once traffic matches a rule, evaluation stops immediately. No further rules are checked.

  4. Default deny: When a pod is selected by any policy, traffic that is not explicitly allowed is denied.

Important

Rule order directly affects matching results. Always place specific allow or deny rules first, and fallback rules last.

Supported match conditions

Important

Policies that use selectors such as service or workload require the controller to dynamically resolve pod IPs and distribute them to each agent. This process introduces an enforcement delay compared to static IP/CIDR rules, making selector-based policies unsuitable for scenarios that demand real-time enforcement.

Direction

Match condition

Description

Ingress

cidr

Matches by source IP range.

service

Matches by source Service.

ports

Matches by destination port and protocol (Layer 4 (L4)).

workload

Matches by destination pod.

Egress

cidr

Matches by destination IP range.

service

Matches by destination Service.

fqdn

Matches by destination domain name.

ports

Matches by destination port and protocol (L4).

workload

Matches by destination pod.

Note

Ingress rules do not support FQDN (Fully Qualified Domain Name) matching. FQDN rules have the following constraints:

  1. Dynamic resolution: The controller resolves DNS records in real time and pushes the resulting IP addresses to nodes. Because DNS records change over time, FQDN-associated IP addresses are dynamic. Wildcard domains are not supported.

  2. Directional control limitation: If multiple domain names resolve to the same IP address, the system cannot distinguish between allow and deny rules based on the domain name. The system enforces rules by priority only.

  3. Best practice: Given these limitations, use FQDN rules only for access control to internal services to ensure policy accuracy and stability.

Comparison with Kubernetes NetworkPolicy

Compared with Kubernetes NetworkPolicy, TrafficPolicy and GlobalTrafficPolicy offer the following advantages:

Capability

Kubernetes NetworkPolicy

TrafficPolicy and GlobalTrafficPolicy

Priority control

Not supported

Supports 1–1000 priority levels

Explicit deny

Not supported

Supported

FQDN matching

Not supported

Supported

Supported cluster scale

Up to 20,000 pods per cluster

Up to 50,000 pods per cluster

Rapid agent scaling scenarios

High management complexity

Optimized for this scenario

Scope

  • Cluster version 1.24 or later. Only IPv4 rules are supported. IPv6 rules are not supported.

  • Poseidon component is v0.7.0 or later with TrafficPolicy enabled.

    Install the component or check the version

    1. Log on to the ACS console. In the left navigation pane, click Clusters.

    2. On the Clusters page, click the name of your cluster. In the left navigation pane, click Components and Add-ons .

    3. On the Add-ons page, check the version of the Poseidon component and ensure that the TrafficPolicy feature is enabled.

  • L4 port feature requires component v0.7.3 or later. Hot updates are not supported for ACS pods; changes apply only to new resources.

  • Workload selection requires component v0.7.6 or later. Hot updates are not supported for ACS pods; changes apply only to new resources.

Configuration examples

Quick start

This example shows how to configure a basic network policy for an agent application, allowing access to the DNS service and the internet.

Step 1: Enable TrafficPolicy in the agent pod

Save the following manifest as agent-pod.yaml and run kubectl apply -f agent-pod.yaml to deploy the example pod.

  • network.alibabacloud.com/enable-network-policy-agent: "true": Enables the network policy agent.

  • network.alibabacloud.com/network-policy-mode: "traffic-policy": Specifies the TrafficPolicy mode.

apiVersion: v1
kind: Pod
metadata:
  name: agent-pod
  annotations:
    network.alibabacloud.com/enable-network-policy-agent: "true"
    network.alibabacloud.com/network-policy-mode: "traffic-policy"
  labels:
    app: agent
spec:
  containers:
  - name: agent
    image: registry.aliyuncs.com/acs/ubuntu:latest
    command: ["sleep", "infinity"]

Step 2: Create a TrafficPolicy

Create the following YAML file agent-basic-policy.yaml to allow the agent pod to access the DNS service and the internet.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-basic-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent

  egress:
    rules:
      # Allow access to the DNS service
      - action: allow
        to:
          - service:
              namespace: kube-system
              name: kube-dns

      # Allow access to the internet
      - action: allow
        to:
          - cidr: 0.0.0.0/0

Step 3: Apply and verify the policy

  1. Apply the policy.

    kubectl apply -f agent-basic-policy.yaml
  2. Check the policy status.

    kubectl get trafficpolicy -n default

    Expected output:

    NAME                 PRIORITY   AGE
    agent-basic-policy   100        10s
  3. Verify network connectivity.

    # Enter the pod
    kubectl exec -it agent-pod -n default -- /bin/bash
    
    # Install network utilities
    apt-get update && apt-get install -y curl dnsutils
    
    # Test internet access (should succeed)
    curl -I https://www.aliyun.com
    
    # Test DNS resolution (should succeed)
    nslookup www.aliyun.com

Restrict pod access to specific services and domains

This policy allows access to the DNS service, a specific domain name, and a specific CIDR (Classless Inter-Domain Routing) block, while denying access to the cloud metadata service and all other addresses.

Replace rds-xxx.aliyuncs.com with your actual RDS instance domain name.
apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-egress-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent

  egress:
    rules:
      # Deny access to the cloud metadata service
      - action: deny
        to:
          - cidr: 100.100.100.200/32

      # Allow access to a specific CIDR block
      - action: allow
        to:
          - cidr: 100.96.0.0/10

      # Allow access to a specific domain name
      - action: allow
        to:
          - fqdn: rds-xxx.aliyuncs.com

      # Allow access to the DNS service
      - action: allow
        to:
          - service:
              namespace: kube-system
              name: kube-dns

      # Fallback rule: Deny access to all other addresses
      - action: deny
        to:
          - cidr: 0.0.0.0/0

Deny pod access to private networks

Explicitly deny access to private CIDR blocks while allowing internet access.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-internet-only-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent
      
  egress:
    rules:
      # Allow DNS
      - action: allow
        to:
          - service:
              namespace: kube-system
              name: kube-dns
  
      # Deny access to private networks
      - action: deny
        to:
          - cidr: 10.0.0.0/8
      - action: deny
        to:
          - cidr: 172.16.0.0/12
      - action: deny
        to:
          - cidr: 192.168.0.0/16

      # Deny access to Gateway
      - action: deny
        from:
          - service:
              name: sandbox-gateway
              namespace: sandbox-system
  
        - action: deny
        from:
          - service:
              name: sandbox-manager
              namespace: sandbox-system
                  
      # Allow access to the internet
      - action: allow
        to:
          - cidr: 0.0.0.0/0

Restrict ingress to a specific Service

This policy restricts the agent pod to accept ingress only from the Gateway service.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-ingress-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent

  ingress:
    rules:
      # Allow ingress from the Gateway service
      - action: allow
        from:
          - service:
              name: sandbox-gateway
              namespace: sandbox-system

      # Fallback rule: Deny ingress from all other sources
      - action: deny
        from:
          - cidr: 0.0.0.0/0

Configure Layer 4 port and protocol filtering

Field

Type

Description

protocol

string

The protocol type. Valid values: TCP and UDP.

If empty, matches any protocol. Port rules are applied to both TCP and UDP.

port

integer

The port number. Combine with endPort to specify a port range. If empty, no port restriction applies.

endPort

integer

End of the port range. Must be >= port. If only port is specified, a single port is matched.

Usage rules

  • Multiple ports entries are combined with OR; the rule matches if any entry matches.

  • Within a rule, ports and peer (from/to) conditions are combined with AND; both must match.

  • If ports is not specified, the rule matches on peer only, without port restrictions (equivalent to an L3 rule).

Example: Allow a specific TCP port

This policy allows the agent pod to access the target server on TCP port 80 only. All other ports are implicitly denied.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-l4-tcp-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent

  egress:
    rules:
      - action: allow
        to:
          - cidr: 10.0.0.10/32
        ports:
          - protocol: TCP
            port: 80

Example: Allow UDP and TCP port 53 for DNS

DNS queries typically use UDP, but large responses can fall back to TCP. This policy allows both:

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-dns-l4-policy
  namespace: default
spec:
  priority: 50
  selector:
    matchLabels:
      app: agent

  egress:
    rules:
      - action: allow
        to:
          - service:
              namespace: kube-system
              name: kube-dns
        ports:
          - protocol: UDP
            port: 53
          - protocol: TCP
            port: 53

Example: Allow a TCP port range

Use port and endPort to define a continuous port range, which is common for services that use high-numbered ports.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-port-range-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent

  egress:
    rules:
      - action: allow
        to:
          - cidr: 10.0.0.0/8
        ports:
          - protocol: TCP
            port: 8080
            endPort: 8090

Example: Restrict ingress to a specific port

This policy allows other pods to access the current pod only on TCP port 80. Ingress traffic on all other ports is implicitly denied.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: agent-ingress-l4-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent

  ingress:
    rules:
      - action: allow
        from:
          - cidr: 0.0.0.0/0
        ports:
          - protocol: TCP
            port: 80

Cluster-wide access control

This global policy denies a specific CIDR block from accessing pods in the cluster while allowing all other traffic.

apiVersion: network.alibabacloud.com/v1alpha1
kind: GlobalTrafficPolicy
metadata:
  name: global-security-baseline
spec:
  priority: 1000    # Low priority, acts as a fallback policy
  selector: {}      # Applies to all pods in the cluster

  ingress:
    rules:
      # Deny access from the Sandbox CIDR block
      - action: deny
        from:
          - cidr: 10.8.0.0/16

      # Allow all other sources
      - action: allow
        from:
          - cidr: 0.0.0.0/0

  egress:
    rules:
      - action: allow
        to:
          - cidr: 0.0.0.0/0
Setting the selector of a GlobalTrafficPolicy to an empty object {} applies the policy to all matching pods in the cluster.

Combine multi-level security policies

You can combine multiple TrafficPolicy resources with different priorities to implement layered control. The following table shows the recommended priority layering scheme and configuration examples.

Priority range

Purpose

Example scenarios

1–49 (High priority)

Infrastructure services

DNS, monitoring, and log collection

50–499 (Medium priority)

Business services

Database, cache, and message queue

500–1000 (Low priority)

Fallback policies

Global security baselines, internet access control

Infrastructure services (high priority)

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: infra-policy
  namespace: default
spec:
  priority: 10
  selector:
    matchLabels:
      app: agent
  egress:
    rules:
      - action: allow
        to:
          - service:
              namespace: kube-system
              name: kube-dns
      - action: allow
        to:
          - service:
              namespace: monitoring
              name: prometheus

Business services (medium priority)

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: business-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: agent
  egress:
    rules:
      - action: allow
        to:
          - service:
              namespace: default
              name: redis
      - action: allow
        to:
          - service:
              namespace: default
              name: mysql

Internet access control (low priority)

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: internet-policy
  namespace: default
spec:
  priority: 500
  selector:
    matchLabels:
      app: agent
  egress:
    rules:
      - action: allow
        to:
          - cidr: 0.0.0.0/0

Complete network policy for OpenClaw

This policy defines a complete network isolation policy for the OpenClaw application, including both ingress and egress rules.

Important

Policies that use selectors such as service or workload require the controller to dynamically resolve pod IPs and distribute them to each agent. This process introduces an enforcement delay compared to static IP/CIDR rules, making selector-based policies unsuitable for scenarios that demand real-time enforcement.

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: openclaw-policy
  namespace: default
spec:
  priority: 100
  selector:
    matchLabels:
      app: openclaw

  ingress:
    rules:
      # Allow access from the control plane switch
      - action: allow
        from:
          - cidr: 172.16.10.0/24
      # Allow access from Gateway and Sandbox Manager (can be omitted if deployed in the same subnet as the control plane switch)
      - action: allow
        from:
          - service:
              name: sandbox-gateway
              namespace: sandbox-system
          - service:
              name: sandbox-manager
              namespace: sandbox-system
          - service:
              name: sandbox-controller-manager-webhook-service
              namespace: sandbox-system
      # Deny all other sources
      - action: deny
        from:
          - cidr: 0.0.0.0/0

  egress:
    rules:
      # Deny access to the cloud metadata service
      - action: deny
        to:
          - cidr: 100.100.100.200/32

      # Allow the DNS service
      - action: allow
        to:
          - service:
              namespace: kube-system
              name: kube-dns

      # Allow access to the LLM proxy service
      - action: allow
        to:
          - service:
              namespace: llm-proxy
              name: llm-proxy

      # Deny access to private networks
      - action: deny
        to:
          - cidr: 10.0.0.0/8
          - cidr: 172.16.0.0/12
          - cidr: 192.168.0.0/16

      # Deny Sandbox Manager
      - action: deny
        to:
          - service:
              name: sandbox-gateway
              namespace: sandbox-system
          - service:
              name: sandbox-manager
              namespace: sandbox-system

      # Allow access to the internet
      - action: allow
        to:
          - cidr: 0.0.0.0/0

Best practices

Follow the principle of least privilege

Grant pods only the necessary network access permissions. Explicitly list the services and addresses that are allowed, and deny all other traffic by default.

egress:
  rules:
    # Explicitly allow services
    - action: allow
      to:
        - service:
            namespace: kube-system
            name: kube-dns
    - action: allow
      to:
        - fqdn: api.alibabacloud.com

    # Deny private networks
    - action: deny
      to:
        - cidr: 10.0.0.0/8
        - cidr: 172.16.0.0/12
        - cidr: 192.168.0.0/16

    # Deny Sandbox Manager
    - action: deny
      to:
        - service:
            name: sandbox-gateway
            namespace: sandbox-system
        - service:
            name: sandbox-manager
            namespace: sandbox-system

    # Allow the internet as needed
    - action: allow
      to:
        - cidr: 0.0.0.0/0

ingress:
  rules:
      # Allow access from Gateway and Sandbox Manager (can be omitted if deployed in the same subnet as the control plane switch)
      - action: allow
        from:
          - service:
              name: sandbox-gateway
              namespace: sandbox-system
          - service:
              name: sandbox-manager
              namespace: sandbox-system
          - service:
              name: sandbox-controller-manager-webhook-service
              namespace: sandbox-system

Design precise label selectors

Use multi-dimensional labels to precisely match target pods and prevent policies from affecting unintended workloads.

# Recommended: Multi-dimensional labels
selector:
  matchLabels:
    app: agent
    environment: production
    team: ai-platform

# Avoid: Overly broad labels
selector:
  matchLabels:
    app: agent

Label design recommendations:

  • app: Identifies the application type.

  • environment: Distinguishes environments (production, staging, development).

  • team: Identifies the owning team.

Combine with GlobalTrafficPolicy

Use GlobalTrafficPolicy for the cluster-wide security baseline, and TrafficPolicy for fine-grained, application-level control:

Policy layer

Type

Priority

Responsibility

Application

TrafficPolicy

50–200

Fine-grained network rules for specific applications.

Global

GlobalTrafficPolicy

1000

Cluster-wide security baseline (for example, denying traffic from a Sandbox CIDR block).

Audit policies regularly

Establish a regular policy auditing mechanism:

  • Check whether TrafficPolicy objects meet the latest security requirements.

  • Review denied connection logs to identify potential issues.

  • Remove policies that are no longer in use.

  • Adjust policies as business requirements change.

  • Verify that priority settings are appropriate.

Example audit script:

#!/bin/bash

echo "=== All TrafficPolicy resources ==="
kubectl get trafficpolicy --all-namespaces -o wide

printf '\n=== All GlobalTrafficPolicy resources ===\n'
kubectl get globaltrafficpolicy -o wide

printf '\n=== Agent pod list ===\n'
kubectl get pods -l app=agent --all-namespaces

Manage policies with version control

Store TrafficPolicy configurations in Git, organized by purpose.

traffic-policies/
├── base/                          # Base policies
│   ├── global-security-baseline.yaml
│   └── dns-access.yaml
├── applications/                  # Application policies
│   ├── openclaw-policy.yaml
│   └── agent-policy.yaml
└── environments/                  # Environment-specific overrides
    ├── production/
    │   └── overrides.yaml
    └── staging/
        └── overrides.yaml

FAQ

Policy not taking effect

Symptom: A TrafficPolicy is created, but network access is not restricted.

Troubleshooting:

  1. Check the Poseidon component status: Confirm that it is installed, the component version is v0.7.0 or later, and the TrafficPolicy feature is enabled.

  2. Check the pod annotations: Confirm that the pod has the required annotations configured.

  3. Check the pod labels: Confirm that the pod labels exactly match the policy's selector.matchLabels.

    kubectl get pod <pod-name> --show-labels
  4. Check the rule order: Confirm that specific rules are placed first and fallback rules are placed last.

    kubectl get trafficpolicy <policy-name> -o yaml

Policy conflicts

Symptom: Multiple policies apply to the same pod, and the network behavior does not match expectations.

Troubleshooting:

  1. List all policies and their priorities:

    kubectl get trafficpolicy,globaltrafficpolicy -A -o wide
  2. Check whether policies with the same priority apply to the same pod.

  3. Adjust the priority values so that higher-priority policies use smaller values.

  4. Merge conflicting policies to avoid duplicate definitions.

Network connection timeout

Symptom: A pod cannot reach the expected address or service.

Troubleshooting:

  1. Check whether the policy is missing required allow rules (such as the DNS service).

  2. Check whether the fallback rule is too strict, blocking required network access.

  3. Add the required allow rule to the policy:

    egress:
      rules:
        - action: allow
          to:
            - service:
                namespace: <namespace>
                name: <service-name>
  4. Ensure that allow rules have a higher priority than deny rules, or place allow rules before deny rules in the same policy.

Pod cannot be accessed

Symptom: Other services cannot access the target pod.

Troubleshooting:

  1. Check whether the ingress rules allow the required source services.

  2. Add an allow rule for the source service:

    ingress:
      rules:
        - action: allow
          from:
            - service:
                name: <source-service>
                namespace: <source-namespace>

TrafficPolicy API reference

Resource overview

Property

Value

API group

network.alibabacloud.com

API version

v1alpha1

Resource type

TrafficPolicy (namespace-scoped) / GlobalTrafficPolicy (cluster-scoped)

Short name

tp / gtp

Minimum component version

v0.7.0

TrafficPolicy and GlobalTrafficPolicy share the same spec structure, differing only in their scope:

Resource

Scope

Short name

Typical scenario

TrafficPolicy

Namespace-scoped; selects pods only within the same namespace.

tp

Application-level, fine-grained network rules.

GlobalTrafficPolicy

Cluster-scoped; selects pods across all namespaces.

gtp

Cluster-wide security baseline.

Version requirements quick reference

Feature

Minimum version

Description

TrafficPolicy / GlobalTrafficPolicy

v0.7.0

Basic features: CIDR, Service, and FQDN peers; allow/deny actions.

L4 port filtering (ports field)

v0.7.3

Supports protocol, port, and endPort.

Workload selector (workload peer)

v0.7.6

Matches pods by namespace and label selector.

Reject action (action: reject)

v0.8.0

Returns a TCP RST or an ICMP port unreachable message.


CRD reference

TrafficPolicy fields

apiVersion: network.alibabacloud.com/v1alpha1
kind: TrafficPolicy
metadata:
  name: <policy-name>              # Policy name. Must be unique within the namespace.
  namespace: <namespace>           # The namespace where the policy is defined.
spec:
  priority: <1-1000>               # Priority. Default: 1000. Lower values have higher priority.
  selector:                        # Pod selector. Determines which pods the policy applies to.
    matchLabels:
      <label-key>: <label-value>
    matchExpressions:              # Optional. Supports more complex selection logic.
      - key: <label-key>
        operator: In|NotIn|Exists|DoesNotExist
        values: [<value1>, <value2>]

  ingress:                         # Ingress rules (optional).
    rules:
      - action: allow|deny|reject         # Action to take when a rule matches.
        from:                      # Source match conditions. Multiple entries are combined with OR.
          - cidr: <cidr>           # Source IP range (for example, 10.0.0.0/8).
          - service:               # Source Service.
              name: <name>
              namespace: <namespace>   # Optional. Defaults to the policy's namespace if omitted.
          - workload:              # Source workload (selects pods by label).
              namespace: <namespace>
              selector:
                <label-key>: <label-value>
        ports:                     # Port filtering (optional). Combined with from using AND logic.
          - protocol: TCP|UDP  # Optional. If omitted, matches both TCP and UDP.
            port: <1-65535>        # Optional. If omitted, no port restriction applies.
            endPort: <1-65535>     # Optional. Use with port to define a port range.

  egress:                          # Egress rules (optional).
    rules:
      - action: allow|deny         # Action to take when a rule matches.
        to:                        # Destination match conditions. Multiple entries are combined with OR.
          - cidr: <cidr>           # Destination IP range.
          - service:               # Destination Service.
              name: <name>
              namespace: <namespace>   # Optional. Defaults to the policy's namespace if omitted.
          - fqdn: <domain>         # Destination FQDN (egress only; wildcards not supported).
          - workload:              # Destination workload (selects pods by label).
              namespace: <namespace>
              selector:
                <label-key>: <label-value>
        ports:                     # Port filtering (optional). Combined with to using AND logic.         

GlobalTrafficPolicy fields

apiVersion: network.alibabacloud.com/v1alpha1
kind: GlobalTrafficPolicy
metadata:
  name: <policy-name>              # Policy name. Must be unique within the cluster.
spec:
  priority: <1-1000>               # Priority. Default: 1000. Lower values have higher priority.
  selector:                        # Pod selector. An empty object {} selects all pods in the cluster.
    matchLabels:
      <label-key>: <label-value>

  ingress:                         # Ingress rules (optional). Same structure as TrafficPolicy.
    rules:
      - action: allow|deny|reject
        from:
          - cidr: <cidr>
          - service:
              name: <name>
              namespace: <namespace>
          - workload:
              namespace: <namespace>
              selector:
                <label-key>: <label-value>
        ports:
          - protocol: TCP|UDP
            port: <1-65535>
            endPort: <1-65535>

  egress:                          # Egress rules (optional). Same structure as TrafficPolicy.
    rules:
      - action: allow|deny|reject
        to:
          - cidr: <cidr>
          - service:
              name: <name>
              namespace: <namespace>
          - fqdn: <domain>
          - workload:
              namespace: <namespace>
              selector:
                <label-key>: <label-value>
        ports:
          - protocol: TCP|UDP
            port: <1-65535>
            endPort: <1-65535>

Match conditions reference

Ingress rules

Field

Type

Description

Example

cidr

string

Source IP range

10.0.0.0/8

service

object

Source Service (includes name and namespace)

{"name": "gateway", "namespace": "default"}

namespace

string

Source namespace

kube-system

Egress rules

Field

Type

Description

Example

cidr

string

Destination IP range

192.168.0.0/16

service

object

Destination Service (includes name and namespace)

{"name": "redis", "namespace": "default"}

fqdn

string

Destination FQDN

api.alibabacloud.com

Go type reference

TrafficPolicy/GlobalTrafficPolicy

package v1alpha1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

type EgressRuleType string

const (
	EgressRuleTypeCIDR     EgressRuleType = "cidr"
	EgressRuleTypeService  EgressRuleType = "service"
	EgressRuleTypeFQDN     EgressRuleType = "fqdn"
	EgressRuleTypeWorkload EgressRuleType = "workload"
)

type EgressRuleAction string

const (
	EgressRuleActionAllow EgressRuleAction = "allow"
	EgressRuleActionDeny  EgressRuleAction = "deny"
	EgressRuleActionReject EgressRuleAction = "reject"
)

type TrafficPolicyServiceRef struct {
	Name string `json:"name"`
	// +optional
	Namespace string `json:"namespace,omitempty"`
}

// TrafficPolicyWorkloadRef selects pods by namespace and label selector.
// The IP addresses of all matching pods are collected into the IPSet.
type TrafficPolicyWorkloadRef struct {
	// Namespace of the target pods.
	Namespace string `json:"namespace"`
	// Selector is a label selector that matches the target pods.
	Selector map[string]string `json:"selector"`
}

type TrafficPolicyPeer struct {
	// +optional
	CIDR string `json:"cidr,omitempty"`
	// +optional
	FQDN string `json:"fqdn,omitempty"`
	// +optional
	Service *TrafficPolicyServiceRef `json:"service,omitempty"`
	// +optional
	Workload *TrafficPolicyWorkloadRef `json:"workload,omitempty"`
}

// TrafficPolicyPort restricts a rule to specific protocol/port combinations.
// If Protocol is empty, matches any protocol:
// with Port nil, there is no L4 match (same as IP-only for that port entry).
// If Protocol is non-empty and Port is nil, matches all ports of that protocol.
type TrafficPolicyPort struct {
	// +optional
	// +kubebuilder:validation:Enum=TCP;UDP
	Protocol string `json:"protocol,omitempty"`
	// +optional
	// +kubebuilder:validation:Minimum=1
	// +kubebuilder:validation:Maximum=65535
	Port *int32 `json:"port,omitempty"`
	// +optional
	// +kubebuilder:validation:Minimum=1
	// +kubebuilder:validation:Maximum=65535
	EndPort *int32 `json:"endPort,omitempty"`
}

type TrafficPolicyRule struct {
	// +kubebuilder:validation:Enum=allow;deny
	Action EgressRuleAction `json:"action"`
	// +optional
	From []TrafficPolicyPeer `json:"from,omitempty"`
	// +optional
	To []TrafficPolicyPeer `json:"to,omitempty"`
	// +optional
	Ports []TrafficPolicyPort `json:"ports,omitempty"`
}

type TrafficPolicyDirection struct {
	// +optional
	Rules []TrafficPolicyRule `json:"rules,omitempty"`
}

// TrafficPolicySpec defines bidirectional policy state on selected pods.
type TrafficPolicySpec struct {
	// +optional
	// +kubebuilder:default:=1000
	// +kubebuilder:validation:Minimum=0
	Priority int32 `json:"priority,omitempty"`

	Selector metav1.LabelSelector `json:"selector"`

	// +optional
	Ingress *TrafficPolicyDirection `json:"ingress,omitempty"`
	// +optional
	Egress *TrafficPolicyDirection `json:"egress,omitempty"`
}

// IPSetBinding records one SelectorIPSet referenced by a rule in this policy,
// along with the direction, action, rule index, and optional port restrictions.
type IPSetBinding struct {
	// Name of the SelectorIPSet object (e.g. "ipset-a1b2c3d4e5f6").
	IPSetName string `json:"ipsetName"`
	// Content hash (same as SelectorIPSet.Spec.IPSetID).
	IPSetID string `json:"ipsetID"`
	// "egress" or "ingress"
	Direction string `json:"direction"`
	// "allow" or "deny"
	Action EgressRuleAction `json:"action"`
	// Index of the rule within spec.egress.rules or spec.ingress.rules.
	RuleIndex int32 `json:"ruleIndex"`
	// +optional
	Ports []TrafficPolicyPort `json:"ports,omitempty"`
}

// TrafficPolicyStatus defines the observed state of TrafficPolicy.
type TrafficPolicyStatus struct {
	// IPSetBindings lists all SelectorIPSet objects referenced by this policy's rules.
	// +optional
	IPSetBindings []IPSetBinding `json:"ipsetBindings,omitempty"`
	// +optional
	Conditions []metav1.Condition `json:"conditions,omitempty"`
}

// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Namespaced,shortName=ep

// TrafficPolicy defines bidirectional traffic rules for selected pods.
type TrafficPolicy struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// +optional
	Spec TrafficPolicySpec `json:"spec,omitempty"`
	// +optional
	Status TrafficPolicyStatus `json:"status,omitempty"`
}

// +kubebuilder:object:root=true

// TrafficPolicyList contains a list of TrafficPolicy.
type TrafficPolicyList struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []TrafficPolicy `json:"items"`
}

// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:resource:scope=Cluster,shortName=gtp
//
// GlobalTrafficPolicy defines bidirectional traffic rules cluster-wide.
type GlobalTrafficPolicy struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// +optional
	Spec TrafficPolicySpec `json:"spec,omitempty"`
	// +optional
	Status TrafficPolicyStatus `json:"status,omitempty"`
}

// +kubebuilder:object:root=true
//
// GlobalTrafficPolicyList contains a list of GlobalTrafficPolicy.
type GlobalTrafficPolicyList struct {
	metav1.TypeMeta `json:",inline"`
	// +optional
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []GlobalTrafficPolicy `json:"items"`
}

var (
	// GroupVersion is group version used to register these objects.
	GroupVersion = schema.GroupVersion{Group: "network.alibabacloud.com", Version: "v1alpha1"}
)