Skip to content

Commit 9ca4708

Browse files
committed
Update script to delete in batch.
1 parent 72857ef commit 9ca4708

File tree

1 file changed

+33
-5
lines changed
  • .github/workflows/util/clean/lambda_layer_cleanup

1 file changed

+33
-5
lines changed

.github/workflows/util/clean/lambda_layer_cleanup/cleaner.py

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,35 @@
44

55
client = boto3.client('apigateway')
66

7-
def delete_old_api_gateways(hours_old=3):
7+
def delete_api_with_retries(client, api_id, retries=5):
8+
"""Deletes an API with retries and exponential backoff."""
9+
delay = 10
10+
for attempt in range(retries):
11+
try:
12+
client.delete_rest_api(restApiId=api_id)
13+
print(f"API {api_id} deleted successfully.")
14+
return
15+
except ClientError as e:
16+
if e.response['Error']['Code'] == 'TooManyRequestsException':
17+
print(f"Rate limit exceeded. Retrying in {delay} seconds (Attempt {attempt + 1}/{retries})...")
18+
time.sleep(delay)
19+
delay *= 2 # Exponential backoff
20+
else:
21+
print(f"Error deleting API {api_id}: {e}")
22+
raise # Re-raise other exceptions
23+
print(f"Failed to delete API {api_id} after {retries} attempts.")
24+
25+
def delete_old_api_gateways(hours_old=3, batch_size=5):
26+
"""Deletes API Gateways older than the specified hours in batches."""
827
now = datetime.now(timezone.utc) # Ensure `now` is timezone-aware
928
cutoff_time = now - timedelta(hours=hours_old)
1029

1130
print(f"Cutoff time: {cutoff_time}")
1231

32+
# Fetch all APIs
1333
apis = client.get_rest_apis()
34+
batch_counter = 0
35+
1436
for api in apis.get('items', []):
1537
created_date = api.get('createdDate') # This is usually UTC already
1638
if created_date and isinstance(created_date, datetime):
@@ -20,11 +42,17 @@ def delete_old_api_gateways(hours_old=3):
2042
if created_date < cutoff_time:
2143
api_id = api['id']
2244
api_name = api.get('name', 'Unnamed API')
23-
print(f"Deleting API: {api_name} (ID: {api_id}), created at {created_date}")
45+
print(f"Preparing to delete API: {api_name} (ID: {api_id}), created at {created_date}")
46+
47+
# Attempt to delete the API with retries
48+
delete_api_with_retries(client, api_id)
49+
50+
batch_counter += 1
2451

25-
client.delete_rest_api(restApiId=api_id)
26-
print("Deleted successfully. Sleeping for 32 seconds...")
27-
time.sleep(60)
52+
# Pause after every batch
53+
if batch_counter % batch_size == 0:
54+
print("Pausing for 2 minutes to avoid rate-limiting...")
55+
time.sleep(120)
2856
else:
2957
print("Invalid or missing createdDate for API:", api)
3058

0 commit comments

Comments
 (0)