I’m looking to add a lifecycle rule to delete all objects inside an S3 bucket after a certain number of days. I get the following error when I execute my code. Could this be due to the target prefix being null??
Error:
com.amazonaws.services.s3.model.AmazonS3Exception: The XML you provided was not well-formed or did not validate against our published schema (Service: Amazon S3; Status Code: 400; Error Code: MalformedXML; Request ID: 4FR7C3BE85YVEW57; S3 Extended Request ID: fcYaw7u//7o843GjDtGGIQRjYxAMbn7f1iepEIas/Yt5bybM9BjDZ0JbG+SVz/vvE1k/KjaKadQ=; Proxy: null), S3 Extended Request ID: fcYaw7u//7o843GjDtGGIQRjYxAMbn7f1iepEIas/Yt5bybM9BjDZ0JbG+SVz/vvE1k/KjaKadQ=
Code used for creating and setting lifecycle rule to bucket configuration:
BucketLifecycleConfiguration.Rule rule = new BucketLifecycleConfiguration.Rule()
.withId("Delete objects in " + expirationInDays + " days")
.withFilter(new LifecycleFilter(new LifecyclePrefixPredicate("")))
.withExpirationInDays(expirationInDays)
.withExpiredObjectDeleteMarker(true)
.withStatus(BucketLifecycleConfiguration.ENABLED);
configuration = new BucketLifecycleConfiguration()
.withRules(Collections.singletonList(rule));
s3Client.setBucketLifecycleConfiguration(bucketName, configuration);
2
Answers
I’d recommend offloading the management of file expiry to AWS, you can use the built-in feature of S3 called AWS S3 lifecycle policies. You can use this lifecycle policies to:
You can implement this using any IAC tools but for the sake of sharing an example, here is the Terraform version of it:
By using the built-in expiry policies of S3, you get the following advantages:
I was able to get this to work with the current Java SDK v2, as follows. The code basically creates a default, empty filter rule instead of a prefix filter on "". I’d assume that you can do the same with SDK v1 (though ideally you would no longer be using SDK v1, because it’s 5 years old).
I came to this conclusion because, after manually configuring a similar lifecycle in the AWS Console, the awscli description of that lifecycle configuration looked like this: