我是python的新手,如果有人与我共享一个示例脚本来提供帮助,将会非常有帮助
获取每个AWS卷的最新快照ID#。

我正在使用AWS api。

最佳答案

这是我编写的Python脚本,它连接到区域并为每个卷制作快照,然后删除快照(最近的N个快照除外)。

您将看到快照按start_time排序,然后使用快照ID删除最早的快照:

#!/usr/bin/env python

import boto.ec2, os

MAX_SNAPSHOTS = 2   # Number of snapshots to keep

# Connect to EC2 in this region
connection = boto.ec2.connect_to_region('us-west-2')

# Get a list of all volumes
volumes = connection.get_all_volumes()

# Create a snapshot of each volume
for v in volumes:
  connection.create_snapshot(v.id)

  # Too many snapshots?
  snapshots = v.snapshots()
  if len(snapshots) > MAX_SNAPSHOTS:

    # Delete oldest snapshots, but keep MAX_SNAPSHOTS available
    snap_sorted = sorted([(s.id, s.start_time) for s in snapshots], key=lambda k: k[1])
    for s in snap_sorted[:-MAX_SNAPSHOTS]:
      print "Deleting snapshot", s[0]
      connection.delete_snapshot(s[0])


通过snap_sorted分配,您可以找到最早的快照。

08-07 22:36