问题
I'm using AWS and pulling snapshots using boto ("The Python interface to Amazon Web Services"). I'm pulling all snapshots using conn.get_all_snapshots()
, but I only want to retrieve the necessary data. I'm using a calendar to view the snapshots, so it would be very helpful if I could only pull the snapshots within the current month I'm viewing.
Is there a restriction (maybe a filter) I can put on the conn.get_all_snapshots()
to only retrieve the snapshots within the month?
Here are boto docs if necessary: http://boto.readthedocs.org/en/latest/ref/ec2.html
回答1:
I'm not aware of any way to do this. The EC2 API allows you to filter results based on snapshot ID's or by various filters such as status
or progress
. There is even a filter for create-time
but unfortunately there is no way to specify a range of times and have it return everything in between. And there is no way to use <
or >
operators in the filter query.
回答2:
Use the snapshot's start_time
field (which is a string, so it'll need to be parsed):
import datetime
# Fetch all snaps
snaps = conn.get_all_snapshots()
# Get UTC of 30-days ago
cutoff = datetime.datetime.utcnow() - datetime.timedelta(days=30)
# datetime parsing format "2015-09-07T20:12:08.000Z"
DATEFORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'
# filter older
old_snaps = [s for s in snaps \
if datetime.datetime.strptime(s.start_time, DATEFORMAT) < cutoff]
# filter newer
new_snaps = [s for s in snaps \
if datetime.datetime.strptime(s.start_time, DATEFORMAT) >= cutoff]
old_snaps
will contain the ones from before this month and new_snaps
will contain the ones from this month. (I have the feeling you want to delete the old snaps, that's why I included the old_snaps
line.)
I'm using datetime.strptime() above because it's builtin, but dateutil is more robust if you have it installed. (See this for details: https://stackoverflow.com/a/3908349/1293152)
来源:https://stackoverflow.com/questions/24891834/aws-boto-get-snapshots-in-time-period