Skip to content

Instantly share code, notes, and snippets.

@crazycodr
Last active September 16, 2022 16:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save crazycodr/ef1b6b65cf03350fafbde9d1b56bd637 to your computer and use it in GitHub Desktop.
Save crazycodr/ef1b6b65cf03350fafbde9d1b56bd637 to your computer and use it in GitHub Desktop.
Batch restore deleted s3 objects by accident
# Set the bucket name and date limit that you want to scan for...
#
# For example, if you deleted everything at 9'ish, set the DATE_LIMIT for a
# few minutes before to ensure you find only the stuff you deleted by error
#
BUCKET_NAME="..."
DATE_LIMIT="0000-00-00T00:00:00.000Z"
aws s3api list-object-versions --bucket "${BUCKET_NAME}" > objects.json
cat objects.json | jq --arg DATE_LIMIT "${DATE_LIMIT}" '[ .DeleteMarkers[] | select(.LastModified > $DATE_LIMIT and .IsLatest) | { file: .Key, version: .VersionId } ]' > markers-to-delete.json
cat markers-to-delete.json | jq --arg BUCKET_NAME "${BUCKET_NAME}" '.[] | "aws s3api delete-object --bucket " + $BUCKET_NAME + " --key " + .file + " --version-id " + .version' -r > undelete.sh
bash undelete.sh
@crazycodr
Copy link
Author

This is a very basic script to undelete s3 objects. If your application writes and deletes a lot of files live into the bucket, this is definitely NOT the right approach because you'd need to also include who did the operation. Only use this on a manually managed bucket or something with a very low volume of file!

@amit4422
Copy link

amit4422 commented Feb 2, 2021

Hey, where exactly are you restoring the files in the command above.
The command which you have mentioned above seems to delete the deleted version completely.

@amit4422
Copy link

amit4422 commented Feb 2, 2021

I would rather recommend to have a look at the following repository.
The command works like a charm
https://github.com/angeloc/s3-pit-restore

@crummy
Copy link

crummy commented Mar 28, 2021

Hey, where exactly are you restoring the files in the command above.
The command which you have mentioned above seems to delete the deleted version completely.

The code above deletes the delete marker - effectively restoring the file.

@RLanderson5
Copy link

How to execute this?

@crazycodr
Copy link
Author

crazycodr commented Sep 16, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment