Recently, one of my friend/client came up with the scenario below.
- There is a lambda function, which calls to a external API and fetch some data.
- This external API only accepts incoming requests only from pre-configured whitelisted IPs.
As per today, AWS doesnt’ support elastic IPs for Lambda. However, there is a simple work around.
Simple solution is, to create the lambda function within a VPC and make the 3rd party API to be accessible via a NAT gateway.
You may use a NAT instance as well, but as a best practice, it is recommended to use NAT Gateway wherever possible, unless there is a specific reason to use NAT instance. Find the comparison between NAT instance vs NAT Gateway here.
This is the simplest version of the network diagram how you can set up this. As NAT Gateway has Elastic IP assigned, all the traffic from Lambda function to the External API will have the same IP of the NAT Gateway. So, we can whitelist the NAT Gateway’s public IP at the external API.
Below is the VPC configuration settings that is required to set up within the Lambda function. You need to choose the VPC, sub nets you need to use Lambda function and the security groups (for access control) as below.
Please note: As highlighted in the above image, once the Lambda function is inside the VPC, it loses the internet connectivity. You have to explicitly configure internet access within the VPC (in this scenario using a NAT Gateway).