如果删除了卷,则删除快照

cha*_*ani 0 python amazon-ec2 amazon-web-services aws-lambda aws-ebs

我需要删除其 EBS 卷已删除的弹性块存储卷的快照。我想使用 Lambda 函数来完成此操作。我编写了一个脚本,如果 EBS 卷不存在,该脚本将返回 false。如何修改它以删除任何相关快照?

def get_snapshots():
    account_ids = list()
    account_ids.append( boto3.client('sts').get_caller_identity().get('Account'))
    return ec2.describe_snapshots(OwnerIds=account_ids)
 
def volume_exists(volume_id):
    if not volume_id: return ''
    try:
        ec2.describe_volumes(VolumeIds=[volume_id])
        return True
    except ClientError:
        return False
 

 
def lambda_handler(event, context):

    with open('/tmp/report.csv', 'w') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow([
        'volume exists'
        ])
        snaps = get_snapshots()
        
        for snap in snaps.get('Snapshots'):
            writer.writerow([
            
            str(volume_exists(snap['VolumeId']))
            ])
Run Code Online (Sandbox Code Playgroud)

有什么建议吗?

Joh*_*ein 6

以下是一些将删除没有现有卷的快照的代码:

import boto3

ec2_client = boto3.client('ec2')

# Make a list of existing volumes
volume_response = ec2_client.describe_volumes()
volumes = [volume['VolumeId'] for volume in volume_response['Volumes']]

# Find snapshots without existing volume
snapshot_response = ec2_client.describe_snapshots(OwnerIds=['self'])

for snapshot in snapshot_response['Snapshots']:
    if snapshot['VolumeId'] not in volumes:
        delete_response = ec2_client.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
Run Code Online (Sandbox Code Playgroud)

resource或者,这是一个使用而不是以下版本client

import boto3

ec2_resource = boto3.resource('ec2')

# Make a list of existing volumes
all_volumes = ec2_resource.volumes.all()
volumes = [volume.volume_id for volume in all_volumes]

# Find snapshots without existing volume
snapshots = ec2_resource.snapshots.filter(OwnerIds=['self'])

for snapshot in snapshots:
    if snapshot.volume_id not in volumes:
        snapshot.delete()
Run Code Online (Sandbox Code Playgroud)

如果它们按照您的意愿工作,您需要将其合并到 Lambda 函数中。

(除了根据本网站服务条款授予的许可之外,本文的内容还根据 MIT-0 获得许可。)