'Create VPC endpoint for S3 bucket lambda access using AWS CDK

I am building a system using Python flavored AWS CDK.

I have a lambda function with an attached EFS. To use EFS, I am required to put the lambda function inside a VPC. The problem is, I also want this lambda function to retrieve files from a particular S3 bucket (in the same region). I am getting Timeout errors when doing the retrieval, and upon some research it seems that I need either a NAT Gateway (too expensive) or a VPC endpoint to allow access.

How can I build a VPC endpoint in CDK to allow my lambda function to talk to my S3 bucket?



Solution 1:[1]

Edit: The comment below from @gshpychka is correct - only the gateway_endpoint in the vpc definition is required.

Here is what I came up with that seems to work after following the ideas in this guide.

You need to create both an S3 access point as well as a VPC Endpoint.

You make the VPC Endpoint when creating the VPC. This allows S3 buckets to be accessible from the VPC. You can later add a policy to restrict this access.

self.vpc = ec2.Vpc(
    scope=self,
    id="VPC",
    vpc_name="my_VPC",
    gateway_endpoints={
        "s3": ec2.GatewayVpcEndpointOptions(
            service=ec2.GatewayVpcEndpointAwsService.S3
        )
    },
    nat_gateways=0,
)

You later create an S3 access point after creating the S3 bucket. This allows access to the bucket.

self.bucket_access = s3.CfnAccessPoint(
    scope=self,
    id="s3_access",
    bucket=self.my_bucket.bucket_name,
    name="bucket-access-point",
    vpc_configuration=s3.CfnAccessPoint.VpcConfigurationProperty(
        vpc_id=self.vpc.vpc_id
    ),
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1