Last active
September 9, 2024 17:50
-
-
Save tobywf/6eb494f4b46cef367540074512161334 to your computer and use it in GitHub Desktop.
A quick script to remove old AWS Lambda function versions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import, print_function, unicode_literals | |
import boto3 | |
def clean_old_lambda_versions(): | |
client = boto3.client('lambda') | |
functions = client.list_functions()['Functions'] | |
for function in functions: | |
versions = client.list_versions_by_function(FunctionName=function['FunctionArn'])['Versions'] | |
for version in versions: | |
if version['Version'] != function['Version']: | |
arn = version['FunctionArn'] | |
print('delete_function(FunctionName={})'.format(arn)) | |
#client.delete_function(FunctionName=arn) # uncomment me once you've checked | |
if __name__ == '__main__': | |
clean_old_lambda_versions() |
More revisions. We don't use aliases, so this keeps the most recent two by version number.
import boto3 def clean_old_lambda_versions(client): functions = client.list_functions()['Functions'] for function in functions: arn = function['FunctionArn'] print(arn) all_versions = [] versions = client.list_versions_by_function( FunctionName=arn) # Page through all the versions while True: page_versions = [int(v['Version']) for v in versions['Versions'] if not v['Version'] == '$LATEST'] all_versions.extend(page_versions) try: marker = versions['NextMarker'] except: break versions = client.list_versions_by_function( FunctionName=arn, Marker=marker) # Sort and keep the last 2 all_versions.sort() print('Which versions must go?') print(all_versions[0:-2]) print('Which versions will live') print(all_versions[-2::]) for chopBlock in all_versions[0:-2]: functionArn = '{}:{}'.format(arn, chopBlock) print('When uncommented, will run: delete_function(FunctionName={})'.format(functionArn)) # I want to leave this commented in Git for safety so we don't run it unscrupulously # client.delete_function(FunctionName=functionArn) # uncomment me once you've checked if __name__ == '__main__': client = boto3.client('lambda', region_name='us-east-1') clean_old_lambda_versions(client)
This Helped for my 88 lambda cleanup, thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had the use case for this due to the deprecation of node versions < 18. I wrote a script to delete all old versions that were not the newest to make the AWS Trusted Advisor happy again. This is my code for people in need to delete for all lambdas all old versions but the newest: