EoyB3377yhaASYgc7VOsGet a list of all stopped AWS EC2 Instances
Get a list of all stopped AWS EC2 Instances
This task involves fetching all stopped AWS EC2 instances, facilitating management and analysis of inactive resources for operational optimization.
Note: region_name = None, fetches the results from all regions.
inputs
outputs
import boto3
from botocore.exceptions import NoCredentialsError, PartialCredentialsError, BotoCoreError, ClientError
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def list_all_regions():
ec2 = boto3.client('ec2',aws_access_key_id=access_key,aws_secret_access_key=secret_key, region_name = 'us-east-1')
return [region['RegionName'] for region in ec2.describe_regions()['Regions']]
def list_ec2_instances(region=None):
regions = [region] if region else list_all_regions()
instance_details = []
for region in regions:
try:
ec2_client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region)
except (NoCredentialsError, PartialCredentialsError):
print(f"Failed for {region}: No AWS credentials found or incomplete credentials provided.")
continue
except BotoCoreError as e:
print(f"Failed for {region}: Error initializing the EC2 client due to BotoCore Error: {e}")
continue
except Exception as e:
print(f"Failed for {region}: Unexpected error initializing the EC2 client: {e}")
continue
try:
paginator = ec2_client.get_paginator('describe_instances')
for page in paginator.paginate():
for reservation in page['Reservations']:
for instance in reservation['Instances']:
state = instance['State']['Name']
if state == 'stopped': # Filter to only include stopped instances
instance_id = instance['InstanceId']
instance_type = instance['InstanceType']
launch_time = instance['LaunchTime']
instance_details.append({
'InstanceId': instance_id,
'InstanceType': instance_type,
'LaunchTime': launch_time,
'State': state,
'Region': region
})
except ClientError as e:
print(f"Failed for {region}: AWS Client Error while fetching EC2 instance details: {e}")
except Exception as e:
print(f"Failed for {region}: Unexpected error while fetching EC2 instance details: {e}")
return instance_details
def display_instance_details(data):
# Initialize table with the desired structure and headers
table = context.newtable()
table.title = "Stopped EC2 Instance Details"
table.num_cols = 5 # Number of columns according to headers
table.num_rows = 1 # Starts with one row for headers
table.has_header_row = True
# Define header names based on the new structure
headers = ["Instance ID", "Instance Type", "Launch Time", "State", "Region"]
# Set headers in the first row
for col_num, header in enumerate(headers):
table.setval(0, col_num, header)
# Sort the instance data by launch time for better organization
data.sort(key=lambda x: x["LaunchTime"], reverse=True)
# Populate the table with instance data
for row_num, instance in enumerate(data, start=1): # Starting from the second row
table.num_rows += 1 # Add a row for each instance
values = [
instance["InstanceId"],
instance["InstanceType"],
instance["LaunchTime"].strftime('%Y-%m-%d %H:%M:%S'), # Format the datetime
instance["State"],
instance["Region"]
]
for col_num, value in enumerate(values):
table.setval(row_num, col_num, value)
# You can replace None with a specific region string like 'us-east-1' to get instances from a specific region
# Hardcoded region_name for One time Execution Result
#region_name=None
instances_list = list_ec2_instances(region_name)
if instances_list:
'''
print("\nEC2 Instance Details:")
for instance in instances_list:
print("-" * 50) # Separator line
for key, value in instance.items():
print(f"{key}: {value}")'''
display_instance_details(instances_list)
else:
print("No instances found or an error occurred.")
copied