|
| 1 | +import boto3 |
| 2 | +import sentry_sdk |
| 3 | + |
| 4 | + |
| 5 | +monitor_slug = "python-sdk-aws-lambda-tests-cleanup" |
| 6 | +monitor_config = { |
| 7 | + "schedule": { |
| 8 | + "type": "crontab", |
| 9 | + "value": "0 12 * * 0", # 12 o'clock on Sunday |
| 10 | + }, |
| 11 | + "timezone": "UTC", |
| 12 | + "checkin_margin": 2, |
| 13 | + "max_runtime": 20, |
| 14 | + "failure_issue_threshold": 1, |
| 15 | + "recovery_threshold": 1, |
| 16 | +} |
| 17 | + |
| 18 | + |
| 19 | +@sentry_sdk.crons.monitor(monitor_slug=monitor_slug) |
| 20 | +def delete_lambda_functions(prefix="test_"): |
| 21 | + """ |
| 22 | + Delete all AWS Lambda functions in the current account |
| 23 | + where the function name matches the prefix |
| 24 | + """ |
| 25 | + client = boto3.client("lambda", region_name="us-east-1") |
| 26 | + functions_deleted = 0 |
| 27 | + |
| 28 | + functions_paginator = client.get_paginator("list_functions") |
| 29 | + for functions_page in functions_paginator.paginate(): |
| 30 | + for func in functions_page["Functions"]: |
| 31 | + function_name = func["FunctionName"] |
| 32 | + if function_name.startswith(prefix): |
| 33 | + try: |
| 34 | + response = client.delete_function( |
| 35 | + FunctionName=func["FunctionArn"], |
| 36 | + ) |
| 37 | + functions_deleted += 1 |
| 38 | + except Exception as ex: |
| 39 | + print(f"Got exception: {ex}") |
| 40 | + |
| 41 | + return functions_deleted |
| 42 | + |
| 43 | + |
| 44 | +def lambda_handler(event, context): |
| 45 | + functions_deleted = delete_lambda_functions() |
| 46 | + |
| 47 | + sentry_sdk.metrics.gauge( |
| 48 | + key="num_aws_functions_deleted", |
| 49 | + value=functions_deleted, |
| 50 | + ) |
| 51 | + |
| 52 | + return { |
| 53 | + 'statusCode': 200, |
| 54 | + 'body': f"{functions_deleted} AWS Lambda functions deleted successfully." |
| 55 | + } |
0 commit comments