如何检查快照现在是否 'completed'

How to check if the snapshot is now 'completed'

我正在使用 boto3 创建一个 id 的快照,我只需要检查快照是否创建完成,但下面的循环不会这样做,只会运行到无穷大。

regions = ['eu-central-1']
for region in regions:
    ec2 = boto3.resource('ec2', region, aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, )
    snapshot = ec2.create_snapshot(VolumeId='vol-f9e7d220', Description='fra01-he-trial-ansible01')
    print snapshot.id

    get_all_snapshots = ec2.snapshots.filter(snap_id=['SnapshotIds'])
    print get_all_snapshots

    while snapshot.state != 'completed':
          ## put a condition here to get all snapshot or update the state !
          print snapshot.progress
          print "Snapshot under creation"
          time.sleep(10)
    else:
        print "snapshot READY"

您应该在循环之前和 sleep 语句之后调用 snapshot.load()

刚刚在 AWS 微型实例上对其进行了测试,将其添加到您的代码后即可正常工作。

snapshot = ec2.create_snapshot(VolumeId='vol-#####', Description='snapshotID')
print snapshot.id
snapshot.load()
while snapshot.state != 'completed':
      print snapshot.progress
      print "Snapshot under creation"
      time.sleep(10)
      snapshot.load()
else:
    print "snapshot READY"

Maximillian 提出 load,但我建议您使用 waiter. This will handle all the waiting logic for you and return when your snapshot is completed. For that resource, you would use: snapshot.wait_until_completed()

一般来说,使用服务员(如果可用)优于自定义等待逻辑,因为它们处理所有边缘情况和其他实现细节。比如创建快照过程中出现错误,就会进入error状态。已接受答案中的代码将继续轮询,直到资源完全消失,此时它将引发错误。这可能需要很长时间。在这种情况下,服务员将最多轮询 40 次,重试延迟为 15 秒。 (您可以查看定义 here。)因此,您不会等待数小时或数天,最多只会等待 10 分钟。不同的服务员有不同的重试延迟和最大重试次数。许多服务员有关于不可恢复状态的额外信息,并且在这些情况下会很快失败。

将 Waiter 与您自己的超时控制结合使用

默认超时为 600 秒(延迟=15 秒 x max_attempts=40),如 Boto3 EC2.Waiter.SnapshotCompleted.

中所述

Polls EC2.Client.describe_snapshots() every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.

验证服务员的当前设置:

Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> client = boto3.client('ec2')
>>> waiter=client.get_waiter('snapshot_completed')
>>> print waiter.config.__dict__
{'delay': 15, '_config': OrderedDict([(u'delay', 15), (u'operation', u'DescribeSnapshots'), (u'maxAttempts', 40), (u'acceptors', [OrderedDict([(u'expected', u'completed'), (u'matcher', u'pathAll'), (u'state', u'success'), (u'argument', u'Snapshots[].State')])])]), 'description': '', 'operation': u'DescribeSnapshots', 'max_attempts': 40}

将 Waiter 与您自己的超时一起使用:

delay= 15
max_attempts = 80
def wait_snapshot(ec2, snapshot):
    waiter = ec2.meta.client.get_waiter('snapshot_completed')

    # Set the timeout
    # Waiter timeout is 10 min (Boto default is delay=15 * max_attempts=40).
    waiter.config.delay = delay
    waiter.config.max_attempts = max_attempts
    waiter.wait(
        SnapshotIds=[
            snapshot.id
        ],
    )