DEV Community

Cover image for How to Retrieve EC2 Instances Information Using Python and Boto3
Dmitry Romanoff
Dmitry Romanoff

Posted on

How to Retrieve EC2 Instances Information Using Python and Boto3

If you're working with AWS (Amazon Web Services), it's likely that you'll need to interact with your EC2 (Elastic Compute Cloud) instances regularly. Whether you're managing a large fleet of virtual machines or automating some of your infrastructure tasks, retrieving EC2 instance details programmatically can save you a lot of time.

In this article, we'll walk through how to use Python with the Boto3 SDK to retrieve and print details of your EC2 instances in a specific AWS region. Boto3 is AWS's SDK for Python, and it provides an easy-to-use API for interacting with AWS services.

Prerequisites

Before we dive into the code, here are a few things you'll need:

  1. AWS Account: You'll need an active AWS account and EC2 instances running in a specific region.
  2. AWS CLI or SDK Configured: You should have your AWS credentials set up. You can use the AWS CLI to configure these credentials, or directly set them in your code (not recommended for production environments).
  3. Boto3 Library: You need to have Boto3 installed in your Python environment. Install it with the following command if you don't have it already:
   pip install boto3
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

The code snippet below demonstrates how to retrieve and display details about EC2 instances in the us-east-1 region using Python and Boto3.

import boto3

def get_ec2_instances():
    # Create EC2 client for us-east-1 region
    ec2_client = boto3.client('ec2', region_name='us-east-1')

    try:
        # Get all instances
        response = ec2_client.describe_instances()

        # List to store instance details
        instance_details = []

        # Iterate through reservations and instances
        for reservation in response['Reservations']:
            for instance in reservation['Instances']:
                # Get instance type
                instance_type = instance['InstanceType']

                # Get instance name from tags if it exists
                instance_name = 'N/A'
                if 'Tags' in instance:
                    for tag in instance['Tags']:
                        if tag['Key'] == 'Name':
                            instance_name = tag['Value']
                            break

                # Get instance ID
                instance_id = instance['InstanceId']

                # Get instance state
                instance_state = instance['State']['Name']

                # Add instance details to list
                instance_details.append({
                    'Instance ID': instance_id,
                    'Name': instance_name,
                    'Type': instance_type,
                    'State': instance_state
                })

        # Print instance details
        if instance_details:
            print("\nEC2 Instances in us-east-1:")
            print("-" * 80)
            for instance in instance_details:
                print(f"Instance ID: {instance['Instance ID']}")
                print(f"Name: {instance['Name']}")
                print(f"Type: {instance['Type']}")
                print(f"State: {instance['State']}")
                print("-" * 80)
        else:
            print("No EC2 instances found in us-east-1 region")

    except Exception as e:
        print(f"Error retrieving EC2 instances: {str(e)}")

if __name__ == "__main__":
    get_ec2_instances()
Enter fullscreen mode Exit fullscreen mode

Explanation of the Code

  1. Creating an EC2 Client:
   ec2_client = boto3.client('ec2', region_name='us-east-1')
Enter fullscreen mode Exit fullscreen mode

The first step is to create a Boto3 EC2 client. Here we specify the region us-east-1, but you can change this to any AWS region where your EC2 instances are running.

  1. Getting EC2 Instances:
   response = ec2_client.describe_instances()
Enter fullscreen mode Exit fullscreen mode

The describe_instances() method retrieves information about all EC2 instances in the specified region. The response contains detailed information about the instances, including their ID, type, state, and tags.

  1. Extracting Instance Details: The returned response contains a list of "reservations," each containing "instances." For each instance, we extract useful information:
    • Instance ID: Unique identifier of the instance.
    • Name: The instance's name tag (if available).
    • Type: The EC2 instance type (e.g., t2.micro, m5.large).
    • State: The current state of the instance (e.g., running, stopped).

We then store these details in a list called instance_details.

  1. Handling Tags:
   if 'Tags' in instance:
       for tag in instance['Tags']:
           if tag['Key'] == 'Name':
               instance_name = tag['Value']
               break
Enter fullscreen mode Exit fullscreen mode

EC2 instances can have tags, including a Name tag that is often used to identify instances. If a Name tag exists, we extract its value. If not, we set the instance name to 'N/A'.

  1. Displaying the Results:
    After gathering all the instance details, the code prints them in a readable format. If no instances are found, it will print a message indicating that.

  2. Error Handling:
    The entire process is wrapped in a try-except block to handle any exceptions that might occur, such as network issues or insufficient permissions.

Running the Script

To run the script, simply execute it in your Python environment. If everything is set up correctly, you will see a list of EC2 instances in the us-east-1 region, showing their ID, name, type, and state.

Example Output:

EC2 Instances in us-east-1:
--------------------------------------------------------------------------------
Instance ID: i-0123456789abcdef0
Name: MyFirstInstance
Type: t2.micro
State: running
--------------------------------------------------------------------------------
Instance ID: i-0987654321fedcba0
Name: N/A
Type: m5.large
State: stopped
--------------------------------------------------------------------------------
Enter fullscreen mode Exit fullscreen mode

Conclusion

This simple script is an excellent starting point for interacting with AWS EC2 instances using Python and Boto3. With just a few lines of code, you can retrieve crucial information about your EC2 instances, automate monitoring tasks, or even integrate this functionality into larger infrastructure management tools.

You can extend this script to:

  • Filter instances based on certain tags or states.
  • Start, stop, or terminate instances programmatically.
  • Collect additional details such as public IP addresses, security groups, and more.

The power of Boto3 and Python allows you to automate a wide range of AWS tasks efficiently.

Top comments (0)