Tip
Serverless Land offers a Lambda function cleanup step-function pattern, which can also help you to manage steady accumulation of lambda versions.
This script fills a similar niche. It will review a CloudFormation stack and remove all but the most recent N versions of all versioned lambda functions it finds there.
If you have enabled Lambda versioning for your AWS deployment (perhaps because you want to be able to use Lambda SnapStart to reduce some inconveniently long cold-start times for certain runtimes, or maybe because you want to control version updates), you may be surprised to discover that all your lambda versions are preserved ad-inifinitum, and that there's no automated mechanism to delete older versions, or to set an expiry time for them.
Caching: For every function version that you publish with SnapStart enabled, you pay for the cost of caching and maintaining the snapshot.
This is especially problematic if you are using SnapStart because you may be charged for every snapshot held by SnapStart for every version of every lambda you have published. (NB. Java does not incur an additional cost.) These are also held ad-inifinitum (and do not fall under free usage levels!)
remove-old-lambda-versions.sh --stack <stack-name> [--region <region>] [--keep <keep>] [--delete]
<stack-name>the name of your stack (required)<region>the AWS region to use (defaults toeu-west-2)<keep>the number of most recent versions of the lambda to keep
The script will perform a dry run (ie. it won't delete anything) unless you also provide the -y/--delete parameter.