【发布时间】:2020-04-14 06:36:48
【问题描述】:
您好,我正在寻找 python 脚本,通过将快照 ID 或实例名称和保留期作为参数来删除快照。我有下面的脚本,它删除所有比保留期设置更早的快照,但是只想对特定实例名称执行删除。
# Delete snapshots older than retention period
import boto3
from botocore.exceptions import ClientError
from datetime import datetime,timedelta
def delete_snapshot(snapshot_id, reg):
try:
ec2resource = boto3.resource('ec2', region_name=reg)
snapshot = ec2resource.Snapshot(snapshot_id)
snapshot.delete()
except ClientError as e:
print "Caught exception: %s" % e
return
def lambda_handler(event, context):
account_id = 'xxxxxxxxxxxxxxx'
retention_days = 10
# Get current timestamp in UTC
now = datetime.now()
# AWS Account ID
# Define retention period in days
# Create EC2 client
ec2 = boto3.client('ec2')
# Get list of regions
regions = ec2.describe_regions().get('Regions',[] )
# Iterate over regions
for region in regions:
print "Checking region %s " % region['RegionName']
reg=region['RegionName']
# Connect to region
ec2 = boto3.client('ec2', region_name=reg)
# Filtering by snapshot timestamp comparison is not supported
# So we grab all snapshot id's
result = ec2.describe_snapshots( OwnerIds=[account_id] )
for snapshot in result['Snapshots']:
print "Checking snapshot %s which was created on %s" % (snapshot['SnapshotId'],snapshot['StartTime'])
# Remove timezone info from snapshot in order for comparison to work below
snapshot_time = snapshot['StartTime'].replace(tzinfo=None)
# Subtract snapshot time from now returns a timedelta
# Check if the timedelta is greater than retention days
if (now - snapshot_time) > timedelta(retention_days):
print "Snapshot is older than configured retention of %d days" % (retention_days)
delete_snapshot(snapshot['SnapshotId'], reg)
else:
print "Snapshot is newer than configured retention of %d days so we keep it" % (retention_days)
【问题讨论】:
-
脚本需要
describe_snapshots()调用,然后使用delete_snapshot()从该列表中删除所需的快照。请编辑您的问题,向我们展示您迄今为止编写的代码以及您面临的困难。 -
谢谢。是的,我会更新我到目前为止的代码。我有一个代码可以删除所有早于我在代码中设置的保留期的快照。但是,我有一个不同的用例,我只想删除特定实例的快照。注意我有每个实例的实例名称或标签
-
@JohnRotenstein 我已经更新了我的问题中的代码。提前致谢
标签: python amazon-web-services amazon-ec2 aws-lambda