This code works with or without prefixes but if u use it without prefix I am not pretty sure it will deep dig enough for the 15 minutes timeout. I created a AWS lambda function using Node.js 14 (put the timeout up to 15minutes) and I ran it manually (it can be automated) but I had like 10 folders in one of the applications bucket that had been deleted and since I had versioning turned on there were versions with Delete Marker. So I had to loop through all the pages and find the ones with delete marker and restore them with their last version so they can be used again. The biggest issue was that while thinking through this was that I used recursion but I get the same 1000 objects since this is how AWS list objects function works and in order to get the next 1000 there is a property called NextKeyMarker that did the job for my case. And the flag that indicates if there are more pages is : IsTruncated - if it is true means that there are more pages - so invoke that function again with the nextKeyMarker to know where to start from (recursion).
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
async function restoreDeletedObjects(bucketName, prefix, nextMarker) {
try {
const params = {
Bucket: bucketName,
Prefix: prefix,
KeyMarker: nextMarker,
};
const response = await s3.listObjectVersions(params).promise();
console.log(response, 'response');
if (response.DeleteMarkers.length > 0) {
console.log('in the first if', response.DeleteMarkers.length);
const objectsToDelete = response.DeleteMarkers.map(deleteMarker => ({
Key: deleteMarker.Key,
VersionId: deleteMarker.VersionId,
}));
console.log(objectsToDelete, 'objects to delete');
// Remove the delete markers and restore the objects
await s3.deleteObjects({
Bucket: bucketName,
Delete: { Objects: objectsToDelete, Quiet: false },
}).promise();
for (const deleteMarker of response.DeleteMarkers) {
console.log(deleteMarker, 'delete Marker');
if (deleteMarker.IsLatest) {
console.log(`Restored: s3://${bucketName}/${deleteMarker.Key}, VersionId: ${deleteMarker.VersionId}`);
}
}
}
if (response.IsTruncated) {
// If there are more delete markers, call the function recursively with the NextKeyMarker
await restoreDeletedObjects(bucketName, prefix, response.NextKeyMarker);
} else {
console.log('Everything with Delete Marker was restored sucessfully')
}
} catch (err) {
console.error("Error:", err);
}
}
exports.handler = async (event, context) => {
const bucketName = "bucket-name-here"; // Replace with your bucket name
const prefix = "put-your-prefix-here"; // Replace with your desired prefix
// we had structure like this - Buckets -> "data" -> and 10 folders here. so we used like it that for each folder that had more than 15000 objects ->
// const bucketName = "orders"
// const prefix = "data/folder1" then "data/folder2" and we ran that for each folder.
await restoreDeletedObjects(bucketName, prefix, undefined);
};```