Skip to content

Instantly share code, notes, and snippets.

@tobywf
Last active April 11, 2024 06:52
Show Gist options
  • Save tobywf/6eb494f4b46cef367540074512161334 to your computer and use it in GitHub Desktop.
Save tobywf/6eb494f4b46cef367540074512161334 to your computer and use it in GitHub Desktop.
A quick script to remove old AWS Lambda function versions
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()
@sw-iot-yashdholakia
Copy link

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