Is there a way in terraform to have multiple lifecycle configuration blocks for a single AWS S3 bucket?

3k Views Asked by At

I am using module to create a AWS S3 bucket via terraform. This module creates a bucket with some a lot of default policies/configuration as mandated by my company. Along with that it sets some lifecycle rules using aws_s3_bucket_lifecycle_configuration.

I don't want to use those rules and they can be disabled via the inputs to the said module. But the problem is when I try to add my custom lifecycle configurations, I always get a different result each time. Sometimes my rules are applied while at other instances they are not present in the configuration.
Even the documentation says that:

NOTE: S3 Buckets only support a single lifecycle configuration. Declaring multiple aws_s3_bucket_lifecycle_configuration resources to the same S3 Bucket will cause a perpetual difference in configuration.

What can be the way around this issue?

I cant set enable_private_bucket to false, but here is the code for the configuration resource in the module.

resource "aws_s3_bucket_lifecycle_configuration" "pca_private_bucket_infrequent_access" {
  count  = var.enable_private_bucket ? 1 : 0

  bucket = aws_s3_bucket.pca_private_bucket[0].id
}
1

There are 1 best solutions below

0
On

You need to do the v3 style which is deprecated but it seems to be the only way of doing it.

Here's how I have it set up where I have extra lifecycle rules using the dynamic block

resource "aws_s3_bucket" "cache" {
  bucket        = local.cache_bucket_name
  force_destroy = false
  tags = {
    Name = "${var.vpc_name} cache"
  }
  lifecycle_rule {
    id                                     = "${local.cache_bucket_name} lifecycle rule"
    abort_incomplete_multipart_upload_days = 1
    enabled                                = true
    noncurrent_version_expiration {
      days = 1
    }
    transition {
      days          = 1
      storage_class = "INTELLIGENT_TIERING"
    }
  }
  dynamic "lifecycle_rule" {
    for_each = var.cache_expiration_rules
    content {
      id      = "${lifecycle_rule.value["prefix"]} expiration in ${lifecycle_rule.value["days"]} days"
      enabled = true
      prefix  = lifecycle_rule.value["prefix"]
      expiration {
        days = lifecycle_rule.value["days"]
      }
    }
  }
  lifecycle {
    prevent_destroy = true
  }
}