├── lambdas └── ec2 │ ├── __pycache__ │ └── reaper.cpython-36.pyc │ ├── slack_notifier.py │ ├── deploy_reaper.yaml │ ├── deploy_to_s3.yaml │ ├── README.md │ └── reaper.py ├── README.md ├── tests └── lambdas │ ├── __pycache__ │ └── test_reaper.cpython-36.pyc │ └── test_reaper.py ├── CODEOWNERS └── LICENSE /lambdas/ec2/__pycache__/reaper.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/puppetlabs/aws_resource_reaper/master/lambdas/ec2/__pycache__/reaper.cpython-36.pyc -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws_resource_reaper 2 | Services to control unmanaged aws resources. 3 | 4 | ## Reapers 5 | 6 | ### [AWS EC2 Reaper](lambdas/ec2/README.md) 7 | 8 | -------------------------------------------------------------------------------- /tests/lambdas/__pycache__/test_reaper.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/puppetlabs/aws_resource_reaper/master/tests/lambdas/__pycache__/test_reaper.cpython-36.pyc -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # This will cause the puppetlabs/it-services group to be assigned 2 | # review of any opened PRs against the branches containing this file. 3 | 4 | * @puppetlabs/it-services 5 | lambdas/* @ShawonC 6 | -------------------------------------------------------------------------------- /lambdas/ec2/slack_notifier.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import boto3 3 | import json 4 | import ast 5 | import zlib 6 | import base64 7 | import os 8 | from urllib.request import Request, urlopen 9 | 10 | RED_ALERTS = [ 11 | 'The following instances have been stopped due to unparsable or missing termination_date tags:' 12 | ] 13 | 14 | NO_ALERT = [ 15 | 'REAPER TERMINATION completed. The following instances have been deleted due to expired termination_date tags: [].', 16 | 'REAPER TERMINATION completed. The following instances have been stopped due to unparsable or missing termination_date tags: [].', 17 | 'REAPER TERMINATION completed. The following instances have been deleted due to expired termination_date tags: []. The following instances have been stopped due to unparsable or missing termination_date tags: [].' 18 | 'REAPER TERMINATION completed. LIVEMODE is off, would have stopped the following instances due to unparsable or missing termination_date tags: []', 19 | 'REAPER TERMINATION completed. LIVEMODE is off, would have deleted the following instances: []', 20 | 'REAPER TERMINATION completed. LIVEMODE is off, would have deleted the following instances: []. REAPER would have stopped the following instances due to unparsable or missing termination_date tags: []' 21 | ] 22 | 23 | def get_account_alias(): 24 | """ 25 | Return the first alias listed from Amazon. Return generic Reaper if unable 26 | to find account alias. 27 | """ 28 | client = boto3.client('iam') 29 | try: 30 | return client.list_account_aliases()['AccountAliases'][0] 31 | except Exception: 32 | print('Unable to find account alias') 33 | return 'AWS EC2 Reaper' 34 | 35 | def read_webhook(): 36 | """ 37 | Read in the environment SLACK_WEBHOOK. 38 | """ 39 | return os.environ['SLACKWEBHOOK'] 40 | 41 | def determine_region(): 42 | """ 43 | Determine the current region execution 44 | """ 45 | region = boto3.session.Session().region_name 46 | return region 47 | 48 | def process_subscription_notification(event): 49 | """ 50 | param: event: AWS log event. 51 | 52 | Decompresses the data from an AWS Log Event and returns a standard dict. 53 | """ 54 | zipped = base64.standard_b64decode(event['awslogs']['data']) 55 | unzipped_string = zlib.decompress(zipped, 16+zlib.MAX_WBITS) 56 | event_dict = ast.literal_eval(unzipped_string.decode('utf-8')) 57 | return event_dict 58 | 59 | def post(event, context): 60 | """ 61 | :param event: AWS Log Event. 62 | :param context: Object to determine runtime info of the Lambda function. 63 | 64 | See http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html for more info 65 | on context. 66 | Process an AWS Log event and post it to a Slack channel via workflow. 67 | """ 68 | 69 | WEBHOOK = read_webhook() 70 | 71 | event_processed = process_subscription_notification(event) 72 | 73 | for log_event in event_processed['logEvents']: 74 | 75 | message = log_event['message'] 76 | for entry in NO_ALERT: 77 | if entry in message: 78 | return "Success" 79 | headers = { 80 | "content-type": "application/json"} 81 | datastr = json.dumps({ 82 | "account": get_account_alias(), 83 | "message": message, 84 | "region": determine_region() 85 | }) 86 | datastr = datastr.encode('utf-8') 87 | request = Request(WEBHOOK, headers=headers, data=datastr) 88 | request.add_header('Content-Length', len(datastr)) 89 | uopen = urlopen(request) 90 | uopen.close() 91 | assert uopen.code == 200 92 | return "Success" 93 | -------------------------------------------------------------------------------- /lambdas/ec2/deploy_reaper.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Parameters: 3 | TerminatorRate: 4 | Type: String 5 | Default: rate(1 hour) 6 | Description: The rate at which to check for expired instances 7 | 8 | SLACKWEBHOOK: 9 | Type: String 10 | Description: Webhook to use when posting notifications to Slack 11 | 12 | LIVEMODE: 13 | Type: String 14 | Default: "False" 15 | Description: Toggle for if the reaper actually deletes ec2 instances. 16 | 17 | S3BucketPrefix: 18 | Type: String 19 | Default: ec2-reaper 20 | Description: Prefix for the S3 Bucket with resources created by the deploy_to_s3 job. 21 | 22 | Resources: 23 | ReaperRole: 24 | Type: AWS::IAM::Role 25 | Properties: 26 | AssumeRolePolicyDocument: 27 | Version: "2012-10-17" 28 | Statement: 29 | - 30 | Effect: "Allow" 31 | Principal: 32 | Service: 33 | - 'lambda.amazonaws.com' 34 | Action: 35 | - "sts:AssumeRole" 36 | ManagedPolicyArns: 37 | - arn:aws:iam::aws:policy/AmazonEC2FullAccess 38 | - arn:aws:iam::aws:policy/AWSLambda_FullAccess 39 | - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 40 | - arn:aws:iam::aws:policy/IAMReadOnlyAccess 41 | - arn:aws:iam::aws:policy/CloudWatchActionsEC2Access 42 | 43 | LambdaTerminator: 44 | Type: AWS::Lambda::Function 45 | Properties: 46 | Code: 47 | S3Key: reaper.zip 48 | S3Bucket: !Sub "${S3BucketPrefix}-${AWS::Region}" 49 | Handler: reaper.terminate_expired_instances 50 | Environment: 51 | Variables: 52 | LIVEMODE: !Ref LIVEMODE 53 | Timeout: 300 54 | Runtime: python3.13 55 | Role: !GetAtt ReaperRole.Arn 56 | DependsOn: ReaperRole 57 | 58 | LambdaTerminatorRule: 59 | Type: AWS::Events::Rule 60 | Properties: 61 | Description: Rule for Terminator Lambda 62 | ScheduleExpression: !Ref TerminatorRate 63 | State: ENABLED 64 | Targets: 65 | - 66 | Arn: !GetAtt LambdaTerminator.Arn 67 | Id: !Ref LambdaTerminator 68 | 69 | LambdaTerminatorPermission: 70 | Type: AWS::Lambda::Permission 71 | Properties: 72 | Action: lambda:InvokeFunction 73 | FunctionName: !Ref LambdaTerminator 74 | Principal: events.amazonaws.com 75 | SourceArn: !GetAtt LambdaTerminatorRule.Arn 76 | 77 | LambdaSchemaEnforcer: 78 | Type: AWS::Lambda::Function 79 | Properties: 80 | Code: 81 | S3Key: reaper.zip 82 | S3Bucket: !Sub "${S3BucketPrefix}-${AWS::Region}" 83 | Handler: reaper.enforce 84 | Environment: 85 | Variables: 86 | LIVEMODE: !Ref LIVEMODE 87 | Timeout: 300 88 | Runtime: python3.13 89 | Role: !GetAtt ReaperRole.Arn 90 | DependsOn: ReaperRole 91 | 92 | LambdaSchemaEnforcerRule: 93 | Type: AWS::Events::Rule 94 | Properties: 95 | Description: Rule for enforcer lambda 96 | EventPattern: 97 | source: 98 | - aws.ec2 99 | detail-type: 100 | - EC2 Instance State-change Notification 101 | detail: 102 | state: 103 | - pending 104 | State: ENABLED 105 | Targets: 106 | - 107 | Arn: !GetAtt LambdaSchemaEnforcer.Arn 108 | Id: !Ref LambdaSchemaEnforcer 109 | 110 | LambdaSchemaEnforcerPermission: 111 | Type: AWS::Lambda::Permission 112 | Properties: 113 | Action: lambda:InvokeFunction 114 | FunctionName: !Ref LambdaSchemaEnforcer 115 | Principal: events.amazonaws.com 116 | SourceArn: !GetAtt LambdaSchemaEnforcerRule.Arn 117 | 118 | LambdaTerminatorLogGroup: 119 | Type: AWS::Logs::LogGroup 120 | Properties: 121 | LogGroupName: !Sub "/aws/lambda/${LambdaTerminator}" 122 | RetentionInDays: 7 123 | 124 | LambdaSchemaEnforcerLogGroup: 125 | Type: AWS::Logs::LogGroup 126 | Properties: 127 | LogGroupName: !Sub "/aws/lambda/${LambdaSchemaEnforcer}" 128 | RetentionInDays: 7 129 | 130 | LambdaSlackNotifierLogGroup: 131 | Type: AWS::Logs::LogGroup 132 | Properties: 133 | LogGroupName: !Sub "/aws/lambda/${LambdaSlackNotifier}" 134 | RetentionInDays: 7 135 | 136 | LambdaSlackNotifier: 137 | Type: AWS::Lambda::Function 138 | Properties: 139 | Code: 140 | S3Key: slack_notifier.zip 141 | S3Bucket: !Sub "${S3BucketPrefix}-${AWS::Region}" 142 | Handler: slack_notifier.post 143 | Timeout: 300 144 | Runtime: python3.13 145 | Role: !GetAtt ReaperRole.Arn 146 | Environment: 147 | Variables: 148 | SLACKWEBHOOK: !Ref SLACKWEBHOOK 149 | DependsOn: ReaperRole 150 | 151 | SchemaEnforcerSlackNotifierSubscription: 152 | Type: AWS::Logs::SubscriptionFilter 153 | Properties: 154 | DestinationArn: !GetAtt LambdaSlackNotifier.Arn 155 | FilterPattern: REAPER TERMINATION 156 | LogGroupName: !Ref LambdaSchemaEnforcerLogGroup 157 | DependsOn: SchemaEnforcerSlackNotifierPermission 158 | 159 | TerminatorSlackNotifierSubscription: 160 | Type: AWS::Logs::SubscriptionFilter 161 | Properties: 162 | DestinationArn: !GetAtt LambdaSlackNotifier.Arn 163 | FilterPattern: REAPER TERMINATION 164 | LogGroupName: !Ref LambdaTerminatorLogGroup 165 | DependsOn: TerminatorSlackNotifierPermission 166 | 167 | TerminatorSlackNotifierPermission: 168 | Type: AWS::Lambda::Permission 169 | Properties: 170 | Action: lambda:InvokeFunction 171 | FunctionName: !Ref LambdaSlackNotifier 172 | Principal: !Sub "logs.${AWS::Region}.amazonaws.com" 173 | SourceArn: !Sub 174 | - ${LogGroupArn} 175 | - { LogGroupArn: !GetAtt LambdaTerminatorLogGroup.Arn } 176 | 177 | SchemaEnforcerSlackNotifierPermission: 178 | Type: AWS::Lambda::Permission 179 | Properties: 180 | Action: lambda:InvokeFunction 181 | FunctionName: !Ref LambdaSlackNotifier 182 | Principal: !Sub "logs.${AWS::Region}.amazonaws.com" 183 | SourceArn: !Sub 184 | - ${LogGroupArn} 185 | - { LogGroupArn: !GetAtt LambdaSchemaEnforcerLogGroup.Arn } 186 | -------------------------------------------------------------------------------- /lambdas/ec2/deploy_to_s3.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | AWSTemplateFormatVersion: '2010-09-09' 3 | 4 | Parameters: 5 | OriginalS3Bucket: 6 | Type: String 7 | Default: reaperfiles 8 | Description: Original bucket that the reaper script resides in. 9 | 10 | OriginalReaperZip: 11 | Type: String 12 | Default: reaper.zip 13 | Description: Key for the reaper.zip file in the S3 bucket. 14 | 15 | OriginalSlackNotifierZip: 16 | Type: String 17 | Default: slack_notifier.zip 18 | Description: Key for the slack_notifier.zip file in the S3 bucket. 19 | 20 | S3BucketPrefix: 21 | Type: String 22 | Default: ec2-reaper 23 | Description: Prefix for the S3 Bucket Name in each region. 24 | 25 | Resources: 26 | S3CopierRole: 27 | Properties: 28 | AssumeRolePolicyDocument: 29 | Statement: 30 | - 31 | Action: 32 | - "sts:AssumeRole" 33 | Effect: Allow 34 | Principal: 35 | Service: 36 | - lambda.amazonaws.com 37 | Version: "2012-10-17" 38 | Path: / 39 | Policies: 40 | - 41 | PolicyDocument: 42 | Statement: 43 | - 44 | Action: 45 | - "logs:CreateLogGroup" 46 | - "logs:CreateLogStream" 47 | - "logs:PutLogEvents" 48 | Effect: Allow 49 | Resource: "arn:aws:logs:*:*:*" 50 | - 51 | Action: 52 | - "s3:*" 53 | Effect: Allow 54 | Resource: "*" 55 | Version: "2012-10-17" 56 | PolicyName: root 57 | Type: "AWS::IAM::Role" 58 | 59 | S3Bucket: 60 | Type: "AWS::S3::Bucket" 61 | Properties: 62 | BucketName: !Sub "${S3BucketPrefix}-${AWS::Region}" 63 | AccessControl: PublicRead 64 | 65 | S3CopierLambda: 66 | Properties: 67 | Timeout: 180 68 | Code: 69 | ZipFile: 70 | !Sub | 71 | import boto3 72 | import json 73 | import sys 74 | import traceback 75 | 76 | try: 77 | from urllib2 import HTTPError, build_opener, HTTPHandler, Request 78 | except ImportError: 79 | from urllib.error import HTTPError 80 | from urllib.request import build_opener, HTTPHandler, Request 81 | 82 | SUCCESS = "SUCCESS" 83 | FAILED = "FAILED" 84 | s3 = boto3.resource('s3') 85 | def handler(event, context): 86 | print event 87 | try: 88 | if event['RequestType'] == 'Delete': 89 | print('Deletion request received') 90 | bucket = s3.Bucket(event['ResourceProperties']['NewBucket']) 91 | bucket.objects.all().delete() 92 | send(event, context, SUCCESS) 93 | return 94 | copy_source = {'Bucket': event['ResourceProperties']['OrigBucketName'], 95 | 'Key': event['ResourceProperties']['OrigReaperKey']} 96 | s3.meta.client.copy(copy_source, 97 | event['ResourceProperties']['NewBucket'], 98 | event['ResourceProperties']['OrigReaperKey']) 99 | s3.ObjectAcl(event['ResourceProperties']['NewBucket'], 100 | event['ResourceProperties']['OrigReaperKey']).put(ACL='public-read') 101 | slack_notifier_copy_source = {'Bucket': event['ResourceProperties']['OrigBucketName'], 102 | 'Key': event['ResourceProperties']['OrigSlackNotifierKey']} 103 | s3.meta.client.copy(slack_notifier_copy_source, 104 | event['ResourceProperties']['NewBucket'], 105 | event['ResourceProperties']['OrigSlackNotifierKey']) 106 | s3.ObjectAcl(event['ResourceProperties']['NewBucket'], 107 | event['ResourceProperties']['OrigSlackNotifierKey']).put(ACL='public-read') 108 | except Exception as e: 109 | print('Error copying S3 data') 110 | exc_type, exc_value, exc_traceback = sys.exc_info() 111 | traceback.print_exception(exc_type, exc_value, exc_traceback, 112 | limit=2, file=sys.stdout) 113 | send(event, context, FAILED) 114 | send(event, context, SUCCESS) 115 | 116 | def send(event, context, response_status, reason=None, response_data=None, physical_resource_id=None): 117 | response_data = response_data or {} 118 | response_body = json.dumps( 119 | { 120 | 'Status': response_status, 121 | 'Reason': reason or "See the details in CloudWatch Log Stream: " + context.log_stream_name, 122 | 'PhysicalResourceId': physical_resource_id or context.log_stream_name, 123 | 'StackId': event['StackId'], 124 | 'RequestId': event['RequestId'], 125 | 'LogicalResourceId': event['LogicalResourceId'], 126 | 'Data': response_data 127 | } 128 | ) 129 | 130 | opener = build_opener(HTTPHandler) 131 | request = Request(event['ResponseURL'], data=response_body) 132 | request.add_header('Content-Type', '') 133 | request.add_header('Content-Length', len(response_body)) 134 | request.get_method = lambda: 'PUT' 135 | try: 136 | response = opener.open(request) 137 | print("Status code: {}".format(response.getcode())) 138 | print("Status message: {}".format(response.msg)) 139 | return True 140 | except HTTPError as exc: 141 | print("Failed executing HTTP request: {}".format(exc.code)) 142 | return False 143 | Handler: index.handler 144 | Role: !GetAtt S3CopierRole.Arn 145 | Runtime: python2.7 146 | Type: "AWS::Lambda::Function" 147 | 148 | S3CopierLambdaTrigger: 149 | Type: Custom::LambdaTrigger 150 | Properties: 151 | ServiceToken: !GetAtt S3CopierLambda.Arn 152 | OrigBucketName: !Ref OriginalS3Bucket 153 | OrigReaperKey: !Ref OriginalReaperZip 154 | OrigSlackNotifierKey: !Ref OriginalSlackNotifierZip 155 | NewBucket: !Ref S3Bucket 156 | -------------------------------------------------------------------------------- /tests/lambdas/test_reaper.py: -------------------------------------------------------------------------------- 1 | # Standard library imports 2 | from unittest.mock import patch 3 | from unittest.mock import MagicMock 4 | 5 | # Reaper import 6 | import lambdas.ec2.reaper as reaper 7 | 8 | @patch.object(reaper, 'os') 9 | def test_determine_live_mode(mock_os): 10 | mock_os.environ = {'LIVEMODE': 'true'} 11 | assert reaper.determine_live_mode() == True 12 | 13 | mock_os.environ = {'NO_LIVE_MODE': 'true'} 14 | assert reaper.determine_live_mode() == False 15 | 16 | mock_os.environ = {'LIVE_MODE': 'false'} 17 | assert reaper.determine_live_mode() == False 18 | 19 | def test_validate_lifetime_value(): 20 | assert reaper.validate_lifetime_value('indefinite') == ('indefinite') 21 | assert reaper.validate_lifetime_value('5m') == (5, 'm') 22 | assert reaper.validate_lifetime_value('2h') == (2, 'h') 23 | assert reaper.validate_lifetime_value('2d') == (2, 'd') 24 | assert reaper.validate_lifetime_value('2w') == (2, 'w') 25 | assert reaper.validate_lifetime_value('42w') == (42, 'w') 26 | assert reaper.validate_lifetime_value('2t') is None 27 | 28 | def test_calculate_lifetime_delta(): 29 | minute = reaper.validate_lifetime_value('1m') 30 | delta = reaper.calculate_lifetime_delta(minute) 31 | assert delta.total_seconds() == 60 32 | 33 | hour = reaper.validate_lifetime_value('1h') 34 | delta = reaper.calculate_lifetime_delta(hour) 35 | assert delta.total_seconds() == 3600 36 | 37 | day = reaper.validate_lifetime_value('1d') 38 | delta = reaper.calculate_lifetime_delta(day) 39 | assert delta.total_seconds() == 86400 40 | 41 | week = reaper.validate_lifetime_value('1w') 42 | delta = reaper.calculate_lifetime_delta(week) 43 | assert delta.total_seconds() == 604800 44 | 45 | def test_get_tag(): 46 | ec2_mock = MagicMock() 47 | ec2_mock.tags = None 48 | assert reaper.get_tag(ec2_mock, 'some_tag') is None 49 | 50 | ec2_mock.tags = [{'Key': 'no_match_', 'Value': 'no_match_value'}] 51 | assert reaper.get_tag(ec2_mock, 'some_tag') is None 52 | 53 | ec2_mock.tags = [{'Key': 'match', 'Value': 'match_value'}] 54 | assert reaper.get_tag(ec2_mock, 'match') is 'match_value' 55 | 56 | def test_terminate_instance(): 57 | with patch.object(reaper, 'LIVEMODE') as mock_live_mode: 58 | 59 | mock_live_mode.return_value = True 60 | ec2_mock = MagicMock() 61 | reaper.terminate_instance(ec2_mock, 'test terminate') 62 | ec2_mock.terminate.assert_called_with() 63 | 64 | mock_live_mode.return_value = False 65 | ec2_mock2 = MagicMock() 66 | reaper.terminate_instance(ec2_mock, 'test terminate') 67 | ec2_mock2.terminate.assert_not_called() 68 | 69 | def test_stop_instance(): 70 | with patch.object(reaper, 'LIVEMODE') as mock_live_mode: 71 | 72 | mock_live_mode.return_value = True 73 | ec2_mock = MagicMock() 74 | reaper.stop_instance(ec2_mock, 'test stop') 75 | ec2_mock.stop.assert_called_with() 76 | 77 | mock_live_mode.return_value = False 78 | ec2_mock2 = MagicMock() 79 | reaper.stop_instance(ec2_mock, 'test stop') 80 | ec2_mock2.stop.assert_not_called() 81 | 82 | @patch.object(reaper, 'get_tag') 83 | @patch.object(reaper, 'terminate_instance') 84 | def test_validate_ec2_termination_date(mock_terminate_instance, mock_get_tag): 85 | ec2_mock = MagicMock() 86 | 87 | mock_get_tag.return_value = reaper.timenow_with_utc().isoformat() 88 | reaper.validate_ec2_termination_date(ec2_mock) 89 | mock_terminate_instance.assert_called_with(ec2_mock, 'The termination_date has passed') 90 | 91 | mock_terminate_instance.reset_mock() 92 | mock_get_tag.return_value = (reaper.timenow_with_utc() + reaper.datetime.timedelta(hours=1)).isoformat() 93 | reaper.validate_ec2_termination_date(ec2_mock) 94 | mock_terminate_instance.assert_not_called() 95 | 96 | @patch.object(reaper, 'calculate_lifetime_delta') 97 | @patch.object(reaper, 'get_tag') 98 | @patch.object(reaper, 'LIVEMODE') 99 | def test_wait_for_tags(mock_live_mode, mock_get_tag, mock_calculate_lifetime_delta): 100 | # When elapsed time to wait is 0, assert terminate is called 101 | mock_ec2_instance = MagicMock() 102 | mock_live_mode.return_value = True 103 | reaper.wait_for_tags(mock_ec2_instance, 0) 104 | mock_ec2_instance.terminate.assert_called_with() 105 | 106 | 107 | with patch.object(reaper, 'validate_lifetime_value') as mock_validate_lifetime_value: 108 | # When the time is in the future, assert terminate is not called 109 | mock_ec2_instance.reset_mock() 110 | mock_validate_lifetime_value.return_value = 2, 'w' 111 | # We use side_effect to mock the initial get_tag call for 'termination_date', 112 | # return a valid lifetime tag, and then return True for the next get_tag call for 113 | # the termination_date 114 | mock_get_tag.side_effect = [None, '2w', True] 115 | reaper.wait_for_tags(mock_ec2_instance, 1) 116 | mock_ec2_instance.terminate.assert_not_called() 117 | mock_ec2_instance.create_tags.assert_called() 118 | 119 | mock_ec2_instance.reset_mock() 120 | # We use side_effect to mock the initial get_tag call for 'termination_date', and 121 | # then return True for the next get_tag call for 'lifetime' 122 | mock_get_tag.side_effect = [None, True] 123 | mock_validate_lifetime_value.return_value = None 124 | reaper.wait_for_tags(mock_ec2_instance, 1) 125 | mock_ec2_instance.terminate.assert_called_with() 126 | 127 | @patch.object(reaper, 'ec2') 128 | @patch.object(reaper, 'wait_for_tags') 129 | @patch.object(reaper, 'validate_ec2_termination_date') 130 | def test_enforce(mock_validate_ec2_termination_date, mock_wait_for_tags, mock_ec2): 131 | event = {'detail': {'instance-id': 'test_instance_id' }} 132 | reaper.enforce(event, 'context') 133 | mock_ec2.Instance.assert_called_with(id=event['detail']['instance-id']) 134 | mock_wait_for_tags.assert_called() 135 | mock_validate_ec2_termination_date.assert_called() 136 | 137 | @patch.object(reaper, 'get_tag') 138 | @patch.object(reaper, 'LIVEMODE') 139 | @patch.object(reaper, 'ec2') 140 | def test_terminate_expired_instances(mock_ec2, mock_live_mode, mock_get_tag): 141 | mock_get_tag.return_value = reaper.timenow_with_utc().isoformat() 142 | mock_ec2_instance = MagicMock() 143 | mock_ec2.instances.filter.return_value = [mock_ec2_instance] 144 | mock_live_mode.return_value = True 145 | reaper.terminate_expired_instances('event', 'context') 146 | mock_ec2_instance.terminate.assert_called_with() 147 | 148 | # ensure that the reaper does not terminate instances with a valid future 149 | # termination_date 150 | mock_get_tag.return_value = (reaper.timenow_with_utc() + reaper.datetime.timedelta(hours=1)).isoformat() 151 | mock_ec2_instance.reset_mock() 152 | reaper.terminate_expired_instances('event', 'context') 153 | mock_ec2_instance.terminate.assert_not_called() 154 | 155 | #ensure that the reaper does not terminate instances with valid 156 | #indefinite tag for termination_date 157 | indefinite = 'indefinite' 158 | mock_get_tag.return_value = indefinite 159 | mock_ec2_instance.reset_mock() 160 | reaper.terminate_expired_instances('event', 'context') 161 | mock_ec2_instance.terminate.assert_not_called() 162 | 163 | #ensure that reaper stops instances with missing 164 | #tag for termination_date 165 | none_tag = None 166 | mock_get_tag.return_value = none_tag 167 | mock_ec2_instance.reset_mock() 168 | reaper.terminate_expired_instances('event', 'context') 169 | mock_ec2_instance.stop.assert_called() 170 | 171 | #ensure that reaper stops instances with 172 | #incorrect tag for termination_date 173 | incorrect_tag = '3/7/2018' 174 | mock_get_tag.return_value = incorrect_tag 175 | mock_ec2_instance.reset_mock() 176 | reaper.terminate_expired_instances('event', 'context') 177 | mock_ec2_instance.stop.assert_called() 178 | -------------------------------------------------------------------------------- /lambdas/ec2/README.md: -------------------------------------------------------------------------------- 1 | # AWS EC2 Reaper 2 | 3 | This AWS EC2 Reaper works using tags set on the instance itself. The Reaper is 4 | composed of two AWS Lambdas: the "Schema Enforcer" and the "Terminator". The 5 | Schema Enforcer ensures that all new instances have been correctly tagged, and 6 | the Terminator runs periodically to terminate all running instances past their 7 | termination date. 8 | 9 | ## Rules and Usage 10 | 11 | **TL;DR** Tag an instance with a `lifetime` tag on creation. A valid `lifetime` 12 | tag is a string of an integer value with a 1 letter unit of w(weeks), d(days), 13 | h(hours). For example, `1w` is 1 week, `2d` is 2 days, and `3h` is 3 hours. 14 | 15 | 1. The Schema Enforcer ensures that a newly created EC2 instance has a valid 16 | future date set for termination. The Schema Enforcer looks for a `lifetime` tag 17 | to determine that date. A valid `lifetime` tag is a string of an integer 18 | value with a 1 letter unit of w(weeks), d(days), h(hours). For example, `1w` is 19 | 1 week, `2d` is 2 days, and `3h` is 3 hours. The Schema Enforcer will calculcate 20 | a future date based upon the `lifetime` tag and set a new `termination_date` tag 21 | on that instance. 22 | * Instead of setting the `lifetime` tag, you can set a `termination_date` 23 | tag directly to specify the date the instance expires. A `termination_date` 24 | must be a valid IS0 8601 value with a UTC offset defined. 25 | 2. If there is an error determining the future termination date, the instance is 26 | terminated. If 4 minutes elapse and no future termination date has been 27 | determined, the instance is terminated. 28 | 3. The Terminator runs periodically to ensure that all EC2 instances are 29 | terminated if they are past their `termination_date`. If an instance needs its 30 | lifetime extended beyond its original future terminatation date, the 31 | `termination_date` tag should be updated directly. 32 | 33 | ### Example: 34 | 35 | Let's say you're using Packer to build an AMI. If you don't tag it properly, the 36 | Reaper will probably identify it as an untagged rogue instance before it's completed 37 | and terminate it. To prevent that, make sure you set the `run_tags` key in your build 38 | JSON file. 39 | 40 | ``` json 41 | { 42 | "builders": [ 43 | { 44 | "type": "amazon-ebs", 45 | "region": "us-west-2", 46 | "source_ami": "ami-c7d092f7", 47 | "instance_type": "m3.large", 48 | "ssh_username": "centos", 49 | "ami_name": "Example AMI", 50 | "ssh_pty": "true", 51 | "run_tags": { 52 | "created_by": "", 53 | "department": "", 54 | "project": "vm_publish", 55 | "lifetime": "1h" 56 | } 57 | } 58 | ], 59 | "..." 60 | } 61 | ``` 62 | 63 | ## Implementation and Details 64 | The following sections are details meant for people implementing the AWS 65 | EC2 Reaper. 66 | 67 | ### Installation 68 | 69 | Installation of the reaper is accomplished by using cloudformation templates found 70 | in the reaperfiles S3 folder. These templates are designed to be used with stacksets 71 | to deploy the reaper across several accounts. 72 | 73 | #### Prequisites 74 | 75 | The directions from AWS [here](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs.html) 76 | should be completed before use of the Cloudformation template. 77 | 78 | A few things to note: 79 | 1. The *administrative account* needs the administrative role as well as the 80 | execution role. This ensures that deploying the `deploy_to_s3.yaml` can create the 81 | necessary S3 buckets in each region in the administrative account for the Reaper 82 | Lambdas to read from. 83 | 2. Both roles should be created by deploying cloudformation stacks using the templates in the documentation linked above. You can download the templates by clicking the link in the documentation to the yaml files. You can follow the steps to create a new stack [here](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) 84 | 3. Make sure to set a stack name that relates to what the stack does (like aws-cf-ar for the aws cloudformation administrator role stack), and use the administrative account ID for the AdministratorAccountID field. 85 | 4. The Administrator role stack only needs to be deployed into the administrative account. The Execution role needs to be deployed into all accounts and the administrative account. 86 | 87 | #### deploy_to_s3 Cloudformation template 88 | 89 | This template places the lambda zip resources in S3 buckets in every region so that 90 | the `deploy_reaper` template can read them for Reaper deployment. In order to use 91 | this template, you must first manually create an S3 bucket that contains the 92 | resources to copy across all regions. You will need to do this once per region; 93 | S3 resources can be read between accounts but not between regions for AWS Lambda. 94 | This only needs to be done one time for the administrative account. If new regions 95 | are added you can just perform step 3 and list the new region. 96 | 97 | 1. Manually create an S3 bucket accessible from the administrative account. Zip up the 98 | two python reaper files, `reaper.py` and `slack_notifier.py` and place them in the 99 | bucket, naming them `reaper.zip` and `slack_notifier.zip`. 100 | 101 | 2. From the administrative account, create a new stack set and use the `deploy_to_s3` 102 | template. An example CLI invocation would look like: 103 | 104 | ``` 105 | aws cloudformation create-stack-set --stack-set-name reaper-assets --template-body 106 | file://path/to/deploy_to_s3.yaml --capabilities CAPABILITY_IAM --parameters 107 | ParameterKey=OriginalS3Bucket,ParameterValue=reaperfiles 108 | ``` 109 | 110 | 3. Deploy stack-set-instances for this stack set, one per region in the administrative 111 | account. Check the Amazon documentation for the most up-to-date region list. 112 | 113 | ``` 114 | aws cloudformation create-stack-instances --stack-set-name --accounts 123456789012 115 | --regions "us-west-1" "us-west-2" "eu-west-1" ... 116 | ``` 117 | 118 | #### deploy_reaper Cloudformation template 119 | 120 | After the resources for the reaper have been distributed, you can use the `deploy_reaper` 121 | Cloudformation template to deploy the reaper into an account. That template can be found 122 | in the folder lambdas/ec2/ in this repository. 123 | 124 | The template has five parameters it uses when creating a stack set. They are listed below 125 | along with their default values (parameters are case sensitive): 126 | 127 | 1. SLACKWEBHOOK=none 128 | 3. TerminatorRate=rate(1 hour) 129 | 4. LIVEMODE=FALSE 130 | 5. S3BucketPrefix=ec2-reaper 131 | 132 | In order to deploy the reaper you must supply the `SLACKWEBHOOK` parameter 133 | value for the `slack_notifier` Lambda to communicate to the Slack channel. 134 | Setting LIVEMODE to TRUE will enable the reaper to terminate instances immediately upon stack 135 | instance deployment. 136 | The TerminatorRate and S3BucketPrefix values can be left as is, and shouldn't ever need set explicitly 137 | 138 | You will need to follow the steps below for each account you are deploying the reaper into. 139 | 140 | 1. First, create a stack set representing the account you wish to run the reaper in. 141 | 142 | ``` 143 | aws cloudformation create-stack-set --stack-set-name reaper-aws-account --template-body 144 | file://path/to/deploy_reaper.yaml --capabilities CAPABILITY_IAM --parameters 145 | ParameterKey=SLACKWEBHOOK,ParameterValue=1234567 ... 146 | ``` 147 | 148 | 2. Deploy the reaper into the account. 149 | 150 | ``` 151 | aws cloudformation create-stack-instances --stack-set-name reaper-aws-account --accounts 152 | 098765432109 --regions "us-west-1" "us-west-2" "eu-west-1" ... 153 | ``` 154 | 155 | ### Turning the Reaper On 156 | 157 | Don't fear the Reaper is turned on after the stack instances are created; they will not 158 | reap anything unless the environment variable `LIVEMODE` is set to `TRUE`. It will 159 | only report what it would have done to Slack. 160 | 161 | When the time comes to activate the Reaper, update the parameter value `LIVEMODE` to 162 | "TRUE"(the regex is case-insensitive). 163 | 164 | ``` 165 | aws cloudformation update-stack-set --stack-set-name reaper-aws-account 166 | --use-previous-template --parameters ParameterKey=LIVEMODE,ParameterValue=TRUE --capabilities CAPABILITY_IAM 167 | ``` 168 | 169 | #### Testing 170 | 171 | Run the reaper in no-op mode and ensure that it is behaving as expected; use the 172 | slack_notifier to get clean reporting, or look at the AWS logs directly. To run 173 | the unit tests, install nose on your system and run `nose tests/lambdas/` from the 174 | root of this repository. 175 | 176 | ### Components 177 | 178 | #### Schema Enforcer 179 | The Schema Enforcer is an AWS Lambda that is designed to be triggered when an EC2 180 | instance enters the 'pending' state. This AWS Lambda waits for an EC2 instance to 181 | have a valid `termination_date` tag associated with it. This AWS Lambda also 182 | listens for a `lifetime` tag; if found, it calculates a new future date and adds 183 | that date as the `termination_date` for the instance. 184 | 185 | The Schema Enforcer terminates instances that do not have valid tags, or if the 186 | timeout period MINUTES_TO_WAIT has elapsed. Unhandled errors are raised, but the 187 | Schema Enforcer does not terminate the instance in these cases. The Schema 188 | Enforcer does not terminate instances after the schema has been enforced; the 189 | Terminator is responsible for that. 190 | 191 | #### Terminator 192 | The Terminator is a simple AWS Lambda that looks for a `termination_date` tag on 193 | an instance and terminates it if it is past its `termination_date`. If the 194 | `termination_date` is missing or malformed, the script logs those instances in its 195 | output. This AWS Lambda is designed to be run periodically; depending on 196 | your needs, every 15 minutes should be more than sufficient. The Terminator does 197 | not ensure that EC2 instances have valid tags; the Schema Enforcer is responsible 198 | for that. 199 | 200 | The `termination_date` must be in a IS0-8601 format with a UTC offset. 201 | 202 | #### Slack Notifier 203 | The Slack Notifier is a separate Lambda that can run and post data about 204 | terminated instances; it runs in its own Lambda, tied to the output of both the 205 | Schema Enforcer and Terminator looking for a "REAPER TERMINATION" string match in 206 | the output of the either Lambda. A Cloudwatch Log trigger with a filter pattern 207 | or `REAPER TERMINATION` should be attached to this Lambda, and a Slack channel webhook 208 | should be set as an environment variable. You will need to create a Slack workflow 209 | in each channel that should receive notifications. The variables to use are as follows: 210 | 211 | - *account:* The account's alias according to AWS. 212 | - *message:* The REAPER TERMINATION string, i.e. the log entry 213 | - *region:* The AWS region the reaper's running in. 214 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lambdas/ec2/reaper.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import datetime 4 | import time 5 | import dateutil 6 | import re 7 | import os 8 | from warnings import warn 9 | import boto3 10 | 11 | ec2 = boto3.resource('ec2') 12 | 13 | def determine_live_mode(): 14 | """ 15 | Returns True if LIVEMODE is set to true in the shell environment, False for 16 | all other cases. 17 | """ 18 | if 'LIVEMODE' in os.environ: 19 | return re.search(r'(?i)^true$', os.environ['LIVEMODE']) is not None 20 | else: 21 | return False 22 | 23 | # The `LIVEMODE` environment variable controls if this script is actually 24 | # running and reaping in your AWS environment. To turn reaping on, set 25 | # the `LIVEMODE` environment variable to true in your Lambda environment. 26 | LIVEMODE = determine_live_mode() 27 | 28 | # The `MINUTES_TO_WAIT` global variable is the number of minutes to wait for 29 | # a termination_date tag to appear for the EC2 instance. Please note that the 30 | # AWS Lambdas are limited to a 5 minute maximum for their total run time. 31 | MINUTES_TO_WAIT = 4 32 | 33 | #The Indefinite lifetime constant 34 | INDEFINITE = 'indefinite' 35 | 36 | def get_tag(ec2_instance, tag_name): 37 | """ 38 | :param ec2_instance: a boto3 resource representing an Amazon EC2 Instance. 39 | :param tag_name: A string of the key name you are searching for. 40 | 41 | This method returns None if the ec2 instance currently has no tags 42 | or if the tag is not found. If the tag is found, it returns the tag 43 | value. 44 | """ 45 | if ec2_instance.tags is None: 46 | return None 47 | for tag in ec2_instance.tags: 48 | if tag['Key'] == tag_name: 49 | return tag['Value'] 50 | return None 51 | 52 | def timenow_with_utc(): 53 | """ 54 | Return a datetime object that includes the tzinfo for utc time. 55 | """ 56 | time = datetime.datetime.utcnow() 57 | time = time.replace(tzinfo=dateutil.tz.tz.tzutc()) 58 | return time 59 | 60 | def wait_for_tags(ec2_instance, wait_time): 61 | """ 62 | :param ec2_instance: a boto3 resource representing an Amazon EC2 Instance 63 | :param wait_time: The number of minutes to wait for the 'termination_date' 64 | 65 | This method returns when a 'termination_date' is found and raises an exception 66 | and terminates the instance when the wait_time has passed. The method looks 67 | for the 'lifetime' key, parses it, and sets the 'termination_date' on the 68 | instance. The 'termination_date' can be set directly on the instance, bypassing 69 | the steps to parse the lifetime key and allowing this to return. 70 | 71 | This returns the termination_date value if successful; otherwise, it returns 72 | None. 73 | """ 74 | start = timenow_with_utc() 75 | timeout = start + datetime.timedelta(minutes=wait_time) 76 | 77 | while timenow_with_utc() < timeout: 78 | ec2_instance.load() 79 | termination_date = get_tag(ec2_instance, 'termination_date') 80 | if termination_date: 81 | print("'termination_date' tag found!") 82 | return termination_date 83 | instance_name = get_tag(ec2_instance, 'Name') 84 | try: 85 | if 'opsworks' in instance_name: 86 | ec2_instance.create_tags( 87 | Tags=[ 88 | { 89 | 'Key': 'termination_date', 90 | 'Value': INDEFINITE 91 | } 92 | ] 93 | ) 94 | return 95 | except: 96 | print("No 'Name' tag specified") 97 | lifetime = get_tag(ec2_instance, 'lifetime') 98 | if not lifetime: 99 | print("No 'lifetime' tag found; sleeping for 15s") 100 | time.sleep(15) 101 | continue 102 | print('lifetime tag found') 103 | if lifetime == INDEFINITE: 104 | ec2_instance.create_tags( 105 | Tags=[ 106 | { 107 | 'Key': 'termination_date', 108 | 'Value': INDEFINITE 109 | } 110 | ] 111 | ) 112 | return 113 | lifetime_match = validate_lifetime_value(lifetime) 114 | if not lifetime_match: 115 | terminate_instance(ec2_instance, 'Invalid lifetime value supplied') 116 | return 117 | lifetime_delta = calculate_lifetime_delta(lifetime_match) 118 | future_termination_date = start + lifetime_delta 119 | ec2_instance.create_tags( 120 | Tags=[ 121 | { 122 | 'Key': 'termination_date', 123 | 'Value': future_termination_date.isoformat() 124 | } 125 | ] 126 | ) 127 | 128 | # If the above while condition does not return after finding a termination_date, 129 | # terminate the instance and raise an exception. 130 | terminate_instance(ec2_instance, 131 | 'No termination_date found within {0} minutes of creation'.format(wait_time)) 132 | 133 | 134 | def terminate_instance(ec2_instance, message): 135 | """ 136 | :param ec2_instance: a boto3 resource representing an Amazon EC2 Instance. 137 | :param message: string explaining why the instance is being terminated. 138 | 139 | Prints a message and terminates an instance if LIVEMODE is True. Otherwise, print out 140 | the instance id of EC2 resource that would have been deleted. 141 | """ 142 | output = "REAPER TERMINATION: {1} for ec2_instance_id={0}\n".format(ec2_instance.id, message) 143 | if LIVEMODE: 144 | output += 'REAPER TERMINATION enabled: deleting instance {0}'.format(ec2_instance.id) 145 | print(output) 146 | ec2_instance.terminate() 147 | else: 148 | output += "REAPER TERMINATION not enabled: LIVEMODE is {0}. Would have deleted instance {1}".format(LIVEMODE, ec2_instance.id) 149 | print(output) 150 | 151 | def stop_instance(ec2_instance, message): 152 | """ 153 | 154 | :param ec2_instance: a boto3 resource representing an Amazon EC2 Instance. 155 | :param message: string explaining why the instance is being terminated 156 | 157 | Prints a message and stop an instance if LIVEMODE is True. Otherwise, print out 158 | the instance id of the EC2 resource that would have been deleted 159 | """ 160 | output = "REAPER STOP message (ec2_instance_id{0}): {1}\n".format(ec2_instance.id, message) 161 | if LIVEMODE: 162 | output += 'REAPER STOP enabled: stopping instance {0}'.format(ec2_instance.id) 163 | print(output) 164 | ec2_instance.stop() 165 | else: 166 | output += "REAPER STOP not enabled: LIVEMODE is {0}. Would have stopped instance {1}".format(LIVEMODE, ec2_instance.id) 167 | print(output) 168 | 169 | def validate_ec2_termination_date(ec2_instance): 170 | """ 171 | :param ec2_instance: a boto3 resource representing an Amazon EC2 Instance. 172 | 173 | Validates that an ec2 instance has a valid termination_date in the future. 174 | Otherwise, delete the instance. 175 | """ 176 | termination_date = get_tag(ec2_instance, 'termination_date') 177 | try: 178 | dateutil.parser.parse(termination_date) - timenow_with_utc() 179 | except Exception as e: 180 | if e is TypeError: 181 | if re.search(r'(offset-naive).+(offset-aware)', e.__str__): 182 | terminate_instance(ec2_instance, 183 | 'The termination_date requires a UTC offset') 184 | else: 185 | terminate_instance(ec2_instance, 186 | 'Unable to parse the termination_date') 187 | return 188 | 189 | if dateutil.parser.parse(termination_date) > timenow_with_utc(): 190 | ttl = dateutil.parser.parse(termination_date) - timenow_with_utc() 191 | print("EC2 instance will be terminated {0} seconds from now, roughly".format(ttl.seconds)) 192 | else: 193 | terminate_instance(ec2_instance, 194 | 'The termination_date has passed') 195 | 196 | def validate_lifetime_value(lifetime_value): 197 | """ 198 | :param lifetime_value: A string from your ec2 instance. 199 | 200 | Return a match object if a match is found; otherwise, return the None from the search method. 201 | """ 202 | search_result = re.search(r'^([0-9]+)(w|d|h|m)$', lifetime_value) 203 | if search_result is None: 204 | return None 205 | toople = search_result.groups() 206 | unit = toople[1] 207 | length = int(toople[0]) 208 | return (length, unit) 209 | 210 | def calculate_lifetime_delta(lifetime_tuple): 211 | """ 212 | :param lifetime_match: Resulting regex match object from validate_lifetime_value. 213 | 214 | Check the value of the lifetime. If not indefinite convert the regex match from 215 | `validate_lifetime_value` into a datetime.timedelta. 216 | """ 217 | length = lifetime_tuple[0] 218 | unit = lifetime_tuple[1] 219 | if unit == 'w': 220 | return datetime.timedelta(weeks=length) 221 | elif unit == 'h': 222 | return datetime.timedelta(hours=length) 223 | elif unit == 'd': 224 | return datetime.timedelta(days=length) 225 | elif unit == 'm': 226 | return datetime.timedelta(minutes=length) 227 | else: 228 | raise ValueError("Unable to parse the unit '{0}'".format(unit)) 229 | 230 | 231 | # This is the function that the schema_enforcer lambda should run when an instance hits 232 | # the pending state. 233 | def enforce(event, context): 234 | """ 235 | :param event: AWS CloudWatch event; should be a configured for when the state is pending. 236 | :param context: Object to determine runtime info of the Lambda function. 237 | 238 | See http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html for more info 239 | on context. 240 | """ 241 | print(event) 242 | print(event['detail']['instance-id']) 243 | instance = ec2.Instance(id=event['detail']['instance-id']) 244 | try: 245 | termination_date = wait_for_tags(instance, MINUTES_TO_WAIT) 246 | if termination_date == INDEFINITE: 247 | return 248 | elif termination_date: 249 | validate_ec2_termination_date(instance) 250 | except Exception as e: 251 | # Here we should catch all exceptions, report on the state of the instance, and then 252 | # bubble up the original exception. 253 | instance.load() 254 | warn('Instance {0} current state is {1}. This unexpected exception should be investigated!'.format(instance.id, instance.state['Name'])) 255 | # TODO: add in code to alert somebody exception happened, or remove 256 | # this comment if cloudwatch starts watching for exceptions from 257 | # this lambda 258 | raise 259 | 260 | print('Schema successfully enforced.') 261 | 262 | # This is the function that a terminator lambda should call periodically to delete instances past their 263 | # termination_date. 264 | def terminate_expired_instances(event, context): 265 | """ 266 | :param event: AWS CloudWatch event; should be a Cloudwatch Scheduled Event. 267 | :param context: Object to determine runtime info of the Lambda function. 268 | 269 | See http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html for more info 270 | on context. 271 | """ 272 | improperly_tagged = [] 273 | deleted_instances = [] 274 | 275 | instances = ec2.instances.filter( 276 | Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) 277 | print(instances) 278 | for instance in instances: 279 | ec2_termination_date = get_tag(instance, 'termination_date') 280 | if ec2_termination_date is None: 281 | print("No termination date found for {0}".format(instance.id)) 282 | stop_instance(instance, "EC2 instance has no termination_date") 283 | improperly_tagged.append(instance) 284 | continue 285 | if ec2_termination_date != INDEFINITE: 286 | try: 287 | if dateutil.parser.parse(ec2_termination_date) > timenow_with_utc(): 288 | ttl = dateutil.parser.parse(ec2_termination_date) - timenow_with_utc() 289 | print("EC2 instance will be terminated {0} seconds from now, roughly".format(ttl.seconds)) 290 | else: 291 | terminate_instance(instance, "EC2 instance is expired") 292 | deleted_instances.append(instance) 293 | except Exception as e: 294 | print("Unable to parse the termination_date for {0}".format(instance.id)) 295 | stop_instance(instance, "EC2 instance has invalid termination_date") 296 | improperly_tagged.append(instance) 297 | continue 298 | if ec2_termination_date == INDEFINITE: 299 | continue 300 | 301 | if LIVEMODE: 302 | if len(improperly_tagged) > 0 and len(deleted_instances) < 1: 303 | print(("REAPER TERMINATION completed. The following instances have been stopped due to unparsable or missing termination_date tags: {0}.").format(improperly_tagged)) 304 | elif len(deleted_instances) > 0 and len(improperly_tagged) < 1: 305 | print(("REAPER TERMINATION completed. The following instances have been deleted due to expired termination_date tags: {0}.").format(deleted_instances)) 306 | else: 307 | print(("REAPER TERMINATION completed. The following instances have been deleted due to expired termination_date tags: {0}. " 308 | "The following instances have been stopped due to unparsable or missing termination_date tags: {1}.").format(deleted_instances, improperly_tagged)) 309 | else: 310 | if len(improperly_tagged) > 0 and len(deleted_instances) < 1: 311 | print("REAPER TERMINATION completed. LIVEMODE is off, would have stopped the following instances due to unparsable or missing termination_date tags: {0} ".format(improperly_tagged)) 312 | elif len(deleted_instances) > 0 and len(improperly_tagged) < 1: 313 | print("REAPER TERMINATION completed. LIVEMODE is off, would have deleted the following instances: {0}. ".format(deleted_instances)) 314 | else: 315 | print(("REAPER TERMINATION completed. LIVEMODE is off, would have deleted the following instances: {0}. " 316 | "REAPER would have stopped the following instances due to unparsable or missing termination_date tags: {1}").format(deleted_instances, improperly_tagged)) 317 | --------------------------------------------------------------------------------