Anthony
Anthony

Reputation: 1714

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

When creating a FargateService using the AWS CDK, I'm getting the following error:

subnets can have at most 16 items.

I have this code to create the service:

 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,
    }
});

Can the subnets be filtered?

Alternatively, the SubnetSelection class has a SubnetGroup property - I know some AWS services allow the creation of a subnet group, but I can't see how to create an arbitrary subnet group to use for the Fargate services.

Update I now only have 15 subnets in the VPC but I still get the same error message.

Upvotes: 2

Views: 2320

Answers (1)

jogold
jogold

Reputation: 7397

If you are importing an existing VPC you can solve this by importing a subset of your subnets by using ec2.Vpc.fromVpcAttributes() instead of using 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']
});

With this, from you CDK application's point of view, your VPC will only have 3 public subnets.

Upvotes: 5

Related Questions