user4508489
user4508489

Reputation: 21

how to get the latest aws volume snapshot id# using python/boto?

I am new to python , it will be very help if some one share me a sample script to
get the latest snapshot ID# of each AWS volumes.

I am using AWS api.

Upvotes: 2

Views: 1478

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269201

Here's a Python script I wrote that connects to a region and makes a snapshot of each volume, then deletes snapshots except for the most recent N snapshots.

You'll see that the snapshots are sorted by start_time and the snapshot ID is then used to delete the oldest snapshots:

#!/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])

It's the snap_sorted assignment that lets you find the oldest snapshots.

Upvotes: 3

Related Questions