Skip to content

Instantly share code, notes, and snippets.

@SaundersB
Created February 26, 2023 15:31
Show Gist options
  • Save SaundersB/1faf615b7d01e728180ec0c808852c81 to your computer and use it in GitHub Desktop.
Save SaundersB/1faf615b7d01e728180ec0c808852c81 to your computer and use it in GitHub Desktop.
Delete AWS EC2 Snapshots Older Than Six Months Lambda
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-west-2' });
exports.handler = async (event, context, callback) => {
const sixMonthsAgo = new Date(Date.now() - 6 * 30 * 24 * 60 * 60 * 1000);
const conditionDate = sixMonthsAgo.toISOString();
const ownerIds = ["REPLACE_ME"];
let nextToken;
do {
const params = {
OwnerIds: ownerIds,
Filters: [
{
Name: 'start-time',
Values: [conditionDate],
},
],
MaxResults: 10,
NextToken: nextToken,
};
const ec2 = new AWS.EC2({ apiVersion: '2016-11-15' });
const result = await ec2.describeSnapshots(params).promise();
const snapshots = result.Snapshots;
console.log(`Found ${snapshots.length} snapshots older than ${conditionDate}`);
if (snapshots.length === 0) {
break;
}
nextToken = result.NextToken;
for (const snapshot of snapshots) {
try {
await ec2.deleteSnapshot({ SnapshotId: snapshot.SnapshotId }).promise();
console.log(`Deleted snapshot ${snapshot.SnapshotId}`);
} catch (error) {
console.log(`Error deleting snapshot ${snapshot.SnapshotId}:`, error);
}
}
} while (nextToken);
callback(null, "Success");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment