Created
March 29, 2022 18:18
-
-
Save Michaelliv/6bf720e03bdfcabb03e15d3d6f1dee06 to your computer and use it in GitHub Desktop.
Deletes entire bucket content based on bucket names, object prefix and minimal date
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
| from datetime import datetime | |
| from typing import Optional | |
| import boto3 | |
| import pytz | |
| def clear_bucket_by_min_date( | |
| bucket: str, | |
| prefix: Optional[str] = None, | |
| min_date: datetime = datetime.now(pytz.UTC), | |
| aws_profile_name: Optional[str] = None, | |
| ): | |
| if aws_profile_name is not None: | |
| s3 = boto3.Session(profile_name=aws_profile_name).resource("s3") | |
| else: | |
| s3 = boto3.resource("s3") | |
| for file in s3.Bucket(bucket).objects.filter(prefix): | |
| if file.last_modified < min_date: | |
| s3.Object(bucket, file.key).delete() | |
| if __name__ == "__main__": | |
| clear_buket_by_min_date( | |
| bucket="example", | |
| prefix="some/prefix", | |
| min_date=datetime(year=2021, month=11, day=26, tzinfo=pytz.UTC), | |
| aws_profile_name="prd", | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment