Back to Terraform

Alibaba Networking: VPCs, VSwitches, Routing and Security Boundaries

November 6, 2026 Wasil Zafar 23 min read

Trace cloud-specific network objects and private service paths with deliberate egress ownership

Table of Contents

  1. Draw VPC, VSwitch and Zone Relationships
  2. Choose CIDRs and Routing Owners Before Gateways
  3. Control Public Addresses, NAT and Security Groups
  4. Connect Private Services and Shared Networks Deliberately
  5. Test an Allowed and Denied Route

Draw VPC, VSwitch and Zone Relationships

A VPC is a regional routing domain; a VSwitch is a zonal address block. The VPC fixes the private range and owns the router that moves traffic between its VSwitches. A VSwitch names exactly one zone, one VPC and one CIDR, and every ENI takes its private address from a VSwitch.

Scope descends in one direction only. A region chooses where the API call lands, a VPC fixes the address plan, a zone fixes the failure domain a workload tolerates, and a VSwitch fixes the block an ENI may draw from. Nothing below the VPC spans a zone.

Creating a VPC also creates a router and a system route table. Terraform manages the VPC object; the router and the table arrive with it, and the VPC exposes the table identifier. That implicit table is why a fresh VPC already routes between its own VSwitches without a single route entry in your code.

Two zones always mean two VSwitches. There is no zonal subdivision of a VSwitch, so an ECS instance launched into zone b cannot borrow an address from a VSwitch in zone a. The second zone is a second CIDR, a second set of ENIs and, later, a second NAT gateway.

The zone is an input, not a constant. Query the zones that can host a VSwitch and pin the returned zone ids in a variable or a map. A hard-coded zone letter works until the instance type you need is unavailable there, and then the fix is a migration rather than a variable change.

Follow one packet out of an ENI. The egress rules on the security groups bound to that ENI are evaluated first. The route table associated with the source VSwitch chooses the next hop, and inside the VPC the system route delivers to the destination ENI, where the ingress rules are evaluated. Security groups are stateful, so the reply to an established connection needs no mirrored rule.

ScopeTerraform objectBinds toWhat it decides
Regionprovider regionevery VPC in the stackwhich zones exist and where the API call lands
VPCalicloud_vpcone regionthe address plan, the router and the system route table
VSwitchalicloud_vswitchone zone and one VPCthe block an ENI draws its address from
ENInetwork interfaceone VSwitchthe private address and security group membership
ECSalicloud_instanceone zone through its VSwitchthe workload that sends the packet

Read the table as a review checklist. A module input that claims to choose a subnet without a zone is hiding a VSwitch, and the zone it picks is whatever the provider default happens to be.

