Scan over all Regions to find out which EC2 instance is running

Vuong Bach Doan - Jan 11 - - Dev Community

When using the AWS console, depending on the situation, we may use resources in different regions.

However, using resources in multiple regions can make it difficult to manage. For example, you might start an EC2 instance in us-east-1, but then switch to us-west-2 for your work. Over time, you might forget about the instance you started in us-east-1, which could lead to unexpected billing charges at the end of the month.

To check which EC2 instances are running in a specific region without having to check each region individually, or you don't want to wait until AWS Budget alarm notify you, you can use the following method.

Idea:

Step 1: List all regions that support EC2.
Step 2: Use the describe_regions() API call to find EC2 instances in each region.
Step 3: Check the status of each instance.

Code snippet:

import boto3

def get_ec2_instances(type=['pending', 'running', 'shutting-down', 'terminated', 'stopping', 'stopped']):
    ec2 = boto3.client('ec2')

    # List all regions that support EC2
    response = ec2.describe_regions()

    print('Checking EC2 instances ')

    # Loop through each region
    for region in response['Regions']:
        # Print the region name
        print(' -', region['RegionName'])

        # Get all instances in the region
        instances = boto3.resource('ec2', region_name=region['RegionName']).instances.all()

        # Loop through each instance
        for instance in instances:
            # Check the instance status
            if instance.state['Name'] in type:
                print('⚠️ Warning: ', instance.id)

Enter fullscreen mode Exit fullscreen mode

Now, you can try and check did you forget any instance ✨

. . . . . . . . . . . . . . .