Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout while starting an EC2 instance from AWS Lambda using boto3

I want to allow users to start an EC2 instance only when it is needed.

So I created a Lambda function to do just that:

import boto3

def lambda_handler(event, context):
    ec2 = boto3.resource('ec2', region_name='eu-central-1')
    return ec2.instances.filter(InstanceIds=['i-abc123']).start()

I've also added the following IAM permissions:

    {
        "Effect": "Allow",
        "Action": [
            "ec2:StartInstances"
        ],
        "Resource": "arn:aws:ec2:*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "ec2:DescribeInstances"
        ],
        "Resource": "*"
    }

Problem is that when I execute the Lambda I get timed out.

BTW running the exact same code from an EC2 within the same VPC and same permissions, returns immediately.

Any idea?

like image 820
Michael Avatar asked Oct 19 '22 10:10

Michael


1 Answers

If credentials were the problem, you would not get timeouts. More likely, you're using a small memory model, and boto takes lots of memory, even to do simple things. Try running with a larger memory model or longer timeout.

If this does turn out to be the issue, consider creating the ec2 resource in class initialization code or using a singleton pattern, so that subsequent invocations can use the same resource. However, be sure to set the function timeout so that it has enough time to do initialization as well as its normal duties, even if that doesn't seem to be necessary. If your function gets an error, the next run may include class init time.

like image 106
Jeff Learman Avatar answered Oct 21 '22 21:10

Jeff Learman