Last active
July 17, 2024 16:15
-
-
Save michalc/defe066c8b352a263f24c166b70921e9 to your computer and use it in GitHub Desktop.
Restore all objects under S3 prefix in versioned bucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Restores all objects under a prefix in an S3 bucket to the version they were before being deleted. | |
# Works by deleting the latest delete marker for the objects. | |
import boto3 | |
bucket = 'the-bucket' | |
prefix = 'the-prefix/' | |
region = 'eu-west-2' | |
client = boto3.client('s3', region_name=region) | |
paginator = client.get_paginator('list_object_versions') | |
page_iterator = paginator.paginate( | |
Bucket=bucket, | |
Prefix=prefix, | |
) | |
latest_delete_markers = ( | |
dm | |
for page in page_iterator | |
for dm in page['DeleteMarkers'] | |
if dm['IsLatest'] | |
) | |
for dm in latest_delete_markers: | |
client.delete_object( | |
Bucket=bucket, | |
Key=dm['Key'], | |
VersionId=dm['VersionId'], | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment