7
votes

I have a simple lambda function as follows

var AWS = require("aws-sdk");

exports.handler = (event, context, callback) => {

var ec2 = new AWS.EC2({region:'us-east-1'});
return ec2.describeRegions({}).promise()
.then(function(regionResponse) {
    console.log(regionResponse.Regions)
    callback(null, regionResponse.Regions);
})
.catch(
    function (err) {
        console.log({"error" : err});
        callback(err, null);
    }
)

};

I can run this function outside of a VPC successfully.

I create a VPC using the VPC wizard and create a VPC with a single public subnet and an Internet Gateway. I place the function in the VPC and give it an execution role with Lambda VPC Execution rights. It now fails with a timeout, which I have set to 10 seconds (normal execution 1 sec)

What am I missing from my config that prevents the function from accessing the AWS SDK inside the VPC?

1
This question gets asked on here at least once a week. Please view the answers to some of the other questions like these: stackoverflow.com/questions/38188532/… stackoverflow.com/questions/35423246/…Mark B
@MarkB the fact that this gets asked so often just goes to show that it needs a proper documented use case or examples provided by Amazon. I have been down these routes before with these other answers so I may have missed something or made a mess of something. I will start again and see if I can get some successajmcgarry
AWS has documented this in lots of places, like here: docs.aws.amazon.com/lambda/latest/dg/vpc.html and the official Lambda VPC announcement here: aws.amazon.com/blogs/aws/… What specifically do you want from them that they aren't providing you? Anyway, that's feedback you need to be providing Amazon instead of posting it here where they will never see it.Mark B
Also, I'm not seeing anything in your posted code that needs to be running inside a VPC. If you just remove the Lambda function from the VPC it will be able to access the AWS API.Mark B
@MarkB the code I posted is just an example I took from a larger application built using the Serverless framework with a NodeJS ExpressJS API fronted by API Gateway.ajmcgarry

1 Answers

0
votes
  1. You are putting callback after return statement. Of course it will never be executed because you returned from the function.

  2. If the subnet you are running the Lambda is not public or does not have NAT Gateway, it won't be able to connect to Internet, thus to AWS API's.