


Introduction
A NAT Gateway is a feature used in AWS VPC setups to allow resources within a private subnet to access the internet or other external resources while keeping those resources secure from inbound internet traffic. Although using a NAT Gateway seems quite practical, the monthly cost of running a NAT Gateway per VPC is around 30 dollars without any data transfer cost. In a three-stage environment consisting of development, testing, and production, the monthly cost can exceed $90. In our application, we wanted to keep our Lambda function secure within the VPC while simultaneously performing operations on Cognito and S3, which are outside the VPC. The common method to achieve this is by creating a NAT Gateway, which incurs significant costs.
This article describes how to connect a Lambda function in a private subnet to a Cognito and S3 service outside the VPC using IPv6, which is a free service.
If you are trying to connect to other AWS services, please check the following doc to see which services support IPv6:
https://docs.aws.amazon.com/vpc/latest/userguide/aws-ipv6-support.html
Step 1: Create VPC
When creating this VPC, we need two subnets. One is a public subnet, and the other is a private with egress subnet. The private with egress subnet allows the Lambda function to access resources outside the VPC while blocking incoming connections. We will connect to the Lambda function through API Gateway.
Don't forget to enable the `ipv6AssignAddressOnCreation` feature. This setting ensures that IPv6 addresses are assigned to the subnets when they are created.
//VPC
let vpc = new ec2.Vpc(this, "cdk-vpc", {
ipProtocol: ec2.IpProtocol.DUAL_STACK, // So that it supports both ipv4 and ipv6.
natGateways: 0, // If you don’t set this as 0, AWS will automatically create Nat Gateways!
subnetConfiguration: [
{
name: "public",
cidrMask: 22,
ipv6AssignAddressOnCreation: true, // Important! This setting ensures that IPv6 addresses are assigned to the subnets when they are created.
subnetType: ec2.SubnetType.PUBLIC
},
{
name: "private",
cidrMask: 24,
ipv6AssignAddressOnCreation: true, // Important! This setting ensures that IPv6 addresses are assigned to the subnets when they are created.
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS
}
]
});
Step 2: Create Security Group for Lambda
Next, create a security group for the Lambda function. This security group will be used to allow outbound IPv6 connections.
const lambdaSecurityGroup = new ec2.SecurityGroup(this, "LambdaSecurityGroup", {
vpc: this.vpc,
allowAllIpv6Outbound: true
});
Step 3: Create Lambda Function
Create the Lambda function and specify the VPC. Enable the `ipv6AllowedForDualStack` setting to allow operation with IPv6. Configure the subnet and security group according to the previously created resources. Set the subnet to private with an egress type and assign the security group created for the Lambda function.
//LAMBDA FUNCTION
const lambdaFunction = new NodejsFunction(this, "Backend", {
entry: join(__dirname, "../backend/index.ts"),
runtime: Runtime.NODEJS_20_X,
role: lambdaRole,
vpc: this.vpc,
ipv6AllowedForDualStack: true,
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS
},
securityGroups: [lambdaSecurityGroup],
timeout: Duration.seconds(15),
});
Step 4: Create Lambda Role
Grant the necessary VPC permissions to the Lambda execution role.
//IAM LAMBDA ROLE
const lambdaRole = new iam.Role(this, "LambdaRole", {
assumedBy: new iam.ServicePrincipal("lambda.amazonaws.com"),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole")
]
});
Step 5: Add Inline Policies
Assign the roles required for the Lambda function to access S3 and Cognito.
// LAMBDA S3 ACCESS
lambdaFunction.role?.attachInlinePolicy(
new iam.Policy(this, "LambdaS3Access", {
statements: [
new PolicyStatement({
actions: ["s3:*"], // For best practice, add specific actions instead of all.
resources: [uploadedFilesBucket.bucketArn, uploadedFilesBucket.arnForObjects("*")]
})
]
})
);
// LAMBDA COGNITO ACCESS
lambdaFunction.role?.attachInlinePolicy(
new iam.Policy(this, "LambdaCognitoAccess", {
statements: [
new PolicyStatement({
actions: ["cognito-idp:*"], // For best practice, add specific actions instead of all.
resources: [userPool.userPoolArn]
})
]
})
);
Step 6: Configure Lambda Code
For Cognito, no additional configuration is needed, but for S3, you might need to enable the dual-stack setting. Now, you can access S3 and Cognito over IPv6 without a NAT Gateway and perform the desired operations.
const cognito = new CognitoIdentityProviderClient();
export const handler = async (event: any, context: Context) => {
let body;
let statusCode = 200;
let s3 = new S3Client({ useDualstackEndpoint: true });
try {
let req = event.body ? JSON.parse(event.body) : event.queryStringParameters || {};
switch (true) {
case event.path === "/users-in-group" && event.httpMethod === "POST":
body = await cognito.send(
new AdminAddUserToGroupCommand({
UserPoolId: process.env.COGNITO_USERPOOLID,
Username: req.userName,
GroupName: req.groupName
})
);
break;
