-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_fucntion.py
More file actions
49 lines (39 loc) · 1.89 KB
/
lambda_fucntion.py
File metadata and controls
49 lines (39 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import boto3
from botocore.exceptions import ClientError
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Get running instances
instance_response = ec2.describe_instances(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
active_instance_ids = set()
for reservation in instance_response['Reservations']:
for instance in reservation['Instances']:
active_instance_ids.add(instance['InstanceId'])
# Get all snapshots owned by account
snapshots_response = ec2.describe_snapshots(OwnerIds=['self'])
for snapshot in snapshots_response['Snapshots']:
snapshot_id = snapshot['SnapshotId']
volume_id = snapshot.get('VolumeId')
# Snapshot not linked to any volume
if not volume_id:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted snapshot {snapshot_id} (no volume attached)")
continue
try:
volume_response = ec2.describe_volumes(VolumeIds=[volume_id])
volume = volume_response['Volumes'][0]
# Volume exists but not attached to any instance
if not volume['Attachments']:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted snapshot {snapshot_id} (volume unused)")
else:
# Volume attached → check instance state
for attach in volume['Attachments']:
if attach['InstanceId'] not in active_instance_ids:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted snapshot {snapshot_id} (instance stopped/terminated)")
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidVolume.NotFound':
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted snapshot {snapshot_id} (volume not found)")