简体   繁体   中英

Python Boto3 SnapshotNotFound exception. Unable to delete snapshot

I'm new to AWS and I have written a Boto3 script which gets the snapshots by OwnerId and delete older snapshots one by one. I'm having a strange issue that boto client finds all Snapshots and when it reaches client.delete_snapshot(SnapshotId=snapshot.snapshot_id) It throws SnapshotNotFoundException - Unable to delete snapshot with id abcd.

It's weird that when i go to AWS Console and search for the ID, Snapshot is there and I can delete it from the AWS Console and I'm using the same account credentials with Boto3 config file.

[default]
aws_access_key_id=foo
aws_secret_access_key=bar 

Here is what i have tried. Boto3 Script

from datetime import datetime, timedelta, timezone
import boto3
ec2 = boto3.resource('ec2')
cl = boto3.client('ec2')
count=0
snapshots = ec2.snapshots.filter(OwnerIds=['xxxxxxxxxx'])
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
for snapshot in snapshots:
    if if_associated_to_ami(cl, snapshot.snapshot_id):
        print('Unabble to delete Snapshot with Id = {}. Snapshot is in used! '. format(snapshot.snapshot_id))
    else:
        start_time = snapshot.start_time
        delete_time = datetime.now(tz=timezone.utc) - timedelta(days=90)
        if delete_time > start_time:
            #snapshot.delete()
            cl.delete_snapshot(SnapshotId=snapshot.snapshot_id)
            print('Snapshot with Id = {} is deleted '. format(snapshot.snapshot_id))
    count+=1
    if count == 1000:
        break

if you face indentation issues, please check the file here. https://github.com/DeveloperMujtaba/usual-resources/blob/master/boto3.py can someone please indicate the issue please? It would be much appreciated. Thanks.

Honestly, just by looking at your code, I cannot tell why it bulks at that but also, b/c you already have the snapshot resource, why not just do:

snapshot.delete()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM