In this blog post, we are going to show how you can delete old versions in an S3 bucket using a Lifecycle Rule. This would come especially handy if you have enabled Versioning on an S3 bucket and you need to delete a large amount of old files that you do not need any more.
When you add a Lifecycle configuration to a bucket, the configuration rules apply to both existing objects and objects that you add later. For example, if you add a Lifecycle configuration rule today with an expiration action that causes objects with a specific prefix to expire 30 days after creation, Amazon S3 will queue for removal any existing objects that are more than 30 days old.
How to add a Lifecycle Rule to Delete Old Versions
The first step is to go to the S3 Bucket AWS Console and click on your bucket.
Next, we will create a new Lifecycle rule by clicking on “Create lifecycle rule”.
You need to give a name to your rule and choose the scope on which this rule will be applied.
Under “Lifecycle rule actions” we need to specify the action “Permanently delete noncurrent versions of objects”.
This action will allow us to delete all non-current versions of the files present in the S3 bucket.
You can specify when an object is considered to be non-current. The minimum value is 1. So you will basically have 24 hours before a version is considered non-current.
Once you are satisfied with your configurations, click on Create Rule.
When is a Lifecycle Rule Applied on S3 Bucket Objects
A question that many people ask is: When is a lifecycle rule executed/applied on an S3 bucket.
And the answer to this question is:
Lifecycle rules run once a day at midnight Universal Coordinated Time (UTC).
In this short tutorial, we showed you how to save money and time by deleting non-current versions of your files.
Note that this will not delete any current versions, only non-current versions.
If you would like to learn more about other AWS services, you can check this link.