如何在超过 16 个子网的 VPC 中使用 AWS CDK 创建 ECS 服务

How do I create an ECS Service using AWS CDK in a VPC with more than 16 subnets

使用 AWS CDK 创建 FargateService 时,出现以下错误:

subnets can have at most 16 items.

我有这个代码来创建服务:

 var ecsService = new FargateService(this, $"{serviceNameHyphen}-service", new FargateServiceProps
 {
    TaskDefinition = taskDefinition,
    AssignPublicIp = false,
    Cluster = infrastructureStack.EcsCluster,
    CloudMapOptions = new CloudMapOptions
    {
          Name = serviceName,
          DnsRecordType = DnsRecordType.A,
          DnsTtl = Duration.Seconds(60),
          FailureThreshold = 2d
    },
    DesiredCount = 1,
    HealthCheckGracePeriod = Duration.Seconds(60),
    MaxHealthyPercent = 200,
    MinHealthyPercent = 100,
    PlatformVersion = FargatePlatformVersion.LATEST,
    ServiceName = $"{serviceNameHyphen}-service",
    SecurityGroup = albSecurityGroup,
    VpcSubnets = new SubnetSelection
    {
         OnePerAz = true,
         SubnetType = SubnetType.PUBLIC,
    }
});

可以过滤子网吗?

或者,SubnetSelection class 有一个 SubnetGroup 属性 - 我知道一些 AWS 服务允许创建子网组,但我看不到如何创建用于 Fargate 服务的任意子网组。

更新 我现在在 VPC 中只有 15 个子网,但我仍然收到相同的错误消息。

如果您要导入现有 VPC,您可以通过使用 ec2.Vpc.fromVpcAttributes() 而不是使用 ec2.Vpc.fromLookup():

导入子网的子集来解决此问题
const vpc = ec2.Vpc.fromVpcAttributes(this, 'Vpc', {
  vpcId: 'vpc-xxxxxxxx',
  availabilityZones: ['eu-west-1a', 'eu-west-1b', 'eu-west-1c'],
  publicSubnetIds: ['subnet-xxxxxxxx', 'subnet-xxxxxxxx', 'subnet-xxxxxxxx'],
  privateSubnetIds: ['subnet-xxxxxxxx', 'subnet-xxxxxxxx', 'subnet-xxxxxxxx']
});

有了这个,从您的 CDK 应用程序的角度来看,您的 VPC 将只有 3 个 public 个子网。