#!/usr/bin/env python3
import boto3
import time
from botocore.exceptions import ClientError
#take snapshots of long time once a week as delete "cron(16 23 ? * 1 *)"
def delete_snapshot(snapshot_id):
try:
ec2resource = boto3.resource('ec2')
snapshot = ec2resource.Snapshot(snapshot_id)
snapshot.delete()
except ClientError as e:
print
"Caught exception: %s" % e
return
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name='ap-southeast-1')
# Get all snapshots
result = ec2.describe_snapshots(OwnerIds=['***************'])
for snapshot in result['Snapshots']:
if 'Tags' in snapshot:
for tags in snapshot['Tags']:
if tags["Key"] == "Date":
#Get the current timestamp
now = int(time.time())
snapshot_date = time.strptime(tags['Value'],"%Y%m%d-%H%M")
snapshot_date_stamp = int(time.mktime(snapshot_date))
# delete the snapshot if more than three months
if now - snapshot_date_stamp > 2592000*3:
#delete older snapshot
ec2.delete_snapshot(snapshot['SnapshotId'])
print("the snapshot of %s has been deleted." %(snapshot['SnapshotId']))
else:
print("this snapshot of %s is created for less than 3 months.." %(snapshot['SnapshotId']))
lambda_handler(2, 3)
aws pathon脚本定期删除snapshots
猜你喜欢
转载自blog.csdn.net/guofeng_hao/article/details/82019795
今日推荐
周排行