【问题标题】:python (boto3) program to delete old snapshots in awspython(boto3)程序删除aws中的旧快照
【发布时间】:2018-06-15 21:29:40
【问题描述】:

我已经编写了一个删除旧快照的程序。但我现在的问题是如果快照附加了 ami 那么它不会被删除并且程序也会停止。它显示以下消息:

botocore.exceptions.ClientError:调用 DeleteSnapshot 操作时发生错误 (InvalidSnapshot.InUse):ami-12345 当前正在使用快照 snap-12345678

我希望程序单独跳过这些快照并继续删除其他快照。下面是我的代码:

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)

【问题讨论】:

    标签: python amazon-web-services aws-lambda boto3


    【解决方案1】:

    我自己解决了。这是代码:

        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
    

    【讨论】:

    • 测试 e.response['Error']['Code'] 可能比 e.message 更好。
    • @vishal 对于 boto3 和 python3,snapshot.delete() 和 client.delete_snapshot(SnapshotId=id) 有什么区别
    【解决方案2】:

    感谢 Vishal,这正是我开始所需要的。由于合规要求,我做了一些调整。我添加了一个例外,以保留所有备份的 StartTime 日期为每月 1 日。我还添加了一个例外来保留我最旧的快照集。

    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
    

    【讨论】:

    • boto3和python3的snapshot.delete()和client.delete_snapshot(SnapshotId=id)有什么区别
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多