Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script for cleaning out old AWS Lambda function versions
#! /usr/bin/env python3
import json
import boto3
import argparse
import time
lambda_client = boto3.client('lambda')
function_choices = [f['FunctionName'] for f in lambda_client.list_functions()['Functions']]
parser = argparse.ArgumentParser(description="Delete a percentage of old lambda function versions")
parser.add_argument('function_name', choices=function_choices, help="Name of lambda function in AWS")
parser.add_argument('--percent', type=float, default=50, help="What percentage of old function versions to delete. Defaults to 50")
args = parser.parse_args()
percent_to_delete = args.percent/100
def get_versions(versions=None, next_marker=None):
versions = versions or []
kwargs = {'FunctionName': args.function_name,
'MaxItems': 50} # 50 is the max allowed?
if next_marker:
kwargs['Marker'] = next_marker
result = lambda_client.list_versions_by_function(**kwargs)
versions += result['Versions']
next_marker = result.get('NextMarker')
if next_marker:
versions = get_versions(versions, next_marker)
return versions
print("Fetching all function versions")
versions = get_versions()
versions = sorted(versions, key=lambda ver: ver['LastModified'])
print("Ignoring the latest version")
for i, version in enumerate(versions):
if version['Version'] == '$LATEST':
versions.pop(i)
json.dump(versions, open('lambda_versions.json', 'w'), indent=2)
code_size = 0
for version in versions:
code_size += version['CodeSize']
total_mb = '{:,.0f}'.format(code_size * 0.000001)
print(f"There are {len(versions)} versions of function '{args.function_name}', totalling {total_mb} MB")
num_to_delete = int(len(versions) * percent_to_delete)
if num_to_delete < 10:
# Keep 10 at the least
num_to_delete = 0
print(f"About to delete {num_to_delete} out of {len(versions)} oldest versions ")
time.sleep(10)
for i, version in enumerate(versions[:num_to_delete]):
print(f"Deleting {i} of {num_to_delete}: {version['LastModified']}")
lambda_client.delete_function(
FunctionName=args.function_name,
Qualifier=version['Version'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment