简体   繁体   English

如何使用BOTO3 Python检索与AWS EC2实例相关的所有快照?

[英]How to retrieve all snapshots related to a AWS EC2 instance using BOTO3 Python?

I am tangled in of the situation: I can retrieve all the snapshots of a volume associated with a EC2 instance but once the EC2 instance gets deleted so does its associated volume. 我纠结于这种情况:我可以检索与EC2实例关联的卷的所有快照,但是一旦删除EC2实例,关联的卷也会被删除。 I have been rubbing my head around the Boto3 documentation and struggling. 我一直在摸索Boto3文档并苦苦挣扎。 Below is my working example to list the snapshots associated with the Volume. 以下是我的工作示例,列出了与卷关联的快照。

import boto3
ec2 = boto3.resource('ec2')
volume_id = "something"
list_of_snapshots = []
vol = ec2.Volume(id=volume_id)
snapshots = vol.snapshots.all()
    try:
        for snapshot in snapshots:
            if snapshot:
                list_of_snapshots.append(snapshot.id)
        return list_of_snapshots[0]
    except:
        return None

One option is to tag the volumes when they are initially created. 一种选择是在最初创建卷时对其进行标记。 The tags will stay with the volumes even when the instance is deleted. 即使实例被删除,这些标签也将保留在卷中。

Amazon EC2 can now propagate tags to volumes on launch. Amazon EC2现在可以在启动时将标签传播到卷。

See: Tag EC2 Instances & EBS Volumes on Creation | 请参阅: 在创建时标记EC2实例和EBS卷| AWS News Blog AWS新闻博客

As @John Rotenstein suggested, 正如@约翰·罗滕斯坦(John Rotenstein)所建议的那样,

The possible solution right now is to add the VolumeID inside the tags while creating the snapshots, so the code turns out to be something like this: 现在可能的解决方案是在创建快照时在标签内添加VolumeID,因此代码如下所示:

import boto3
ec2 = boto3.client('ec2')
volume_id= "something"
list_of_snapshots = []
    snapshots = ec2.describe_snapshots(Filters=[{'Name':'tag:volume_id', 'Values': [volume_id]}])['Snapshots']
    try:
        for snapshot in snapshots:
            if snapshot:
                list_of_snapshots.append(snapshot['SnapshotId'])
        return list_of_snapshots
    except:
        return None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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