fork download
  1. import datetime
  2. import boto3
  3. import logging
  4. import re
  5.  
  6. logger = logging.getLogger()
  7. logger.setLevel(logging.DEBUG)
  8.  
  9. backup_instances = ['i-e7700c54', 'i-096887d5319d0415b']
  10.  
  11.  
  12. def handler(event, context):
  13. for instance in backup_instances:
  14. cleanup(instance)
  15.  
  16.  
  17. def cleanup(instance_id):
  18. ec = boto3.client('ec2')
  19. response = ec.describe_instance_attribute(
  20. Attribute='blockDeviceMapping',
  21. InstanceId=instance_id
  22. )
  23. logger.debug('Describe Instance: %s', response)
  24.  
  25. volume_filters = [
  26. {'Name': 'attachment.instance-id', 'Values': [instance_id]}
  27. ]
  28. volumes = ec.describe_volumes(Filters=volume_filters)['Volumes']
  29. volume_id = ''
  30. volume_size = ''
  31. logger.debug('Volumes: %s', volumes)
  32. for volume in volumes:
  33. if not volume_id or not volume_size or volume['Size'] > volume_size:
  34. volume_id = volume['VolumeId']
  35. volume_size = volume['Size']
  36.  
  37. # filter snapshots by volume id
  38. filters = [
  39. {'Name': 'volume-id', 'Values': [volume_id]}
  40. ]
  41. # retrieve snapshots belonging to owner by id
  42. account_ids = ['585826603973']
  43. snapshots = ec.describe_snapshots(OwnerIds=account_ids, Filters=filters)['Snapshots']
  44.  
  45. today = datetime.datetime.today().strftime('%Y-%m-%d')
  46. today_date = datetime.datetime.strptime(today, '%Y-%m-%d')
  47. date_regex = '\d{4}[-]\d{2}[-]\d{2}'
  48. count = 0
  49.  
  50. # for each snapshot, compare to today's date. If older than 5 days, delete it
  51. for snap in snapshots:
  52. snap_time = re.search(date_regex, str(snap['StartTime'])).group(0)
  53. logger.info('Snapshot: %s\nDatestamp: %s', snap['SnapshotId'], snap_time)
  54. snap_date = datetime.datetime.strptime(snap_time, '%Y-%m-%d')
  55. delta = today_date - snap_date
  56. logger.info('Delta: %s', delta)
  57.  
  58. if delta > datetime.timedelta(days=4):
  59. logger.info('Older than 5 days, deleting snapshot: %s', snap['SnapshotId'])
  60. ec.delete_snapshot(SnapshotId=snap['SnapshotId'])
  61. count += 1
  62. logger.info('%s snapshot(s) deleted', count)
  63.  
Runtime error #stdin #stdout #stderr 0.02s 28640KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 2, in <module>
ImportError: No module named 'boto3'