Tien Dung Tran
Tien Dung Tran

Reputation: 1209

AWS S3 versioning - Choose which version S3 to restore

Currently, I'm using S3 versioning and I sync data to S3 bucket daily. My question is how can I restore a versioned bucket in to a particular point in time? For example: I sync data to S3 from Monday to Saturday, and in Saturday I want to restore whole folder from Tuesday, so how can I do in cli? Thanks.

Upvotes: 2

Views: 1860

Answers (1)

firescar96
firescar96

Reputation: 449

We used this in production to cleanup some files after s3-pit-restore and AWS support failed. This python script permanently deletes all versions of files after a given time.

import os
from datetime import datetime
import boto3

bad_day = datetime.now()

s3 = boto3.resource(
    's3',
    aws_access_key_id=os.environ['AWS_ID'],
    aws_secret_access_key=os.environ['AWS_SECRET'])

key = ''
metadata = s3.meta.client.list_object_versions(Bucket=os.environ['AWS_BUCKET'], Prefix=key)

to_delete = []
for version in metadata['Versions']:
    if version['Size'] > 0:
        continue

    if version['LastModified'] > bad_day:
        to_delete.append({'Key': version['Key'], 'VersionId': version['VersionId']})

bucket = s3.Bucket(os.environ['AWS_BUCKET'])
# bucket.delete_objects(Delete={'Objects': to_delete})

Don't uncomment the last line until you are ready to delete.

Upvotes: 1

Related Questions