Ghost9
Ghost9

Reputation: 70

Find running ec2 instances in all regions using python

I want to find all the running instances of Ec2 machines in all the regions.

I've tried executing the following code.

import boto3

def lambda_handler(event,context):
    regions=['us-east-1','ap-south-1']
    for j in regions:    
        ec2client = boto3.client('ec2',region_name=j)
        response = ec2client.describe_instances()
        for reservation in response["Reservations"]:
            for instance in reservation["Instances"]:
                if instance['State']['Name'] == 'running':
                    print(instance["InstanceId"])

The code only executes for the first region in the list 'us-east-1' and returns the running instance but gives the following error for the next region.

"errorMessage:" Task timed out after 3.00 seconds

Upvotes: 1

Views: 2604

Answers (1)

Julien Simon
Julien Simon

Reputation: 2719

It's look like you're running this code inside a Lambda function. The default timeout is 3 seconds, so you simply need to increase this value, either in the AWS console or programmatically:

aws lambda update-function-configuration --function-name my-function --timeout <seconds>

More info at https://docs.aws.amazon.com/lambda/latest/dg/resource-model.html

Upvotes: 2

Related Questions