How to remove older versions of Lambda

Alien
2 min readApr 17, 2020

--

Use case:

Lambda has soft storage limit which mostly you hit when you numerous lambdas and numerous lambda versions.

Currently, there is no way to configure at Lambda level for retaining the number of versions and delete the older versions.

A workaround to this will be create a AWS Rules Trigger which will run either once a day or after every deployment which will trigger a Lambda to delete the older versions.

AWS Rules -> Lambda

Step 1: Create Lambda

You will need to create a Lambda with run time of Python and Role which has AWSLambdaFullAccess access policy attached.

Copy paste the following code in Lambda:

import json
import boto3
from collections import Counter
def lambda_handler(event, context):
client = boto3.client('lambda')
response = client.list_functions(FunctionVersion='ALL')
d = dict(Counter([x['FunctionName'] for x in response['Functions']]))
print(json.dumps(d, indent=2))
for key, value in d.items():
if value > 5:
print(key, '->', value)
a = {}
for x in response['Functions']:
if x['FunctionName'] == key and x['Version'] != '$LATEST':
#print(x['FunctionArn'],x['LastModified'])
a[x['FunctionArn']] = x['LastModified']
listofTuples = sorted(a.items() , key=lambda x: x[1])
print(a)
print(json.dumps(listofTuples))
if len(listofTuples) > 5:
for elem in listofTuples[0:len(listofTuples)-5]:
response = client.delete_function(FunctionName=elem[0])
print("FunctionArn",elem[0],"Deleted response",response,sep = "->")

If you have large number of lambdas then using paginator will help. You can use following code for reference

import json
import boto3
from collections import Counter


def lambda_handler(event, context):
client = boto3.client("lambda")
paginator = client.get_paginator("list_functions")
response_iterator = paginator.paginate(
FunctionVersion="ALL",
PaginationConfig={
"MaxItems": 123,
"PageSize": 123,
},
)
print(response_iterator)
for page in response_iterator:
d = dict(Counter([x["FunctionName"] for x in page["Functions"]]))
print(json.dumps(d, indent=2))
for key, value in d.items():
if value > 5:
print(key, "->", value)
a = {}
for x in response["Functions"]:
if x["FunctionName"] == key and x["Version"] != "$LATEST":
# print(x['FunctionArn'],x['LastModified'])
a[x["FunctionArn"]] = x["LastModified"]
listofTuples = sorted(a.items(), key=lambda x: x[1])
print(a)
print(json.dumps(listofTuples))
if len(listofTuples) > 5:
for elem in listofTuples[0 : len(listofTuples) - 5]:
response = client.delete_function(FunctionName=elem[0])
print(
"FunctionArn",
elem[0],
"Deleted response",
response,
sep="->",
)

The code logic is find Lambda function which have more than 5 versions and delete the oldest versions in that Lambda version. You may change the code as per your requirement.

Step 2: Create Rule

Create a rule which will run at a fixed rate of 1 day and target as above the Lambda function. You can also use cron expression for scheduling the rule.

This will take care of deletion your storage problem and save money.

--

--