Skip to content

Instantly share code, notes, and snippets.

@koleror
Last active June 19, 2020 15:05
Show Gist options
  • Save koleror/9117276cdca812ab879480e2455f9310 to your computer and use it in GitHub Desktop.
Save koleror/9117276cdca812ab879480e2455f9310 to your computer and use it in GitHub Desktop.
Cleanup lambda functions versions
import boto3
client = boto3.client('lambda')
def _clean_function(function_data, dry_run, max_versions):
skipped_items = 0
while True: # list_versions_by_function returns up to 50 versions per call
versions = client.list_versions_by_function(
FunctionName=function_data['FunctionArn']
)['Versions']
if len(versions) <= max_versions + skipped_items:
print(
f"{function_data['FunctionName']}: done. Leaving "
f"{max_versions + skipped_items} versions"
)
break
for version in versions[:-max_versions]:
if version['Version'] != function_data['Version']:
arn = version['FunctionArn']
if dry_run:
print(f'Would delete {arn})')
else:
print(f"Deleting {arn}...")
client.delete_function(FunctionName=arn)
else:
skipped_items += 1
if dry_run:
print(f"Would keep {version['FunctionArn']}")
if dry_run:
for version in versions[-max_versions:]:
print(f"Would keep {version['FunctionArn']}")
break # Would be an infinite loop in case of dry_run
def clean_function_old_versions(function_name, dry_run=True, max_versions=10):
_clean_function(
client.get_function(FunctionName=function_name)["Configuration"],
dry_run=dry_run,
max_versions=max_versions,
)
def clean_all_old_versions(dry_run=True, marker=None, max_versions=10):
if not marker:
functions = client.list_functions()
else:
functions = client.list_functions(Marker=marker)
for function_data in functions['Functions']:
_clean_function(function_data, dry_run, max_versions)
if 'NextMarker' in functions:
clean_all_old_versions(
dry_run=dry_run,
marker=functions['NextMarker'],
max_versions=max_versions,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment