1. Answers
  2. How to auto-delete files in S3 after 30 days?

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:

  1. Create an S3 bucket: This is where your objects will be stored.
  2. Define a lifecycle policy: This policy will specify that objects should be deleted 30 days after they are created.
  3. 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:

  1. Importing Modules: We import the necessary modules from Pulumi and the AWS provider.
  2. Creating an S3 Bucket: We create a new S3 bucket using aws.s3.Bucket.
  3. 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 empty prefix means the rule applies to all objects in the bucket.
  4. Applying the Lifecycle Policy: The lifecycle policy is associated with the S3 bucket by specifying the bucket name.
  5. 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 up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up