Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.15 KB | None | 0 0
  1. # Automated AMI and Snapshot Deletion
  2. #
  3. # @author Bobby Kozora
  4. #
  5. # This script will search for all instances having a tag named "Backup" with a value of "Backup".
  6. # As soon as we have the instances list, we loop through each instance
  7. # and reference the AMIs of that instance. We check that the latest daily backup
  8. # succeeded then we store every image that's reached its DeleteOn tag's date for
  9. # deletion. We then loop through the AMIs, deregister them and remove all the
  10. # snapshots associated with that AMI.
  11.  
  12. import boto3
  13. import collections
  14. import datetime
  15. import time
  16. import sys
  17.  
  18. ec = boto3.client('ec2', 'us-east-1')
  19. ec2 = boto3.resource('ec2', 'us-east-1')
  20. images = ec2.images.filter(Owners=["self"])
  21.  
  22.  
  23. def lambda_handler(event, context):
  24.  
  25. reservations = ec.describe_instances(Filters=[
  26. {
  27. 'Name': 'tag-key',
  28. 'Values': ['backup', 'Backup']
  29. },
  30. ]).get('Reservations', [])
  31.  
  32. instances = sum([[i for i in r['Instances']] for r in reservations], [])
  33.  
  34. print("Found %d instances that need evaluated" % len(instances))
  35.  
  36. to_tag = collections.defaultdict(list)
  37.  
  38. date = datetime.datetime.now()
  39. date_fmt = date.strftime('%Y-%m-%d')
  40.  
  41. imagesList = []
  42.  
  43. # Set to true once we confirm we have a backup taken today
  44. backupSuccess = False
  45.  
  46. # Loop through all of our instances with a tag named "Backup"
  47. for instance in instances:
  48. imagecount = 0
  49.  
  50. # Loop through each image of our current instance
  51. for image in images:
  52.  
  53. # Our other Lambda Function names its AMIs Lambda - i-instancenumber.
  54. # We now know these images are auto created
  55. if image.name.startswith('Lambda - ' + instance['InstanceId']):
  56.  
  57. # print "FOUND IMAGE " + image.id + " FOR INSTANCE " + instance['InstanceId']
  58.  
  59. # Count this image's occcurance
  60. imagecount = imagecount + 1
  61.  
  62. try:
  63. if image.tags is not None:
  64. deletion_date = [
  65. t.get('Value') for t in image.tags
  66. if t['Key'] == 'DeleteOn'
  67. ][0]
  68. delete_date = time.strptime(deletion_date, "%m-%d-%Y")
  69. except IndexError:
  70. deletion_date = False
  71. delete_date = False
  72.  
  73. today_time = datetime.datetime.now().strftime('%m-%d-%Y')
  74. # today_fmt = today_time.strftime('%m-%d-%Y')
  75. today_date = time.strptime(today_time, '%m-%d-%Y')
  76.  
  77. # If image's DeleteOn date is less than or equal to today,
  78. # add this image to our list of images to process later
  79. if delete_date <= today_date:
  80. imagesList.append(image.id)
  81.  
  82. # Make sure we have an AMI from today and mark backupSuccess as true
  83. if image.name.endswith(date_fmt):
  84. # Our latest backup from our other Lambda Function succeeded
  85. backupSuccess = True
  86. print("Latest backup from " + date_fmt + " was a success")
  87.  
  88. print("instance " + instance['InstanceId'] + " has " +
  89. str(imagecount) + " AMIs")
  90.  
  91. print("=============")
  92.  
  93. print("About to process the following AMIs:")
  94. print(imagesList)
  95.  
  96. if backupSuccess == True:
  97.  
  98. myAccount = boto3.client('sts').get_caller_identity()['Account']
  99. snapshots = ec.describe_snapshots(MaxResults=1000,
  100. OwnerIds=[myAccount])['Snapshots']
  101.  
  102. # loop through list of image IDs
  103. for image in imagesList:
  104. print("deregistering image %s" % image)
  105. amiResponse = ec.deregister_image(
  106. DryRun=False,
  107. ImageId=image,
  108. )
  109.  
  110. for snapshot in snapshots:
  111. if snapshot['Description'].find(image) > 0:
  112. snap = ec.delete_snapshot(
  113. SnapshotId=snapshot['SnapshotId'])
  114. print("Deleting snapshot " + snapshot['SnapshotId'])
  115. print("-------------")
  116.  
  117. else:
  118. print("No current backup found. Termination suspended.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement