daily pastebin goal
57%
SHARE
TWEET

Untitled

a guest Dec 18th, 2018 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Author: Roland Peto <petoroland1234@gmail.com>
  2. # Created: 2018-12-09
  3. # Last modified: 2018-12-09
  4. # Version 0.1
  5. # Short description: Delete old EC2 snapshots in the Ireland region.
  6.  
  7. import boto3  
  8. import re  
  9. from datetime import datetime, timedelta
  10. import json
  11. import os
  12.  
  13.  
  14. ec2 = boto3.client('ec2', region_name='eu-west-1')
  15. sns = boto3.client('sns', region_name='eu-west-1')
  16. iam = boto3.client('iam')
  17.  
  18.  
  19. def lambda_handler(event, context):
  20.    
  21.     # Get account ID
  22.     account_ids = list()
  23.     try:
  24.         iam.get_user()
  25.     except Exception as e:
  26.         # use the exception message to get the account ID the function executes under
  27.         account_ids.append(re.search(r'(arn:aws:sts::)([0-9]+)', str(e)).groups()[1])
  28.  
  29.     # Get snapshots
  30.     snapshot_response = ec2.describe_snapshots(OwnerIds=account_ids)
  31.     delete_response_codes = []
  32.     for snapshot in snapshot_response['Snapshots']:
  33.         # if the snapshot is older than 8 days
  34.         if ((datetime.now() - snapshot['StartTime'].replace(tzinfo=None)) > timedelta(days=int(os.environ['retentionDays']))):
  35.             # delete snapshot, save response code and log the result
  36.             delete_response = ec2.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
  37.             delete_response_codes.append(delete_response['ResponseMetadata']['HTTPStatusCode'])
  38.             if(delete_response['ResponseMetadata']['HTTPStatusCode'] == 200):
  39.                 print 'Old snapshot ('+snapshot['SnapshotId']+') has been deleted successfully.'
  40.             else:
  41.                 print 'Something went wrong with the deletion of '+snapshot['SnapshotId']+'. Response: ' + delete_response
  42.    
  43.     # check if something went wrong with the deletions
  44.     error = False
  45.     for code in delete_response_codes:
  46.         if (code != 200):
  47.             error = True
  48.    
  49.     # get the snapshot list again
  50.     snapshot_response = ec2.describe_snapshots(OwnerIds=account_ids)
  51.    
  52.     # send SNS notifications to Admins
  53.     if (not error):
  54.         message = 'EBS snapshot mgmt scipt has just finished successfully. Current available snapshots: ' + str(snapshot_response['Snapshots'])
  55.     else:
  56.         message = 'EBS snapshot mgmt scipt has just finished, but there were some errors. Check logs for details.'
  57.    
  58.     sns.publish(
  59.         TargetArn='arn:aws:sns:eu-west-1:127095825479:AdminMessages',
  60.         Subject='EBS snapshot management',
  61.         Message=message
  62.     )
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top