AWS Lambda: Enable Outgoing Internet Access within VPC
After setting up a VPC for an AWS Lambda function, your function will lose access to the internet because network interfaces created by Lambda only have private IP addresses, you will not be able to use an IGW to gain internet access. — AWS
I had some troubles to enable internet access again after I setup a VPC. I tried every tutorial and read every AWS documentation and forum but I was too dumb to set it up correctly with these ressources.
Now I want to share my “trial and error” solution 💪
My initial setup:
I had 1 VPC with 4 public subnets in it:
These 4 subnets had the following rules in Route Tables. Everything gets routed outside to the internet via the IGW (internet gateway)
I have EC2 instances, RDS Databases and ElastiCache in this VPC, splitted into different subnets/Availability Zones.
Setup Lambda function:
I created a Lambda function and set the VPC to “vpc-dvel”, added every subnet and a security group. I need the function to be in the VPC to reach every other service in there like RDS Database and ElastiCache.
But internet access was gone after this change.
Solution:
1. Create 4 new subnets, one in every Availability Zone (or at least 2)
2. Set the 4 new subnets in the Lambda function settings:
3. Create a NAT Gateway in one of your initial VPC subnets with internet access in route table. In my case I chose the “subnet-dvel-001”.
!!! Make sure this subnet has access to the internet via IGW.
Enter or create a new EIP and hit create.
4. Create a Route Table in your VPC.
5. Go to your newly created Route Table and to to the Routes tab. Add a new entry with 0.0.0.0/0 and choose your NAT gateway you created in step 3.
6. Click on Subnet Associations and select your 4 newly created subnets (Step 1) for Lambda.
🎉 Congratulations: Your Lambda function has internet access again!
If you have any questions or need help, don’t hesistate to ask me 😉
Your’s Phil.