aws-cdkaws-cdk-typescript

Building aws cdk-stack get 'Error: Cannot create a VPC Endpoint with no subnets'


I'm creating an AWS CDK stack (2.66.1) in which I have to define 2 VPC endpoints.

I defined all the resource necessary to my app but when I try to build it with 'cdk synth', it doesn't: Error: Cannot create a VPC Endpoint with no subnets

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"
    );

    new ec2.InterfaceVpcEndpoint(this, env.vpcEndpointDynamoDBName, {
      vpc,
      service: new ec2.InterfaceVpcEndpointService('com.amazonaws.' + region + '.dynamodb', 443),
      subnets: {
        subnets: [...vpc.privateSubnets]
      },
      privateDnsEnabled: true,
      securityGroups: [securityGroup]
    });


    new ec2.InterfaceVpcEndpoint(this, env.vpcEndpoints3Name, {
      vpc,
      service: new ec2.InterfaceVpcEndpointService('com.amazonaws.' + region + '.s3', 443),
      subnets: {
        subnets: [...vpc.privateSubnets]
      },
      privateDnsEnabled: true,
      securityGroups: [securityGroup]
    });

Solution

  • You are passing vpc.privateSubnets as the interface endpoint subnets, but this attribute is undefined. Your VPC defines a single PRIVATE_ISOLATED subnet, which is available as vpc.isolatedSubnets.

      subnets: {
        subnets: vpc.isolatedSubnets
      },
    

    Here's how the VPC subnet attributes map to SubnetType values (source):


    BTW, you are creating interface endpoints for DynamoDB and S3. Consider Gateway Endpoints instead. Gateway Endpoints are supported for DynamoDB and S3 and carry no hourly charge. See the Types of VPC endpoints for Amazon S3 docs for a comparison.