构建AWS CDK Stack时遇'Error: Cannot create a VPC Endpoint with no subnets'错误
问题分析与解决
错误原因
- 子网引用错误:你的VPC配置的是
PRIVATE_ISOLATED类型子网,但代码中用vpc.privateSubnets获取子网。在AWS CDK中,vpc.privateSubnets对应的是PRIVATE_WITH_EGRESS类型的子网,PRIVATE_ISOLATED子网需通过vpc.isolatedSubnets获取,导致传递给VPC端点的子网数组为空,触发Cannot create a VPC Endpoint with no subnets错误。 - S3端点类型错误:S3的VPC端点是网关型(Gateway),而非接口型(Interface),用
InterfaceVpcEndpoint创建S3端点本身就是错误,后续即使解决子网问题也会触发其他异常。
修正后的代码
import * as ec2 from 'aws-cdk-lib/aws-ec2'; [...] /*** Create VPC and its SUBNET and ENDPOINT ***/ const vpc = new ec2.Vpc(this, env.vpcName, { ipAddresses: ec2.IpAddresses.cidr('172.16.0.0/16'), subnetConfiguration: [ { // CIDR mask: 255.255.255.0 cidrMask: 24, name: env.vpcSubnetName, subnetType: ec2.SubnetType.PRIVATE_ISOLATED } ] }); // Security group for the EC2 instance const securityGroup = new ec2.SecurityGroup(this, env.securityGroupName, { vpc, description: "Allow SSH (TCP port 22) and HTTP (TCP port 80) in", allowAllOutbound: true, }); // Allow SSH access on port tcp/22 securityGroup.addIngressRule( ec2.Peer.anyIpv4(), ec2.Port.tcp(22), "Allow SSH Access" ); // Allow HTTP access on port tcp/80 securityGroup.addIngressRule( ec2.Peer.anyIpv4(), ec2.Port.tcp(80), "Allow HTTP Access" ); // DynamoDB接口型VPC端点,修正子网引用 new ec2.InterfaceVpcEndpoint(this, env.vpcEndpointDynamoDBName, { vpc, service: ec2.InterfaceVpcEndpointService.fromAwsService(ec2.AwsService.DYNAMODB), subnets: { subnets: vpc.isolatedSubnets // 改用isolatedSubnets获取隔离子网 }, privateDnsEnabled: true, securityGroups: [securityGroup] }); // S3网关型VPC端点,修正端点类型 new ec2.GatewayVpcEndpoint(this, env.vpcEndpoints3Name, { vpc, service: ec2.GatewayVpcEndpointAwsService.S3, // 关联隔离子网的路由表 subnets: [ { subnetType: ec2.SubnetType.PRIVATE_ISOLATED } ] });
额外说明
- 使用
InterfaceVpcEndpointService.fromAwsService替代手动拼接服务名,避免拼写错误,同时符合CDK最佳实践。 - S3网关端点不需要安全组,它通过路由表控制访问,只需关联目标子网的路由表即可。
内容的提问来源于stack exchange,提问作者deid
相关产品推荐
相关产品推荐

