Skip to content

Commit

Permalink
add day-18
Browse files Browse the repository at this point in the history
  • Loading branch information
iam-veeramalla authored Jul 24, 2023
1 parent 1717904 commit d3516b7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions day-18/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# AWS Cloud Cost Optimization - Identifying Stale Resources

## Identifying Stale EBS Snapshots

In this example, we'll create a Lambda function that identifies EBS snapshots that are no longer associated with any active EC2 instance and deletes them to save on storage costs.

### Description:

The Lambda function fetches all EBS snapshots owned by the same account ('self') and also retrieves a list of active EC2 instances (running and stopped). For each snapshot, it checks if the associated volume (if exists) is not associated with any active instance. If it finds a stale snapshot, it deletes it, effectively optimizing storage costs.



22 changes: 22 additions & 0 deletions day-18/ebs_stale_snapshosts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import boto3

def lambda_handler(event, context):
ec2 = boto3.client('ec2')

# Get all EBS snapshots
response = ec2.describe_snapshots(OwnerIds=['self'])

# Get all active EC2 instance IDs
instances_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}])
active_instance_ids = set()

for reservation in instances_response['Reservations']:
for instance in reservation['Instances']:
active_instance_ids.add(instance['InstanceId'])

# Iterate through each snapshot and delete if it's stale
for snapshot in response['Snapshots']:
snapshot_id = snapshot['SnapshotId']
if 'VolumeId' in snapshot and snapshot['VolumeId'] not in active_instance_ids:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted stale EBS snapshot {snapshot_id}.")

0 comments on commit d3516b7

Please sign in to comment.