Reputation: 3860
I am getting the following Error while deleting snapshots. I wanted to delete Snapshot which are currently not in use by My AWS AMI's and Other Instances.. as well .I tried but got this error..
Traceback (most recent call last):
<path to error file>
EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?><Response><Errors><Error><Code>InvalidSnapshot.InUse</Code><Message>The snapshot snap-xxxxxxxx is currently in use by ami-xxxxxxxx</Message></Error></Errors><RequestID>bbe55333-4acf-4ca7-9aa3-49307b189ca3</RequestID></Response>
Upvotes: 2
Views: 3858
Reputation: 11
Just in case anyone still wondering how to do it:
def if_associated_to_ami(client, snapshot_id):
img = client.describe_images(
Filters=[
{'Name': 'block-device-mapping.snapshot-id', 'Values': [snapshot_id]}
]
)
try:
ami_id = img['Images'][0]['ImageId']
print("Snapshot(" + snapshot_id + ") is associated to image(" + ami_id + "). Return True")
return True
except IndexError:
print("Snapshot(" + snapshot_id + ") is not associated to any image. Return False")
return False
Upvotes: 0
Reputation: 1390
1) Retrieve all the Snapshots, Use regular expression to search for AMI-ID inside snapshot description.
reAmi = re.compile('ami-[^ ]+')
snapshotImageId = reAmi.findall(snapshot.description)
2) Retrieve all the AMI's. Check whether the AMI-ID retrieved in first step still exist, if not then snapshot associated with that particular AMI is no longer required.
complete code is posted here
Hope it helps !!
Upvotes: 0
Reputation: 5794
Delete all Snapshots which are not in use :
for s in $(comm -23 <(echo $(ec2-describe-snapshots --region ap-southeast-1 | grep SNAPSHOT | awk '{print $2}' | sort | uniq) | tr ' ' '\n') <(echo $(ec2-describe-images --region ap-southeast-1 | grep BLOCKDEVICEMAPPING | awk '{print $3}' | sort | uniq) | tr ' ' '\n') | tr '\n' ' ')
do
echo Deleting snapshot $s
ec2-delete-snapshot --region ap-southeast-1 $s
done
Upvotes: 2
Reputation: 36063
Unfortunately, there is not an API to get AMI ID directly from an EBS snapshot.
Instead, you can go the other way.
ec2:DescribeImages
to get a list of AMI images. Edit: Another possibility:
You may be able to use ec2:DescribeImages
with a filter on the EBS snapshot ID.
https://ec2.amazonaws.com/?Action=DescribeImages
&Filter.1.Name=block-device-mapping.snapshot-id
&Filter.1.Value=snap-xxxx
Reference: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeImages.html
Upvotes: 2