in aws_sra_examples/solutions/guardduty/guardduty_org/lambda/src/app.py [0:0]
def delete(event, context):
"""
CloudFormation Delete Event.
:param event: event data
:param context: runtime information
:return: CloudFormation response
"""
logger.info("Delete Event")
try:
check_parameters(event)
params = event.get("ResourceProperties")
available_regions = get_available_service_regions(params.get("ENABLED_REGIONS", ""), "guardduty")
session = assume_role(
params.get("DELEGATED_ADMIN_ACCOUNT_ID", ""),
params.get("AWS_PARTITION", "aws"),
params.get("CONFIGURATION_ROLE_NAME", ""),
"DeleteGuardDuty")
# Loop through the regions and disable GuardDuty in the delegated admin account
for region in available_regions:
try:
regional_guardduty = get_service_client("guardduty", region)
disable_organization_admin_account(regional_guardduty, region)
# Delete Detectors in the Delegated Admin Account
session_guardduty = get_service_client("guardduty", region, session)
delete_detectors(session_guardduty, region, True)
except Exception as exc:
logger.error(f"GuardDuty Exception: {exc}")
raise ValueError(f"GuardDuty API Exception: {exc}")
deregister_delegated_administrator(params.get("DELEGATED_ADMIN_ACCOUNT_ID", ""), SERVICE_NAME)
accounts, account_ids = get_all_organization_accounts(params.get("DELEGATED_ADMIN_ACCOUNT_ID", ""))
# Cleanup member account GuardDuty detectors
start = now()
processes = []
with ThreadPoolExecutor(max_workers=MAX_THREADS) as executor:
for account_id in account_ids:
try:
processes.append(executor.submit(
cleanup_member_account,
account_id,
params.get("AWS_PARTITION", "aws"),
params.get("DELETE_DETECTOR_ROLE_NAME", ""),
available_regions
))
except Exception as error:
logger.error(f"{error}")
continue
for task in as_completed(processes):
logger.info(f"process task - {task.result()}")
logger.info(f"Time taken to delete member account detectors: {now() - start}")
except Exception as exc:
logger.error(f"Unexpected error {exc}")
raise ValueError("Unexpected error. Review logs for details.")