|
| 1 | +#// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +#// SPDX-License-Identifier: Apache-2.0 |
| 3 | +# Assisted Log Enabler for AWS - Find resources that are not logging, and turn them on. |
| 4 | +# Joshua "DozerCat" McKiddy - Team DragonCat - AWS |
| 5 | + |
| 6 | + |
| 7 | +import logging |
| 8 | +import os |
| 9 | +import json |
| 10 | +import boto3 |
| 11 | +import time |
| 12 | +import datetime |
| 13 | +from botocore.exceptions import ClientError |
| 14 | +from datetime import timezone |
| 15 | + |
| 16 | + |
| 17 | +current_date = datetime.datetime.now(tz=timezone.utc) |
| 18 | +current_date_string = str(current_date) |
| 19 | +timestamp_date = datetime.datetime.now(tz=timezone.utc).strftime("%Y-%m-%d-%H%M%S") |
| 20 | +timestamp_date_string = str(timestamp_date) |
| 21 | + |
| 22 | + |
| 23 | +logFormatter = '%(asctime)s - %(levelname)s - %(message)s' |
| 24 | +logging.basicConfig(format=logFormatter, level=logging.INFO) |
| 25 | +logger = logging.getLogger() |
| 26 | +logger.setLevel(logging.INFO) |
| 27 | +output_handle = logging.FileHandler('ALE_' + timestamp_date_string + '.log') |
| 28 | +output_handle.setLevel(logging.INFO) |
| 29 | +logger.addHandler(output_handle) |
| 30 | +formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') |
| 31 | +output_handle.setFormatter(formatter) |
| 32 | + |
| 33 | + |
| 34 | +region = os.environ['AWS_REGION'] |
| 35 | + |
| 36 | + |
| 37 | +region_list = ['af-south-1', 'ap-east-1', 'ap-south-1', 'ap-northeast-1', 'ap-northeast-2', 'ap-northeast-3', 'ap-southeast-1', 'ap-southeast-2', 'ca-central-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-north-1', 'eu-south-1', 'me-south-1', 'sa-east-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'] |
| 38 | + |
| 39 | + |
| 40 | +# 1. Remove the Route 53 Resolver Query Logging Resources created by Assisted Log Enabler |
| 41 | +def r53_cleanup(): |
| 42 | + """Function to clean up Route 53 Query Logging Resources""" |
| 43 | + for aws_region in region_list: |
| 44 | + logging.info("---- LINE BREAK BETWEEN REGIONS ----") |
| 45 | + logging.info("Cleaning up Route 53 Query Logging Resources in region " + aws_region + ".") |
| 46 | + route53resolver = boto3.client('route53resolver', region_name=aws_region) |
| 47 | + try: |
| 48 | + QueryLogList: list = [] |
| 49 | + QueryLogArnRemoveList: list = [] |
| 50 | + QueryLogIdRemoveList: list = [] |
| 51 | + logging.info("ListResolverQueryLogConfigs API Call") |
| 52 | + ale_r53_logs = route53resolver.list_resolver_query_log_configs() # Collecting Arn of all Query Logs |
| 53 | + for r53_arn in ale_r53_logs['ResolverQueryLogConfigs']: |
| 54 | + QueryLogList.append(r53_arn['Arn']) |
| 55 | + for r53_tag_info in QueryLogList: |
| 56 | + logging.info("Listing Tags for " + r53_tag_info) |
| 57 | + logging.info("ListTagsForResource API Call") |
| 58 | + r53_tags = route53resolver.list_tags_for_resource( # Looking at tags for each Arn collected |
| 59 | + ResourceArn=r53_tag_info |
| 60 | + ) |
| 61 | + for value in r53_tags['Tags']: |
| 62 | + if (value['Key'] == 'Workflow' and value['Value'] == 'assisted-log-enabler'): |
| 63 | + logging.info("The following Route 53 Query Logger was created by Assisted Log Enabler for AWS, and will be removed within this function: " + r53_tag_info) |
| 64 | + QueryLogArnRemoveList.append(r53_tag_info) |
| 65 | + for Id in QueryLogArnRemoveList: |
| 66 | + logging.info("Gathering Resource ID for Route 53 Query Logging Resource to be removed.") |
| 67 | + logging.info("ListResolverQueryLogConfigs API Call") |
| 68 | + r53_resource_id = route53resolver.list_resolver_query_log_configs()['ResolverQueryLogConfigs'][QueryLogArnRemoveList.index(Id)]['Id'] # Collecting Resource ID for each Arn collected |
| 69 | + QueryLogIdRemoveList.append(r53_resource_id) |
| 70 | + logging.info(r53_resource_id + " added to removal list.") |
| 71 | + logging.info("The following Resource IDs were created by Assisted Log Enabler for AWS, and will be removed within this function.") |
| 72 | + print(QueryLogIdRemoveList) |
| 73 | + for r53_remove in QueryLogIdRemoveList: |
| 74 | + logging.info("Gathering Query Log Config Associations for " + r53_remove) |
| 75 | + logging.info("ListResolverQueryLogConfigAssociations API Call") |
| 76 | + associated_vpcs = route53resolver.list_resolver_query_log_config_associations( |
| 77 | + ) |
| 78 | + if associated_vpcs['TotalCount'] > 0 and associated_vpcs['ResolverQueryLogConfigAssociations'][0]['ResolverQueryLogConfigId'] == r53_remove: |
| 79 | + logging.info("The following Route 53 Query Logger is associated with a VPC, and will be removed within this function: " + r53_remove) |
| 80 | + VPCRemovalList = [] |
| 81 | + for vpc_info in associated_vpcs['ResolverQueryLogConfigAssociations']: |
| 82 | + VPCRemovalList.append(vpc_info['ResourceId']) |
| 83 | + logging.info("List of VPCs to be disassociated:") |
| 84 | + print(VPCRemovalList) |
| 85 | + for vpc in VPCRemovalList: |
| 86 | + logging.info("Removing " + vpc + " from Route 53 Query Logging configuration " + r53_remove) |
| 87 | + logging.info("DisassociateResolverQueryLogConfig API Call") |
| 88 | + removing_vpc = route53resolver.disassociate_resolver_query_log_config( |
| 89 | + ResolverQueryLogConfigId=r53_remove, |
| 90 | + ResourceId=vpc |
| 91 | + ) |
| 92 | + logging.info(vpc + " removed from " + r53_remove) |
| 93 | + time.sleep(1) |
| 94 | + logging.info("60 second pause to ensure disassociation of Amazon VPCs...") |
| 95 | + time.sleep(60) |
| 96 | + logging.info("Removing Route 53 Query Logger: " + r53_remove) |
| 97 | + logging.info("DeleteResolverQueryLogConfig") |
| 98 | + r53_cleanup = route53resolver.delete_resolver_query_log_config( |
| 99 | + ResolverQueryLogConfigId=r53_remove |
| 100 | + ) |
| 101 | + logging.info(r53_remove + " has been removed.") |
| 102 | + time.sleep(2) |
| 103 | + else: |
| 104 | + logging.info("Removing Route 53 Query Logger: " + r53_remove) |
| 105 | + logging.info("DeleteResolverQueryLogConfig") |
| 106 | + r53_cleanup = route53resolver.delete_resolver_query_log_config( |
| 107 | + ResolverQueryLogConfigId=r53_remove |
| 108 | + ) |
| 109 | + logging.info(r53_remove + " has been removed.") |
| 110 | + time.sleep(2) |
| 111 | + except Exception as exception_handle: |
| 112 | + logging.error(exception_handle) |
| 113 | + |
| 114 | + |
| 115 | +def run_r53_cleanup(): |
| 116 | + """Function to run the r53_cleanup function""" |
| 117 | + r53_cleanup() |
| 118 | + logging.info("This is the end of the script. Please feel free to validate that logging resources have been cleaned up.") |
| 119 | + |
| 120 | + |
| 121 | +def lambda_handler(event, context): |
| 122 | + """Function that runs all of the previously defined functions""" |
| 123 | + r53_cleanup() |
| 124 | + logging.info("This is the end of the script. Please feel free to validate that logging resources have been cleaned up.") |
| 125 | + |
| 126 | + |
| 127 | +if __name__ == '__main__': |
| 128 | + event = "event" |
| 129 | + context = "context" |
| 130 | + lambda_handler(event, context) |
0 commit comments