Draw VPC, VSwitch and Zone Relationships
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    Z["Zone query
VSwitch-capable zones"] --> V["VPC 10.20.0.0/16
one router, one system table"] V --> SYS["System route table
default association"] V --> A["vSwitch app-a
10.20.1.0/24, zone a"] V --> B["vSwitch app-b
10.20.2.0/24, zone b"] SYS -.->|"covers unless reattached"| A SYS -.->|"covers unless reattached"| B A --> EA["ENI and ECS
private IP, security groups"] B --> EB["ENI and ECS
private IP, security groups"] EA -->|"egress rules first"| RT["Route lookup
in the app-a table"] RT -->|"same VPC"| EB classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class Z warn; class V,RT primary; class SYS secondary; class A,B ok; class EA,EB secondary;

The diagram draws the VSwitch twice on purpose. It is the only object in the chain that is simultaneously an address block and a placement decision, so it appears once as the VPC's child and once as the parent of an ENI. The dotted edges are default associations rather than route entries you wrote.

Region, VPC, zone and VSwitch scopes in Alibaba Cloud A region contains one VPC with a router and system route table. The VPC contains two zones. Each zone contains one VSwitch with its own CIDR and one ENI-attached ECS instance, showing that a VSwitch never spans zones. Region, VPC, zone and VSwitch are four different scopes REGION cn-hangzhou a VPC cannot leave the region, a VSwitch cannot leave its zone VPC 10.20.0.0/16 router and system route table created with the VPC System route table covers every VSwitch until one is reattached PACKET PATH 1 egress rules on the ENI 2 route lookup in the VSwitch 3 router to the destination ENI 4 ingress rules on that ENI ZONE a vSwitch app-a 10.20.1.0/24 ENI and ECS private IP from app-a security groups apply at the ENI not at the VPC or the VSwitch ZONE b vSwitch app-b 10.20.2.0/24 ENI and ECS private IP from app-b the same VPC, a different zone no shared VSwitch is possible Two zones are two VSwitches, two CIDRs and two ENI sets — inside one VPC and one address plan.

The nested boxes are the point of the figure. The region contains the VPC, the VPC contains both zones, and each zone contains its own VSwitch and workload. A "subnet" mental model drawn as one flat row hides the fact that the middle object cannot be reused across zones.

Choose CIDRs and Routing Owners Before Gateways

The VPC block is the range you cannot quietly change. The primary CIDR is fixed at creation, and growth comes from adding a secondary block rather than editing the first. Each VSwitch CIDR is replacement-only, so a late resize is a new VSwitch with new ENIs rather than an edit.

The accepted ranges are wider than RFC1918, but the mask is not. The primary block may be 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 or a subset of one, with a mask of 8 to 28 bits. Custom blocks are accepted except a short reserved set — 100.64.0.0/10, 224.0.0.0/4, 127.0.0.0/8 and 169.254.0.0/16 — and every VSwitch must be between /16 and /29 and inside the VPC.

Overlap decides which connectivity product you may use. VPC peering needs disjoint ranges, so two teams that both took 10.0.0.0/8 have no pairing option. CEN exposes a protection level that permits overlapping ranges as long as they are not identical, which is an escape hatch rather than an address plan.

RangeCIDRLives inWhy it is reserved now
Production VPC10.20.0.0/16one region, two zonesworkload and NAT addresses
Staging VPC10.21.0.0/16one region, two zonesidentical shape, disjoint block
Shared services VPC10.30.0.0/16one regionPrivateLink providers and directories
On-premises172.20.0.0/16Express Connectmust not collide with any VPC above

Leave gaps between environments, not inside them. A /16 per environment with /24 VSwitches leaves room for a second tier without re-addressing, and the next environment starts a full octet away. The on-premises range is reserved even if the leased line is a year out, because retrofitting it later means renumbering whatever grew into the gap.

A route table belongs to a VPC but associates with VSwitches. The system table covers every VSwitch by default. A custom table plus an attachment moves one VSwitch onto its own routing, which is the smallest unit of routing ownership Alibaba offers.

A route entry is keyed by table and prefix. The entry resource is identified by the route table and the destination CIDR, and the prefix is replacement-only. Two modules that declare the same prefix on the same table do not merge; the second apply overwrites the next hop or fails with a conflict, and the earlier declaration then shows up as drift.

Enhanced NAT writes a default route you did not declare. The provider documents that creating an enhanced internet NAT gateway adds a 0.0.0.0/0 entry pointing at the gateway in the VPC route table. That is convenient, and it is also a second author for the most contested prefix in the network.

Give routes exactly one owner. The network stack owns the VPC, the VSwitches, the route tables, the entries, NAT, EIPs, peering and CEN attachments. Workload stacks own security groups, ENIs and instances, and read route identifiers instead of writing them. Any plan where a workload module contains a route entry is a review defect, even when the diff looks harmless.

This article targets Terraform 1.17.1 and aliyun/alicloud 2.2.0. In that provider the custom entry is alicloud_vpc_route_entry, and the VSwitch attachment is a separate resource. Managing a VSwitch's routing through the VPC object alone is not possible, which is why the attachment is the ownership boundary.

Choose CIDRs and Routing Owners Before Gateways
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    P["Pick the VPC block
10.20.0.0/16"] --> C{"Overlaps another VPC
or the on-premises range?"} C -->|"yes"| F1["Stop
peering cannot be created"] C -->|"no, or CEN allows it"| S["Split per zone
one /24 per VSwitch"] S --> M{"Inside the VPC and
mask between 16 and 29?"} M -->|"no"| F2["Apply fails
invalid VSwitch CIDR"] M -->|"yes"| R["Attach a route table
to each VSwitch"] R --> G{"Does a gateway also
write 0.0.0.0/0?"} G -->|"yes"| F3["Two owners for one prefix
the second one is drift"] G -->|"no"| OK["Entries only from
the network stack"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class P primary; class M,R,G,S secondary; class C warn; class F1,F2,F3 danger; class OK ok;

The amber decision is the one that passes plan and fails the network. CEN will accept an overlapping pair, so a bad range can survive apply and then be unreachable in the way that matters. The two red branches fail where you can see them; the last red branch is a conflict that no single apply reports.

DestinationNext hop typeWritten byFails when
Another VSwitch in the VPCsystem routethe VPC routera custom table hides it
Internet through NATNatGatewaythe gateway's default routetwo modules claim 0.0.0.0/0
Peer VPC prefixVpcPeera route entry on both sidesone side is missing
Alibaba service endpointGatewayEndpointthe endpoint attachmentattached to the wrong table
Appliance or extra ENIENI next hopa route entrythe ENI moves to another VSwitch

That list is the whole routing surface of a VPC. If a destination is not in one of those rows, the packet has no next hop and is dropped at the source VSwitch. That is why a missing peering route looks like a firewall problem from the application's point of view.

Control Public Addresses, NAT and Security Groups

Private addressing is included; public addressing is purchased. A VPC and its VSwitches hand out private addresses only. A public path is an EIP attached to an ENI or a NAT gateway holding EIPs, and both are billed whether or not traffic flows. The third path is easy to miss: an instance created with non-zero outbound bandwidth gets a public address with no EIP object in the plan.

Allocation and association are separate Terraform objects. One resource creates the address, another binds it, so a plan can keep a billed EIP attached to nothing. Destroy order follows the same split: detach first, release second.

A NAT gateway is created in a VSwitch, so it is tied to one zone. Enhanced NAT needs a VSwitch id, pay-as-you-go billing and at least one EIP. Two zones behind one gateway means the surviving zone's egress depends on the zone that failed.

NAT translates; it does not authorize. The egress security group still has to allow the flow, and NAT accepts no unsolicited inbound connection. It is also a poor per-workload audit boundary, because every ECS in the routed VSwitches leaves through the same source addresses.

Public pathObjectsInbound possibleBills while idle
EIP on an ENIaddress plus associationyes, subject to the security groupthe address
NAT gatewaygateway, EIPs, VSwitchnogateway capacity and addresses
No public pathnonenonothing

A security group belongs to a VPC and filters an ENI. Rules run by priority from 1 to 100, lower wins, and each rule accepts or drops. When no rule matches, the traffic is denied, and once a connection is established the return traffic is allowed without a mirror rule.

Network type is the field that breaks private tests. A rule that names a source security group must use intranet, and the provider rejects the combination otherwise. With NAT the workload has no public address, so its outbound path is private and the rule that governs it is the intranet one; an internet rule covers the path that arrives over a public address.

Internal access policy decides traffic inside the group. It defaults to accept, so two ENIs in one security group can talk on every port regardless of the rules you wrote. Set the policy to drop when the group is meant to isolate a tier, and expect the change to break service discovery that relied on the default.

A rule with no source fails closed. The source field has no default value, so an ingress rule without a CIDR, prefix list or source group is rejected rather than opened to everything. That is the right failure, but it means a half-finished rule looks like a network fault until you read the error.

PathRule that permits itRoute that carries itOwner
ECS to ECS, same VPCingress on the destination, source group, intranetsystem routeworkload team
ECS to internet through NATegress on the source, intranet0.0.0.0/0 to NatGatewaynetwork team
Internet to ECS through an EIPingress on the destination, internetEIP on the ENInetwork team
ECS to a peer VPCegress on the source, intranetVpcPeer entry on both sidesnetwork team

Read the table across, not down. Each row pairs one rule with one route; a row that is half true produces a timeout, not a refusal. The refusal case is usually a listener that is not running, which is why the denial test in the last section has to distinguish the two.

Connect Private Services and Shared Networks Deliberately

Alibaba has no Shared VPC object. There is no host VPC that a workload VPC joins, so sharing is composed from four products with different boundaries. Peering joins a pair, CEN joins many, PrivateLink exposes one service, and PrivateZone supplies the names.

Peering is a pair, and both sides write a route. alicloud_vpc_peer_connection creates the request and alicloud_vpc_peer_connection_accepter accepts it, and neither writes the routes you need. Each VPC needs a prefix entry pointing at the connection, and a third VPC inherits nothing from the first two.

CEN is the transit layer. Attach a VPC with alicloud_cen_instance_attachment, and CEN learns the attached CIDR so pairwise entries disappear from your code. Cross-account attachment needs the child owner id plus alicloud_cen_transit_router_grant_attachment, which replaces the deprecated CEN instance grant.

PrivateLink exposes a service, not a network. An interface endpoint lives in the consumer VPC, is placed in a VSwitch per zone, and carries a security group. The service provider never learns the consumer's range, so overlap stops mattering and the consumer cannot route to anything except the published service.

PrivateZone is the name layer, and attachment is the permission. A zone answers only inside the VPCs attached to it through alicloud_pvtz_zone_attachment, including attachments in another region. A VPC that was never attached resolves the public name or nothing at all, which is the failure that looks like a broken endpoint.

Shared networking is a RAM decision before it is a network one. Every cross-account path pairs a grant in one account with an attachment in the other, and the two are separate Terraform objects. A VPC cannot be moved between accounts, so the account that creates it owns every grant that follows.

NeedObjectsCrosses an accountBoundary you accept
Two VPCs, one pairpeer connection plus accepteroptionallyany port the security groups allow, both directions, disjoint CIDRs
Many VPCs, any-to-anyCEN instance, attachments, transit router grantyestransit reach for every attached range
One service, least reachPrivateLink endpoint plus zoneyesonly the published service
A private namePrivateZone plus attachmentyes, with authorizationname resolution inside attached VPCs

Choose by contract, then draw the diagram. A pair of VPCs with disjoint ranges is a peering. A growing estate, or one that must cross accounts, is a CEN. A single managed service that must not expose its range is a PrivateLink endpoint. Names are always PrivateZone, and none of the four implies another.

One-sided peering routes fail, two-sided routes work, PrivateLink avoids the return path On the left, VPC A has a route to the peering connection but VPC B has none, so the request crosses and the reply is dropped. On the right, both route tables carry the peer prefix and traffic flows both ways. A band below explains that a PrivateLink endpoint in the consumer VPC removes the return-route question. A peering connection is not a route, and a route is not bidirectional BEFORE · ROUTE ON ONE SIDE ONLY VPC A 10.20.0.0/16 route to peer VPC B 10.21.0.0/16 no route back The request arrives, the reply is dropped The connection exists and the CIDRs do not overlap, so nothing in the plan looks wrong. VPC B has no entry for 10.20.0.0/16, so the return packet has no next hop and is dropped at its source VSwitch. Symptom: a timeout, not a refusal. AFTER · ROUTES ON BOTH SIDES VPC A 10.20.0.0/16 route to peer VPC B 10.21.0.0/16 route to peer Two entries, two directions, one connection Each VPC names the peer prefix and the connection as the next hop. The design is symmetric, which is also why a third VPC cannot borrow the path: it has no route and the connection is not transitive. Symptom of success: a completed request. PRIVATELINK REMOVES THE RETURN-ROUTE QUESTION The endpoint takes an address from the consumer's own VSwitch, so the reply follows a local route back. The provider publishes a service instead of a range, so overlap stops mattering and the consumer's CIDR never has to be known. The endpoint's security group still decides who may connect.

The two panels are the same apply with one route entry moved. On the left, the connection is healthy and the plan is green; the only missing object is the prefix entry on the far side. On the right, symmetry is restored, and the amber band shows the product that sidesteps the whole question by putting the endpoint inside the consumer.

Test an Allowed and Denied Route

The Terraform runner is outside the network it builds. A laptop or hosted CI agent calls the API over the internet, so it can create a private path it has no way to use. Test from an ECS inside the workload VSwitch, with the same route table and the same security groups as the application.

Use Cloud Assistant instead of a public address. It runs a command through the instance agent, which keeps the instance private and still gives you a shell. Opening SSH to the internet to run one test changes the boundary you are trying to prove.

Control-plane success and data-plane success are different claims. A clean apply says the API accepted the objects. It does not say the route is present in the table the VSwitch uses, that the rule matched the traffic's network type, or that the destination is listening.

Lab

Test an Allowed and Denied Route

Status: design-only. One VPC, two zonal VSwitches, two ECS instances without public addresses, one enhanced NAT gateway and one EIP. The trace below is a design and a set of pass conditions, not a claim that it ran.

Prerequisites. Terraform 1.17.1 and aliyun/alicloud 2.2.0, a region with at least two VSwitch-capable zones, a pay-as-you-go account, and Cloud Assistant reachable from the runner.

Steps.

  1. Create a VPC at 10.20.0.0/16 and two VSwitches, one per zone, chosen from the VSwitch-capable zone query.
  2. Create a client group and a server group, and set inner_access_policy = "Drop" on both.
  3. Allow ingress TCP 443 on the server group from the client group with network type intranet, and add no other ingress rule.
  4. Allow egress TCP 443 to 0.0.0.0/0 on both groups with network type intranet.
  5. Create an enhanced NAT gateway in the app-a VSwitch with one EIP, and leave both VSwitches on the system route table so the gateway owns the default route. One gateway is enough for the trace; a production layout puts one in each zone.
  6. Launch client-a in the first VSwitch with the client group and server-b in the second with the server group, neither with a public address.
  7. Start a listener on 443 and another on 8080 on server-b, and confirm the Cloud Assistant agent is online.
  8. From the runner, send a Cloud Assistant command to client-a that connects to server-b on 443, then on 8080.
  9. Add an 8080 ingress rule with network type internet, repeat the private test, then remove the rule.
  10. From server-b, request a public HTTPS endpoint to prove the NAT path.
CheckMethodPass conditionFailure signal
Allowed 443assistant command from client-a to server-bconnection established, bytes returnedtimeout means route or rule
Denied 8080same command, port 8080timeout with no responseany response means the rule is too wide
Wrong network type8080 rule added as internetstill a timeoutsuccess means the rule reached private traffic
Egress through NATserver-b requests a public HTTPS URLa completed requesttimeout means no default route or no egress rule
Address inventorylist the ENIs and their addressesprivate addresses onlya public address means an EIP or an assigned public IP

Expected observation. The 443 connection completes, the 8080 connection times out, and adding the internet-type rule does not change that result. The public request from server-b completes through the NAT address while both ENIs keep private addresses only.

Failure check. The lab fails if 8080 answers, if the internet-type rule changes the private result, if the public request fails while the default route exists, if any test ENI holds a public address, or if a clean apply is treated as proof of connectivity.

Cost and cleanup. The NAT gateway and the EIP bill by the hour, so use pay-as-you-go: a subscription NAT gateway cannot be destroyed through Terraform since provider 2.1.0. Detach the EIP before releasing the address, delete the route entries with their table, and confirm the state list is empty rather than trusting the console.

Evidence to keep. The Cloud Assistant invocation identifiers, both security group rule listings, the route table listing before and after the internet-type rule, and the state list after destroy.

Next in the Series

In ECS Delivery: Images, Scaling and Alibaba Load-Balancer Health, we'll explore Coordinate compute images, scaling groups and health-based traffic without assuming resource creation equals readiness.