问题
I have already written a program to delete old snapshots.But the problem for me now is if the snapshot is attached with an ami then it doesn't get deleted and the program also stops.It displays the following message :
botocore.exceptions.ClientError: An error occurred (InvalidSnapshot.InUse) when calling the DeleteSnapshot operation: The snapshot snap-12345678 is currently in use by ami-12345
I want the program to skip those snapshots alone and continue to delete other snapshots. here is my code below:
import boto3
import datetime
client = boto3.client('ec2',region_name='us-west-1')
snapshots = client.describe_snapshots(OwnerIds=['12345678'])
for snapshot in snapshots['Snapshots']:
a= snapshot['StartTime']
b=a.date()
c=datetime.datetime.now().date()
d=c-b
if d.days>10:
id = snapshot['SnapshotId']
client.delete_snapshot(SnapshotId=id)
回答1:
I've solved it myself. here is the code:
import boto3
import datetime
client = boto3.client('ec2',region_name='us-west-1')
snapshots = client.describe_snapshots(OwnerIds=['12345678'])
for snapshot in snapshots['Snapshots']:
a= snapshot['StartTime']
b=a.date()
c=datetime.datetime.now().date()
d=c-b
try:
if d.days>10:
id = snapshot['SnapshotId']
client.delete_snapshot(SnapshotId=id)
except Exception,e:
if 'InvalidSnapshot.InUse' in e.message:
print "skipping this snapshot"
continue
回答2:
Thanks Vishal, exactly what I needed to get started. I made a few tweaks due to compliance requirements. I added an exception to keep all backups with a StartTime date of the 1st of the month. I also added an exception to keep my oldest snapshot set.
import boto3
import datetime
client = boto3.client('ec2',region_name='us-west-1')
snapshots = client.describe_snapshots(OwnerIds=['111111111111'])
def lambda_handler(event, context):
for snapshot in snapshots['Snapshots']:
a=snapshot['StartTime']
b=a.date()
c=datetime.datetime.now().date()
d=c-b
f=a.day
excludeDate=datetime.datetime.strptime('2018-1-10', '%Y-%m-%d').date()
try:
if d.days>30 and f!=1 and b!=excludeDate:
id = snapshot['SnapshotId']
client.delete_snapshot(SnapshotId=id)
except Exception,e:
if 'InvalidSnapshot.InUse' in e.message:
print "skipping this snapshot"
continue
来源:https://stackoverflow.com/questions/48124269/python-boto3-program-to-delete-old-snapshots-in-aws