ec2_list_instances

List EC2 instances using Python and boto3. Quickly retrieve instance IDs, types, and IPs. Free, easy-to-use AWS instance listing tool.

EC2 List Instances

Use this tool to list your EC2 instances in AWS using Python and the boto3 library. This script filters instances based on their state (running) and a tag key (my-instance-group-name), then prints their ID, instance type, and private IP address.

import boto3

profile_name = ''
region_name = ''

ec2 = boto3.Session(profile_name=profile_name, region_name=region_name).client('ec2')
instances = ec2.instances.filter(
    Filters=[
        {'Name': 'instance-state-name', 'Values': ['running']},
        {'Name': 'tag-key', 'Values': ['my-instance-group-name']}
    ]
)

for instance in instances:
    print(instance.id, instance.instance_type, instance.private_ip_address)

Explanation

This Python script uses the boto3 library to interact with Amazon Web Services (AWS). It lists EC2 instances based on specified filters. Here's a breakdown:

  • boto3: The AWS SDK for Python, allowing you to write Python code that interacts with AWS services like EC2.
  • Session: Creates a session to manage AWS credentials and region. profile_name and region_name should be configured in your AWS CLI.
  • EC2 Client: Creates an EC2 client object, which allows you to call EC2 APIs.
  • Filtering Instances: Filters EC2 instances that are in the 'running' state and have a specific tag key ('my-instance-group-name').
  • Looping Through Instances: Iterates through the filtered instances and prints their ID, instance type, and private IP address.

Related Resources