-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanup-snapshots.py
More file actions
33 lines (28 loc) · 877 Bytes
/
cleanup-snapshots.py
File metadata and controls
33 lines (28 loc) · 877 Bytes
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
import boto3
from operator import itemgetter
ec2_client = boto3.client('ec2', region_name="eu-central-1")
volumes = ec2_client.describe_volumes(
Filters=[
{
'Name': 'tag:Name',
'Values': ['prod']
}
]
)
for volume in volumes['Volumes']:
snapshots = ec2_client.describe_snapshots(
OwnerIds=['self'], # created by us
Filters=[
{
'Name': 'volume-id',
'Values': [volume['VolumeId']]
}
]
)
# sorting a list of dictionaries by key value
sorted_by_date = sorted(snapshots['Snapshots'], key=itemgetter('StartTime'), reverse=True)
for snap in sorted_by_date[2:]: # slicing out 2 most recent items from the list
response = ec2_client.delete_snapshot(
SnapshotId=snap['SnapshotId']
)
print(response)