85

I've followed the tutorial here to create a VPC with public and private subnets.

Then I set up an AWS lambda function inside the public subnet to test if it could connect to the outside internet.

Here's my lambda function written in python3

import requests

def lambda_handler(event, context):
    r = requests.get('http://www.google.com')
    print(r)

The function above failed to fetch the content of http://www.google.com when I set it inside the public subnet in a VPC.

Here's the error message:

"errorMessage": "HTTPConnectionPool(host='www.google.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 110] Connection timed out',))", "errorType": "ConnectionError",

I don't understand why.

The route table of the public subnet looks like this:

enter image description here

The GET request to http://www.google.com should match igw-XXXXXXXXX target. Why can't the internet-gateway(igw) deliver the request to http://www.google.com and get back the website content?

This article says that I must set the lambda function inside the private subnet in order to have internet access.

If your Lambda function needs to access private VPC resources (for example, an Amazon RDS DB instance or Amazon EC2 instance), you must associate the function with a VPC. If your function also requires internet access (for example, to reach a public AWS service endpoint), your function must use a NAT gateway or instance.

But it doesn't explain why I can't set the lambda function inside the public subnet.

Brian
  • 12,145
  • 20
  • 90
  • 153
  • What does the Lambda logs in Cloudwatch say? Assume you have included requests modules with your deployment package? Could it be NACL preventing outbound traffic? – toringe Oct 25 '18 at 16:52
  • Do you actually need to deploy the Lambda function into a VPC? – jarmod Oct 25 '18 at 17:10
  • 2
    You need to setup a NAT gateway https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html – kichik Oct 25 '18 at 18:04

3 Answers3

193

Lambda functions connected to a VPC public subnet cannot typically** access the internet.

To access the internet from a public subnet you need a public IP or you need to route via a NAT that itself has a public IP. You also need an Internet Gateway (IGW). However:

  1. Lambda functions do not, and cannot, have public IP addresses, and
  2. the default route target in a VPC public subnet is the IGW, not a NAT

So, because the Lambda function only has a private IP and its traffic is routed to the IGW rather than to a NAT, all packets to the internet from the Lambda function will be dropped at the IGW.

** there is an alleged workaround whereby an Elastic IP can be associated with the Lambda function's ENI. See this post for more details and, importantly, some potentially significant limitations.

Should I Configure my Lambda Function for VPC Access?

If your Lambda function does not need to reach private resources inside your VPC (e.g. an RDS database or Elasticsearch cluster) then do not configure the Lambda function to connect to the VPC.

If your Lambda function does need to reach private resources inside your VPC, then configure the Lambda function to connect to private subnets (and only private subnets).

NAT or Not?

If the Lambda function only needs access to resources in the VPC (e.g. an RDS database in a private subnet) then you don't need to route through NAT.

If the Lambda function only needs access to resources in the VPC and access to AWS services that are all available via private VPC Endpoint then you don't need to route through NAT. Use VPC Endpoints.

If your Lambda function needs to reach endpoints on the internet then ensure a default route from the Lambda function's private subnets to a NAT instance or NAT Gateway in a public subnet. And configure an IGW, if needed, without which internet access is not possible.

Be aware that NAT gateway charges per hour and per GB processed so it's worth understanding how to reduce data transfer costs for NAT gateway.

Best Practices

When configuring Lambda functions for VPC access, it is an HA best practice to configure multiple (private) subnets across different Availability Zones (AZs).

Intermittent Connectivity

Be sure that all the subnets you configure for your Lambda function are private subnets. It is a common mistake to configure, for example, 1 private subnet and 1 public subnet. This will result in your Lambda function working OK sometimes and failing at other times without any obvious cause.

For example, the Lambda function may succeed 5 times in a row, and then fail with a timeout (being unable to access some internet resource or AWS service). This happens because the first launch was in a private subnet, launches 2-5 reused the same Lambda function execution environment in the same private subnet (the so-called "warm start"), and then launch 6 was a "cold start" where the AWS Lambda service deployed the Lambda function in a public subnet where the Lambda function has no route to the internet.

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • 2
    Is there a reason why you advise to run the lambda in a private subnet? Any drawbacks vs running it on a public one? – LLL Dec 12 '19 at 18:25
  • 5
    @LLL stepping back, you run Lambda functions in a VPC if you *need* them to run there, e.g. because they need to access private resources such as a MySQL DB inside the VPC or an S3 bucket restricts access to a specific VPC via private endpoint. The drawback of running in VPC is cold start latency is higher than when not run in VPC (because an ENI must be attached). The difference between public and private subnets is routing (what the 0.0.0.0/0 default route points to, IGW or NAT). If your Lambda needs outbound access then it won't work in a public subnet, because the default route is the IGW. – jarmod Dec 12 '19 at 18:45
  • 4
    Thanks! I didn't realize that only private subnets can have a NAT GW, so it makes perfect sense. BTW while going this rabbit hole I also found out that you actually CAN have a lambda access the internet from a public subnet, but an elastic IP needs to be attached to its ENI. I know it's silly but it's nice to know. – LLL Dec 12 '19 at 18:52
  • @LLL You're welcome. My understanding is that, while you technically can do that, you probably shouldn't. See https://stackoverflow.com/questions/55771064/how-to-choose-elastic-ip-when-my-aws-lambda-function-execute – jarmod Dec 12 '19 at 18:59
  • Nice! I was wondering how concurrency would be handled using that solution and that explains it - it wouldn't. Thanks again! – LLL Dec 12 '19 at 19:02
  • 3
    And it all changes again. AWS have listened regarding the cold start and ENI consumption issues and now support Hyperplain for Lambda, you still have to add the appropriate IAM permissions extra, but it looks like significant improvements : https://aws.amazon.com/blogs/compute/announcing-improved-vpc-networking-for-aws-lambda-functions/ – Aardvark Feb 01 '20 at 02:52
  • I'm not a networking person, but why doesn't AWS do NATing for instances without public IP? https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html – Ganesh Satpute Aug 05 '20 at 13:30
  • @GaneshSatpute AWS offers a managed NAT Gateway option and there are NAT instance options, so you can pro-actively choose NAT if it makes sense for your application (though it would only operate for instances in private subnets because of the earlier default routing constraint). Many customers need to prevent their compute instances from routing to the internet so it’s not the default. Plus NAT has a charge. – jarmod Aug 05 '20 at 13:54
  • 1
    In case your lambda (inside vpc) is accessing specific resources like SSM, you can create a VPC endpoint instead of a NAT gateway. – Santhos Ramalingam Dec 16 '20 at 06:34
  • 2
    Technically the public/private subnet + NAT solution is great. But the NAT Gateway is quiet expensive. That's why I would like to avoid it! – Robert Reiz Jan 04 '21 at 10:11
  • 1
    @RobertReiz yes, NAT gateway charges per hour and per GB processed so it's worth understanding [how to reduce data transfer costs for NAT gateway](https://aws.amazon.com/premiumsupport/knowledge-center/vpc-reduce-nat-gateway-transfer-costs/). – jarmod Feb 22 '21 at 13:20
  • If the lambda has to connect to dynamo and external api.. then should be assign it to both a private subnet and a public subnet? – Karthick Selvam Sep 30 '21 at 04:52
  • 1
    @KarthickSelvam No, don't do that. Such a Lambda function fundamentally needs a network route to both DynamoDB and to the external API. Neither of these intrinsically requires the Lambda to be connected to your VPC at all. If, however, the Lambda function is connected to your VPC (for compliance reasons or because it also needs to access private resources in your VPC e.g. RDS) then the Lambda should be in a private subnet. Your route to DynamoDB is then via VPC Endpoint (if you need that) or NAT, and your route to the external API is via NAT. – jarmod Sep 30 '21 at 14:49
15

You can make a lambda function access the public internet from within your VPC. Solution A is the actual answer, Solution B is a more elegant alternative solution.


Solution A - Lambda in VPC + Public IP associated with ENI

