Timeout on starting an EC2 instance from AWS Lambda using boto3

I want to allow users to start an EC2 instance only when necessary.

So, I created a Lambda function for this:

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 also added the following IAM permissions:

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

The problem is that when I run Lambda I get a timeout.

BTW runs the same code from EC2 within the same VPC and the same permissions, returns immediately.

Any idea?

+5
source share
1 answer

If the credentials were a problem, you won’t get timeouts. Most likely you are using a small memory model, and boto takes up a lot of memory, even for simple things. Try running with a larger memory model or longer timeout.

If this turns out to be a problem, consider creating an ec2 resource in the class initialization code or using a singleton pattern so that subsequent calls can use the same resource. However, do not forget to set the function timeout so that it has enough time for initialization, as well as for its usual duties, even if it does not seem necessary. If your function receives an error message, the next run may include class initialization time.

+2
source

Source: https://habr.com/ru/post/1247954/


All Articles