Ankur
Ankur

Reputation: 71

terraform code to delete objects in the bucket after 10 days

I have to delete objects in the bucket after 10 days. It means all the objects that bucket has more than 10 days older need to be deleted using terraform.

Wherever I found a code to delete it, it having prefix. What needs to be done if I have to apply to all the objects in buckets instead of prefix.

Upvotes: 7

Views: 14193

Answers (2)

ofirule
ofirule

Reputation: 4659

You need to add expiration lifecycle rule (Note that prefix is optional).

Example:

resource "aws_s3_bucket" "b1" {
  bucket = "b1"

  lifecycle_rule {
    enabled  = true
    id     = "expire_all_files"

    expiration {
        days = 10
      }
  }
}

see docs

UPDATE:

On v4.0 and above the aws provider api changed and now adding expiration lifecycle rule looks like:

resource "aws_s3_bucket" "b1" {
  bucket = "b1"    
}

resource "aws_s3_bucket_lifecycle_configuration" "l1" {
  bucket = aws_s3_bucket.b1.id
  rule {
    status = "Enabled"
    id     = "expire_all_files"
    expiration {
        days = 10
    }
  }
}

Upvotes: 19

TaiT's
TaiT's

Reputation: 3216

Wherever I found a code to delete it, it having prefix. What needs to be done if I have to apply to all the objects in buckets instead of prefix.

As mentioned in the doc

prefix - (Optional) Object key prefix identifying one or more objects to which the rule applies.

Which means if you don't specify any prefix, it will apply to all objects.

Upvotes: 1

Related Questions