This code snippet will help you to get the list of all running EC2 instances across all regions in an AWS account. I have used python boto3 package for developing the code. This code will dynamically pick up all the aws ec2 regions. So the code will work perfectly without any modification even if a new region gets added to the AWS.

Note: Only the basic api calls just to list the instance details are mentioned in this program . Proper coding conventions are not followed . 🙂


import boto3
access_key = "XXXXXXXXXXXXXXXXXX"
secret_key = "XXXXXXXXXXXXXXXXXX"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,
region_name='us-east-1')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,
region_name=region)
instances = conn.instances.filter()
for instance in instances:
if instance.state["Name"] == "running":
print (instance.id, instance.instance_type, region)

 

Generate the AWS Access Key and Secret Access Key from the AWS console (IAM section). This code will be helpful to quickly find the summary of all the EC2 instances across regions.

Advertisement