In this post I have added my experience of working with lambda function in a VPC.
When I was debugging the aws lambda functions locally it was running properly and was able to make API calls to outside resources.
I was using AWS SAM cli to debug lambda function, which spins up a docker image and runs lambda function inside it.
But when I deployed lambda function to aws and associated it with a VPC, It was not able to call outside internet. All the calls to outside APIs were timed out. Then I researched a bit about this and found out its because how lambda functions work.
Lambda function can not access internet when attached to a public subnet of your VPC, because Lambda functions do not have public IP addresses. You cannot send traffic to the internet, which happens via the VPC's Internet Gateway, unless you have a public IP.
The way to access the internet is to route traffic through a NAT. NAT gateway has an elastic network interface (i.e. an IP address). So NAT gateway can forward traffic to internet gateway and allow access to outside internet.
Steps to be followed are,
Now your lambda function can access outside internet.
Below diagram shows this setup. Lambda function can access SNS APIs, as traffic is routed through NAT and then internet gateway.
Read more about the solution in this aws article