Guest User

Untitled

a guest
Jul 8th, 2018
114
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from datetime import datetime, timedelta, timezone
  2.  
  3. import boto3
  4.  
  5. class Ec2Instances(object):
  6.  
  7. def __init__(self, region):
  8. print("region "+ region)
  9. self.ec2 = boto3.client('ec2', region_name=region)
  10.  
  11. def delete_snapshots(self, older_days=1):
  12. delete_snapshots_num = 0
  13. snapshots = self.get_lambda_created_snapshots()
  14. for snapshot in snapshots['Snapshots']:
  15. fmt_start_time = snapshot['StartTime']
  16. if (fmt_start_time < self.get_delete_data(older_days)):
  17. self.delete_snapshot(snapshot['SnapshotId'])
  18. delete_snapshots_num+1
  19. return delete_snapshots_num
  20.  
  21. def get_lambda_created_snapshots(self):
  22. snapshots = self.ec2.describe_snapshots(Filters=[{'Name': 'description', 'Values': ['Created by Lambda backup function ebs-snapshots']}])
  23. return snapshots
  24.  
  25. def get_delete_data(self, older_days):
  26. delete_time = datetime.now(tz=timezone.utc) - timedelta(days=older_days)
  27. return delete_time;
  28.  
  29. def delete_snapshot(self, snapshot_id):
  30. self.ec2.delete_snapshot(SnapshotId=snapshot_id)
  31.  
  32. def lambda_handler(event, context):
  33. print("event " + str(event))
  34. print("context " + str(context))
  35. ec2_reg = boto3.client('ec2')
  36. regions = ec2_reg.describe_regions()
  37. for region in regions['Regions']:
  38. region_name = region['RegionName']
  39. instances = Ec2Instances(region_name)
  40. deleted_counts = instances.delete_snapshots(1)
  41. print("deleted_counts for region "+ str(region_name) +" is " + str(deleted_counts))
  42. return 'completed'
RAW Paste Data