List EBS snapshots which is n days older
Boto is the Amazon Web Services (AWS) SDK for Python, which allows Python developers to write software that makes use of Amazon services like S3 and EC2. Boto provides an easy to use, object-oriented API as well as low-level direct service access
We will be using three different python modules.
- boto3
- datetime
#!/usr/bin/python
import boto3
import datetime
# Calculate timeLimit for EBS Snapshots
time_limit = datetime.datetime.now() - datetime.timedelta(days=7)
# ec2 object creation
ec2client = boto3.client('ec2')
# This function is used to retrive the ec2 instances from the given region
def get_ec2_instances():
instance_list = ec2client.describe_instances()
# Return Instances List
return instance_list
# This function is used to retrive the volumes list by instance id
def get_volumes_by_instance_id(instance_id):
volume_filters = [{"Name": "attachment.instance-id", "Values": [instance_id]}]
volume_list = ec2client.describe_volumes(Filters=volume_filters)
return volume_list
# This function is used to retrive the snapshots by volume id
def get_ebs_snapshots_by_volume_id(volume_id):
snapshot_filters = [{"Name": "volume-id", "Values": [volume_id]}]
snapshot_list = ec2client.describe_snapshots(Filters=snapshot_filters)
return snapshot_list
instance_list_info = get_ec2_instances()
for ec2_reservation in instance_list_info["Reservations"]:
for ec2_instance in ec2_reservation["Instances"]:
volume_list_info = get_volumes_by_instance_id(ec2_instance["InstanceId"])
for volume_info in volume_list_info["Volumes"]:
snapshot_list_info = get_ebs_snapshots_by_volume_id(volume_info["VolumeId"])
for snapshot_info in snapshot_list_info["Snapshots"]:
if snapshot_info['StartTime'].date() >= time_limit.date():
print("Instance ID :", ec2_instance["InstanceId"])
print("Volume ID :", volume_info["VolumeId"])
print(snapshot_info['SnapshotId'], snapshot_info['StartTime'].date())
Category: amazon web services, aws, boto, Programming
0 comments