LDJ
LDJ

Reputation: 7324

Lambda function not executing http.get

I have a function that when tested locally worked fine, but when running via AWS Lambda doesn't seem to execute the HTTP get. The code is as follows:

function makeAPIRequest(path, responseControl, callback) {

    var responseString = '';
    console.log("Executing makeAPIRequest to " + apiSettings.host + " and path " + path);
    var options = {
        host: apiSettings.host,
        path: path,
        method: 'GET',
        headers: {
            'X-Auth-Token': apiSettings.token
        }
    };
    http.get(options, function (res) {
        console.log('Status Code: ' + res.statusCode);
        if (res.statusCode != 200) {
            callback(new Error("Non 200 Response"));
        }
        res.on('data', function (data) {
            responseString += data;
        });
        res.on('end', function () {
            console.log('http end function hit...');
            callback(null, responseString);
        });
    }).on('error', function (e) {
        console.log("Communications error: " + e.message);
        callback(new Error(e.message));
    });
}

I initially wrote it using the request npm package but that failed, so I dropped back to vanilla http.get, but neither seems to execute. In the log output from Lambda I can see the output of the following:

console.log("Executing makeAPIRequest to " + apiSettings.host + " and path " + path);

with the correct host and path being passed in, but

console.log('Status Code: ' + res.statusCode);

never outputs to the screen. There are no errors logged and the API endpoint that I'm hitting reports the number of API requests, but this isn't changing, so I dont think the request is even being made.

Has anyone got Lambda to make http calls and if so, any ideas on what I'm not doing here?

Thanks

Edit: verified that 'no vpc' is set in the advanced settings section of lambda

Upvotes: 1

Views: 1485

Answers (1)

Mark B
Mark B

Reputation: 201138

I see some variation of this question on here every few days. In almost every case it is because you placed the Lambda function in your VPC. Lambda functions don't get public IP addresses assigned to them inside a VPC, so they don't have access to anything outside the VPC. This results in network calls to resources outside the VPC hanging like what you describe.

The solution is to either move the Lambda function outside of the VPC, or add a NAT gateway to your VPC.

Upvotes: 5

Related Questions