I am trying to create a aws_s3_bucket_lifecycle_configuration
resource but only if bucket_lifecycle
variable is not empty. Current code works fine and create multiple rules within single lifecycle configuration but it is failing if bucket_lifecycle variable is empty (no aws_s3_bucket_lifecycle_configuration is expected)
Current code:
locals {
bucket_lifecycle = { for k, v in var.lifecycle_rules : k => v }
}
resource "aws_s3_bucket_lifecycle_configuration" "this" {
bucket = aws_s3_bucket.this.id
dynamic "rule" {
for_each = local.bucket_lifecycle
content {
id = try(rule.value.id, null)
status = try(rule.value.enabled, true) ? "Enabled" : "Disabled"
dynamic "filter" {
for_each = try(rule.value.prefix, null) == null ? [] : toset(["0"])
content {
prefix = lookup(rule.value, "prefix", null)
and {
tags = lookup(rule.value, "tags", null)
}
}
}
dynamic "expiration" {
for_each = lookup(rule.value, "expiration", {})
content {
date = lookup(expiration.value, "date", null)
days = lookup(expiration.value, "days", null)
expired_object_delete_marker = lookup(expiration.value, "expired_object_delete_marker", false)
}
}
dynamic "noncurrent_version_expiration" {
for_each = lookup(rule.value, "noncurrent_version_expiration", {})
content {
noncurrent_days = lookup(noncurrent_version_expiration.value, "days", null)
}
}
dynamic "noncurrent_version_transition" {
for_each = lookup(rule.value, "noncurrent_version_transition", {})
content {
noncurrent_days = lookup(noncurrent_version_transition.value, "days", null)
storage_class = noncurrent_version_transition.value.storage_class
}
}
dynamic "transition" {
for_each = lookup(rule.value, "transition", {})
content {
date = lookup(transition.value, "date", null)
days = lookup(transition.value, "days", null)
storage_class = transition.value.storage_class
}
}
}
}
}
I’ve tried to change it to:
resource "aws_s3_bucket_lifecycle_configuration" "this" {
for_each = length(local.bucket_lifecycle) > 0 ? local.bucket_lifecycle : {}
bucket = aws_s3_bucket.this.id
dynamic "rule" {
for_each = each.value
...
but that doesn’t work, throwing list of errors like:
Invalid value for "inputMap" parameter: lookup() requires a map as the first argument.
The module configuration looks like:
module "s3" {
[...]
lifecycle_rules = [
{
id = "first"
enable = true
prefix = "*/path1/"
expiration = [
{
days = 1
}
]
noncurrent_version_expiration = [
{
days = 1
}
]
},
{
id = "second"
enable = true
prefix = "*/path2/"
expiration = [
{
days = 1
}
]
noncurrent_version_expiration = [
{
days = 1
}
]
}
]
policy = ""
}