Skip to content

Instantly share code, notes, and snippets.

@EmilyBurak
Created June 28, 2024 15:11
Show Gist options
  • Select an option

  • Save EmilyBurak/4339efd1c38a8d8f257c3fff9cb116dd to your computer and use it in GitHub Desktop.

Select an option

Save EmilyBurak/4339efd1c38a8d8f257c3fff9cb116dd to your computer and use it in GitHub Desktop.
An example of how to use dynamic blocks to make s3 storage class transitions optional, inspired by needing to modify child code inheriting from a parent s3 bucket module with transitions enabled by default to suppress Glacier transitions in favor of simply expiring objects.
# variables.tf
variable "transition_enabled" {
default = false
description = "Enable transition of S3 objects in a given bucket to Glacier storage class"
type = bool
}
variable "transition_to_glacier" {
default = 30
description = "The number of days to wait before transitioning an object to Glacier"
type = number
}
variable "expiration_days" {
# would cause an error if the optional/dynamic config is not in place, try it out! you can't set objects to expire BEFORE they are set to transition to another storage class
default = 15
description = "The number of days before an object expires"
type = number
}
# if you want multiple transition rules for a more advanced use case
# variable "transition_rules" {
# default = []
# description = "The transition rules for the S3 bucket"
# type = list(object({
# days = number
# storage_class = string
# }))
# }
# main.tf or module_path/main.tf if using as a module in another configuration file
resource "aws_s3_bucket" "dynamic-test-bucket" {
bucket = "terraform-dynamic-test-bucket-lifecycles"
}
resource "aws_s3_bucket_lifecycle_configuration" "dynamic-test-config" {
bucket = aws_s3_bucket.dynamic-test-bucket.id
rule {
id = "logs"
status = "Enabled"
# or non_concurrent_object_transition if you want to transition objects one by one instead of in parallel as they age out of the standard storage class window
dynamic "transition" {
# if transition enabled, then create a transition block, or var.transition_rules and attendant modifications if using multiple rules
for_each = var.transition_enabled ? [1] : []
content {
days = var.glacier_transition_days
storage_class = "GLACIER"
}
}
expiration {
days = var.expiration_days
}
}
}
# See https://stackoverflow.com/questions/66131173/how-to-make-s3-lifecycle-rule-transition-optional-using-terraform-12,
# https://www.terraform.io/docs/language/meta-arguments/dynamic.html for more information on how to use dynamic blocks in Terraform and
# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_lifecycle_configuration for references
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment