I’m using an AWS lambda function to connect to the internet. It belongs to a VPC with 1 public subnet and 3 private subnets (3 availability zones) with 2 routes tables (public route for public subnet and private route for private subnets) but when I run the Lambda function, it gives me a timeout. Does anyone know what to do?
import json
import urllib.request
def lambda_handler(event, context):
url = "https://www.google.com"
try:
# Make HTTP GET request
response = urllib.request.urlopen(url)
# Read response data
html = response.read().decode("utf-8")
# Log response
print("Response from", url, ":", html)
return {
'statusCode': 200,
'body': json.dumps('Successfully accessed the internet!')
}
except Exception as e:
# Log error
print("Error:", str(e))
return {
'statusCode': 500,
'body': json.dumps('Failed to access the internet!')
}
2
Answers
If your Lambda function does not need to connect to any resources in the VPC, then simply disconnect the Lambda function from the VPC and it will have full Internet access. That’s all you need to do and it is the cheapest option.
However, if the Lambda function also needs to access resources in the VPC, then you will need this configuration:
0.0.0.0/0
to the NAT GatewayThis way, when the Lambda function wants to access the Internet, the request will be sent via the NAT Gateway.
The default timeout for a lambda function is around 3 seconds. Try updating the timeout from
AWS Management Console -> Configuration -> General Configuration -> Timeout -> Save.
The maximum duration a Lambda function can run is 15 minutes (So set timeout accordingly).
Try to run again and check output.