DEV Community

Cover image for Scan over all Regions to find out which EC2 instance is running
Vuong Bach Doan
Vuong Bach Doan

Posted on

3 2 2 2 2

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

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 ✨

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay