Skip to content

Instantly share code, notes, and snippets.

@jpdom
Created March 26, 2024 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpdom/cc693afbc9312f8946b877308bf437a9 to your computer and use it in GitHub Desktop.
Save jpdom/cc693afbc9312f8946b877308bf437a9 to your computer and use it in GitHub Desktop.
[AWS] Delete all ApiGateway APIs in all regions
import subprocess
import json
# List all enabled regions
nextPageToken = None
regions = []
while nextPageToken != '':
if nextPageToken is None:
regions_raw = subprocess.check_output(['aws', 'account', 'list-regions'])
else:
regions_raw = subprocess.check_output(['aws', 'account', 'list-regions', '--starting-token', nextPageToken])
regions_raw = json.loads(regions_raw)
regions += [region['RegionName'] for region in regions_raw['Regions'] if region['RegionOptStatus'] != 'DISABLED']
nextPageToken = regions_raw.get('NextToken', '')
print("Total regions:", len(regions))
# Retrieve all APIs
all_apis = []
for region in regions:
apis_in_region = 0
print("Region:", region)
nextPageToken = None
while nextPageToken != '':
if nextPageToken is None:
output = subprocess.check_output(['aws', 'apigateway', 'get-rest-apis', '--region', region])
else:
output = subprocess.check_output(['aws', 'apigateway', 'get-rest-apis', '--region', region, '--starting-token', nextPageToken])
data = json.loads(output)
# Add region to the data
for item in data['items']:
item['region'] = region
apis_in_region += len(data['items'])
all_apis.extend(data['items'])
nextPageToken = data.get('nextToken', '')
print("Total APIs in region:", apis_in_region)
print("Total APIs:", len(all_apis))
while len(all_apis) > 0:
for region in regions:
# Get the first API from this region
api = next((api for api in all_apis if api['region'] == region), None)
if api is None:
continue
print(api['id'])
#Use delete-rest-api to delete the API, on error continue to next one
try:
subprocess.check_output(['aws', 'apigateway', 'delete-rest-api', '--rest-api-id', api['id'], '--region', api['region']])
print(f"Api {api['id']} deleted in region {api['region']}")
api['deleted'] = True
except subprocess.CalledProcessError as e:
print('Error deleting API:', api['id'], e)
continue
# Remove deleted APIs
all_apis = [api for api in all_apis if 'deleted' not in api]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment