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()
@JanAbb
Copy link

JanAbb commented Jan 17, 2024

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:

import { LambdaClient, ListVersionsByFunctionCommand, DeleteFunctionCommand, FunctionConfiguration, ListFunctionsCommand } from '@aws-sdk/client-lambda';

const lambda = new LambdaClient({
    region: 'eu-central-1'
});

const fetchAllVersions = async (functionName: string) => {
    let marker: string | undefined;
    let versions: FunctionConfiguration[] = [];
    do {
        const listCommand = new ListVersionsByFunctionCommand({
            FunctionName: functionName,
            Marker: marker
        });
        const partOfVersions = await lambda.send(listCommand);
        versions = versions.concat(partOfVersions.Versions ?? []);
        marker = partOfVersions.NextMarker;
    } while(marker);
    

    return versions;
};

const deleteOldVersionsOfLambda = async (functionName: string) => {
    const versions = await fetchAllVersions(functionName);
    const deletionList: string[] = versions?.filter(v => v.Version !== '$LATEST').map(v => v.FunctionArn) as string[];


    for (const arn of deletionList) {
        const deletionCommand = new DeleteFunctionCommand({
            FunctionName: arn
        });

        await lambda.send(deletionCommand);
    }

    return null;
};

const getAllFunctionsAvailable = async () => {
    const listFunctionsCommand = new ListFunctionsCommand({});

    const functions = await lambda.send(listFunctionsCommand);

    return functions.Functions?.map(f => f.FunctionName).filter(f => f != null);
};

const deleteAllOldVersions = async () => {
    const allFunctionsNames = await getAllFunctionsAvailable();
    
    for (const functionName of allFunctionsNames!) {
        await deleteOldVersionsOfLambda(functionName!);
    }
};

deleteAllOldVersions();

@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