You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建AWS CDK Stack时遇'Error: Cannot create a VPC Endpoint with no subnets'错误

问题分析与解决

错误原因

  1. 子网引用错误:你的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错误。
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:07:54