AWS Lambda functions with a static IP

Matthew Leak
2 min readNov 7, 2016

--

Internally at Compare52 we build a lot of server-less micro-services on AWS Lambda which is great for running stateless web services in the cloud that don’t need their web servers to be continuously running. AWS Lambda provides easy scaling and high availability to your application code without any effort or responsibility of you managing and provisioning EC2 instances. With Amazon EC2 you are responsible for provisioning capacity, monitoring fleet health and performance, and designing for fault tolerance and scalability.

With AWS Lambda, you pay only for what you use. You are charged based on the number of requests for your functions and the time your code executes. The Lambda free tier includes 1M free requests per month and 400,000 GB-seconds of compute time per month. A no brainer…

The problem

One of our third parties required us to send data received by a client to their API which only accepted requests from whitelisted IP addresses. AWS Lambda is not the same an as EC2 instance as it runs on containers within the AWS infrastructure. Traffic would appear to be coming from certain IP addresses but there is no way to configure which IP address is used meaning that the IP address that the requests are sent from will not be the same.

The solution

AWS Lambda supports executing your code from inside a VPC. With this ability we’re able to create a NAT (Network Address Translator) Gateway so that all out-bound connections from our lambda functions will exit from the NAT which is assigned to a fixed IP address. This fixed IP adress can then be whitelisted by our third-parties.

  1. Create a new VPC to run your code in (or use an existing VPC)
  2. Create a new Internet Gateway to communicate with the Internet from inside your VPC
  3. Create a Public Subnet and add a new route to the route table which routes to your Internet Gateway from 0.0.0.0/0
  4. Create a new Elastic IP address.
  5. Create a new NAT Gateway and assign it to the Public Subnet and Elastic IP address that you just created.
  6. Create a Private Subnet and add a new route to the route table which routes to your NAT Gateway from 0.0.0.0/0

A lambda function can then be created inside your VPC to make a request to the Internet. A simple test can then be to use the request module (in Node.js) to make a request to www.google.com. If the request is successful then we know the request is being successfully NATed. The Elastic IP address that we created earlier can then be added to any external organisations’ IP whitelists.

If you’re interested in how Lambda functions actually work, check out my recent article on just that, or check this out if you’re interested in implementing similar functionality on Azure.

If this article has been useful to you, be sure to leave lots of claps! (you can leave up to 50!)

--

--

Matthew Leak

UK-based Technology Consultant working in London and Manchester.