Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't run ec2 method in AWS Lambda Function

I'm invoking the following lambda function to describe an instance information:

'use strict'

var aws = require('aws-sdk');

exports.handler = function(event, context) {
    var instanceID = JSON.parse(event.Records[0].Sns.Message).Trigger.Dimensions[0].value;

    aws.config.region = 'us-east-1';

    var ec2 = new aws.EC2;

    var params = {InstanceIds: [instanceID]};

    ec2.describeInstances(params, function(e, data) {
        if (e)
            console.log(e, e.stack);
        else
            console.log(data);
    }
};

In CloudWatch Logs I can see that function runs until the end, but doesn't log nothing inside ec2.describeInstances method:

END RequestId: xxxxxxxxxxxxxx REPORT RequestId: xxxxxxxxxxxxxx Duration: xx ms Billed Duration: xx ms Memory Size: xx MB Max Memory Used: xx MB

My lambda function has VPC access and IAM Role of AdministratorAccess (full access). For some reason, it can't run ec2.describeInstances method. What is wrong and how can I fix it?

like image 482
Danilo Avatar asked Jul 01 '26 01:07

Danilo


1 Answers

When you add VPC configuration to a Lambda function, it can only access resources in that VPC. If a Lambda function needs to access both VPC resources and the public Internet, the VPC needs to have a Network Address Translation (NAT) instance inside the VPC. So for that EC2 instance to send logs to cloud watch it needs internet connection through the NAT instance.

AWS Lambda uses the VPC information you provide to set up ENIs that allow your Lambda function to access VPC resources. Each ENI is assigned a private IP address from the IP address range within the Subnets you specify, but is not assigned any public IP addresses. Therefore, if your Lambda function requires Internet access (for example, to access AWS services that don't have VPC endpoints, such as Amazon Cloudwatch), you can configure a NAT instance inside your VPC or you can use the Amazon VPC NAT gateway. For more information, see NAT Gateways in the Amazon VPC User Guide. You cannot use an Internet gateway attached to your VPC, since that requires the ENI to have public IP addresses.

like image 181
error2007s Avatar answered Jul 03 '26 17:07

error2007s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!