For accessing resources external to AWS such as Google API (like OP's example) you do need a Public IP. For other cases like RDS or S3 you don't need a Public IP, you can use a VPC Endpoint, so communication between your Lambda and the desired AWS Service doesn't leave AWS network.

By default some AWS Services are indeed reached via public internet, but it doesn't have to be.

Now if you want an actual external resource (e.g. google), you need to assign Elastic Public IPs to the Network Interfaces for each subnet linked to your lambda. First let's figure which subnets and security groups are linked to your lambda:

Lambda screen

Next, go to EC2 Service, find the Public IPs menu under Network & Security. Allocate one IP for each subnet (in the example above there are two subnets).

Go to Network Interfaces menu, find the network interfaces attached to your lambda (same subnet and security group).

Network Interfaces

Associate the Public IPs in the actions menu for each one:

Actions menu

Associate IP

That's it, now your Lambda can reach out to public internet.

[EDIT] Someone was concerned about Solution's A scalability issues saying each lambda instance has a new network interface but they missed this from AWS Docs:

"Multiple Lambda functions can share a network interface, if the functions share the same subnet and security group"

So whatever scalability issues you may face has nothing to do with this solution and how Lambda uses ENI, you'd face the same issues using EC2, ECS, EKS, not just Lambda.


Solution B - Decompose into multiple Lambdas

Requiring access both to external resources and VPC resources would seem like too much responsibility for a single function. You may want to rethink your design and decompose your single lambda function into at least two lambda functions:

  • Lambda A goes to external resources (e.g. Google API), fetches whatever data you need, add to SQS. No need to attach to VPC, no need to manually associate Elastic Public IP to ENI.
  • Lambda B processes the message from SQS, stores results to a storage (db, s3, efs, another queue, etc). This one lives within your VPC, and don't need external access.

This way seems more scalable, more secure, each individual lambda is less complex and more maintainable, the architecture looks better overall.

Of course life is not always rainbows and butterflies, so Solution A is good and scalable enough, but improving the architecture is even better.

Alisson Reinaldo Silva
  • 10,009
  • 5
  • 65
  • 83
  • 1
    Does someone know when AWS allowed this? I'm finding lots of "doesn't work" material (which is old) but I also saw that this works now (at least for some time >=2021) – Augunrik Jan 13 '23 at 07:42
  • 1
    I think this method does not work reliably with lambdas as when it scales, each lambda instance has a new network interface. So while you can do this, it's not going to work when you scale out. – Capaj Jan 16 '23 at 10:39
  • @Capaj [from AWS docs](https://docs.aws.amazon.com/lambda/latest/dg/foundation-networking.html): _"Multiple Lambda functions can share a network interface, if the functions share the same subnet and security group"_. Also you must have a Public IP for reaching Public Internet, regardless of it being a Lambda, EC2, ECS, even a NAT Gateway needs an Elastic Public IP if you want to reach the public internet through it. – Alisson Reinaldo Silva Jan 16 '23 at 19:47
  • This indeed works for me. And instead of having NAT gateway which is expensive, this sounds good to me. But i hope there won't be any issues if we scale. – Veer Feb 21 '23 at 15:14
  • @Veer you'd only explicitly attach a VPC to your lambda if you need to access resources inside it. You'd also only need a Public IP (via NAT or ENI) if you need external resources (outside AWS). One way to improve things even more is trying to decompose your lambda into two smaller lambdas, one that gets access to external resources, another for VPC resources. e.g. lambda A gets data from external API, adds output to SQS, lambda B processes the message, store to database. I'll update my answer with this suggestion. – Alisson Reinaldo Silva Feb 21 '23 at 22:33
  • I have been developing a 'test' Lambda function which needs to connect to my local environment. I thought I would have to temporarily create a NAT Gateway each time I needed to work on it, then destroy the NAT Gateway when I was done. Solution A is much better! But in the Associate form, why was there only one Elastic IP and one private address that I could select? – ScottyB Mar 01 '23 at 22:09
  • @ScottyB sorry for the late response. I think the UI only shows Public IPs not associated with any other resources (e.g. available IPs). As for the Private Address, I'd suspect you only had one ENI because your Lambda spams only one Availability Zone, hence there was only one Private IP to be linked to. – Alisson Reinaldo Silva Jul 03 '23 at 12:44
0

A bit late, but nonetheless. @jarmod answer is correct but I'd like to develop further on it. The explanation for the inability of a Lambda function linked to a public subnet to access the Internet is as follows:

Lambda functions operate within an AWS-managed Virtual Private Cloud (VPC). When you establish a "connection" between the Lambda function and your designated VPC, an Elastic Network Interface (ENI), specifically a Hyperplane ENI, is generated within the chosen subnets for Lambda's execution. This ENI assumes a "private" IP, directing all of the Lambda function's network traffic through it. Yet, why is a public IP not assigned to it???

This is because of how public IP assignment within AWS works. The configuration of a public IP for an EC2 instance doesn't reside within the instance itself; rather, it's orchestrated through Network Address Translation (NAT) within the Internet Gateway (IGW). Therefore, deploying an EC2 instance within a public subnet doesn't guarantee automatic possession of a public IP. This also applies to Lambda functions as well, but unlike EC2 instances, Lambdas lack the capacity for manual public IP assignment.

Hope it helps.

Andres Bores
  • 212
  • 1
  • 14