How do I auto-delete files in S3 after 30 days?
To automatically delete files in an S3 bucket after 30 days, you can use S3 bucket lifecycle policies. These policies allow you to define rules that apply to objects in your bucket to manage their lifecycle. In this case, we’ll create a rule that will delete objects 30 days after they are created.
We’ll use the aws.s3.BucketLifecycleConfigurationV2
resource from the Pulumi AWS package to configure this lifecycle rule.
Here is how you can do it:
- Create an S3 bucket: This is where your objects will be stored.
- Define a lifecycle policy: This policy will specify that objects should be deleted 30 days after they are created.
- Apply the lifecycle policy to the S3 bucket: This will enforce the rule on the bucket.
Below is a detailed Pulumi program written in TypeScript that accomplishes this:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an S3 bucket
const bucket = new aws.s3.Bucket("my-bucket");
// Define a lifecycle policy to delete objects after 30 days
const lifecyclePolicy = new aws.s3.BucketLifecycleConfigurationV2("bucketLifecycle", {
bucket: bucket.bucket,
rules: [{
id: "delete-after-30-days",
status: "Enabled",
expiration: {
days: 30, // Delete objects after 30 days
},
filter: {
prefix: "", // Apply to all objects in the bucket
},
}],
});
// Export the bucket name
export const bucketName = bucket.bucket;
Explanation:
- Importing Modules: We import the necessary modules from Pulumi and the AWS provider.
- Creating an S3 Bucket: We create a new S3 bucket using
aws.s3.Bucket
. - Defining the Lifecycle Policy:
- We create a lifecycle policy using
aws.s3.BucketLifecycleConfigurationV2
. - The
rules
property is an array where each object defines a lifecycle rule. - We set the
id
of the rule for identification purposes. - The
status
is set to “Enabled” to activate the rule. - The
expiration
property specifies that objects should be deleted after 30 days. - The
filter
property with an emptyprefix
means the rule applies to all objects in the bucket.
- We create a lifecycle policy using
- Applying the Lifecycle Policy: The lifecycle policy is associated with the S3 bucket by specifying the bucket name.
- Exporting the Bucket Name: Finally, we export the bucket name so that it can be easily referenced.
This Pulumi program will create an S3 bucket and configure it to automatically delete objects that are older than 30 days. You can run this program using the Pulumi CLI to set up your infrastructure.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.