forked from iam-veeramalla/aws-devops-zero-to-hero
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1717904
commit d3516b7
Showing
2 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}.") |