Friday, October 25

How to setup Lambda Function in VPC to access internet

AWS Lambda functions are great for anyone who is creating a full-blown serverless system or simply want to offload small computational tasks without worrying too much about infrastructure. For reasons of security, accessing to VPC resources, or just for fun, some of us would like to put our Lambda functions in a Virtual Private Cloud (VPC). The first thing you would notice as soon as you place your function into a VPC is that AWS immediately gives you a warning message about losing access to the Internet. Here is the full message:

"When you enable a VPC, your Lambda function loses default internet access. If you require external internet access for your function, make sure that your security group allows outbound connections and that your VPC has a NAT gateway."

But unfortunately, AWS did not provide much detail on how to configure the NAT gateway in order for your functions to access the internet. AWS knowledge center has a nice video by Kien on how the setup can be done; you can find the video here:

However, if you are like me who has no patience of sitting through watching a video of screen capture on how to set up this step-by-step then this guide is for you 😉

The setup is pretty standard and can be most easily illustrated with a diagram. 

This setup requires 3 different subnets in your VPC - Public Subnet, Private Subnet A, and Private Subnet B. Public Subnet has both an Internet Gateway as well as a NAT Gateway assigned to it as illustrated in the diagram. The NAT gateway will also require an Elastic IP, and this Elastic IP will be the source public IP for all traffic coming from your Lambda functions; it is especially handy if you need to use IP whitelisting for external services. 

The two private subnets A and B should be created in different availability zones for high availability. This is a recommended practice though not mandatory; your Lambda function will work even if there is only one private subnet. You should only place your Lambda function in private subnets never the public one. 

Finally, we then need two routing tables in this setup one for privates subnets and another for the public subnet. The private routing table should route all traffic (with mask to the NAT gateway while the public routing table should route all traffic (with mask to the Internet gateway. 

Now you have it; at this point, all your Lambda function in your VPC should have access to the Internet. Have fun!