Skip to content

Instantly share code, notes, and snippets.

@jeff-hager-dev
Created November 11, 2021 16:39
Show Gist options
  • Select an option

  • Save jeff-hager-dev/a2195671f137dc06be068ab440c15d58 to your computer and use it in GitHub Desktop.

Select an option

Save jeff-hager-dev/a2195671f137dc06be068ab440c15d58 to your computer and use it in GitHub Desktop.
Deletes old lambda versions which is useful if the 75gb limit is hit in region
/**
* @fileOverview
*
* Deletes old lambda versions which is useful if the 75gb limit is hit in region
*
*
* Example of running script:
* NODE_ENV=prod AWS_PROFILE=user-profile AWS_REGION=us-west-2 node ./delete-old-lambda-versions.js
*/
const AWS = require("aws-sdk");
const lambda = new AWS.Lambda();
(async function () {
const lambdaDetails = {
"functionName": "<LAMBDA-ARN-HERE>",
"maxItems": 25
}
// NOTE: Versions that should not be deleted
const versionsToKeep = [
"$LATEST",
"145"
];
for await (const lambdaVersions of _getBatchOfLambdaVersions(lambdaDetails)) {
await _deleteLambdaVersions({
lambdaVersions,
versionsToKeep
});
}
console.log("##> FINISHED");
})();
/**
* Gets a batch of lambda versions for a function. The size of the batch is determined by "maxItems"
*
* @param {String} params.functionName
* @param {Number} params.maxItems
* @return {AsyncGenerator<Lambda.FunctionConfiguration[], void, *>}
*/
async function* _getBatchOfLambdaVersions(params) {
const {
functionName,
maxItems
} = params;
let nextMarker = null;
while (true) {
try {
const params = {
FunctionName: functionName,
MaxItems: maxItems
};
if (nextMarker) {
params.Marker = nextMarker;
}
const lambdaGroup = await lambda.listVersionsByFunction(params).promise();
nextMarker = lambdaGroup.NextMarker;
yield lambdaGroup.Versions;
if(!Boolean(nextMarker)){
return;
}
} catch (error) {
console.error(error.message);
return;
}
}
}
/**
* Deletes a group of lambda Versions
*
* @param {Array} params.lambdaVersions
* @param {Array} params.versionsToKeep
* @return {Promise<{[p: string]: PromiseSettledResult<*>}>}
* @private
*/
async function _deleteLambdaVersions(params){
const {lambdaVersions, versionsToKeep} = params;
const deletePromises = lambdaVersions.map(async lambdaVersion => {
if (versionsToKeep.indexOf(lambdaVersion.Version) > -1) {
console.log("##> NOT DELETING VERSION: ", lambdaVersion.Version);
return;
}
await lambda.deleteFunction({"FunctionName": lambdaVersion.FunctionArn}).promise();
console.log("##> DELETED VERSION: ", lambdaVersion.Version);
});
return await Promise.allSettled(deletePromises);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment