Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Author: Roland Peto <petoroland1234@gmail.com>
- # Created: 2018-12-09
- # Last modified: 2018-12-09
- # Version 0.1
- # Short description: Delete old EC2 snapshots in the Ireland region.
- import boto3
- import re
- from datetime import datetime, timedelta
- import json
- import os
- ec2 = boto3.client('ec2', region_name='eu-west-1')
- sns = boto3.client('sns', region_name='eu-west-1')
- iam = boto3.client('iam')
- def lambda_handler(event, context):
- # Get account ID
- account_ids = list()
- try:
- iam.get_user()
- except Exception as e:
- # use the exception message to get the account ID the function executes under
- account_ids.append(re.search(r'(arn:aws:sts::)([0-9]+)', str(e)).groups()[1])
- # Get snapshots
- snapshot_response = ec2.describe_snapshots(OwnerIds=account_ids)
- delete_response_codes = []
- for snapshot in snapshot_response['Snapshots']:
- # if the snapshot is older than 8 days
- if ((datetime.now() - snapshot['StartTime'].replace(tzinfo=None)) > timedelta(days=int(os.environ['retentionDays']))):
- # delete snapshot, save response code and log the result
- delete_response = ec2.delete_snapshot(SnapshotId=snapshot['SnapshotId'])
- delete_response_codes.append(delete_response['ResponseMetadata']['HTTPStatusCode'])
- if(delete_response['ResponseMetadata']['HTTPStatusCode'] == 200):
- print 'Old snapshot ('+snapshot['SnapshotId']+') has been deleted successfully.'
- else:
- print 'Something went wrong with the deletion of '+snapshot['SnapshotId']+'. Response: ' + delete_response
- # check if something went wrong with the deletions
- error = False
- for code in delete_response_codes:
- if (code != 200):
- error = True
- # get the snapshot list again
- snapshot_response = ec2.describe_snapshots(OwnerIds=account_ids)
- # send SNS notifications to Admins
- if (not error):
- message = 'EBS snapshot mgmt scipt has just finished successfully. Current available snapshots: ' + str(snapshot_response['Snapshots'])
- else:
- message = 'EBS snapshot mgmt scipt has just finished, but there were some errors. Check logs for details.'
- sns.publish(
- TargetArn='arn:aws:sns:eu-west-1:127095825479:AdminMessages',
- Subject='EBS snapshot management',
- Message=message
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement