for_each function in dynmaic block Terraform

Viewed 29

I am using the dynamic block like below for s3 encryption. I wanted the values based on 'true' for sse-algorithm under the rule. If it's true, I need to assign the value "aws:kms" else I need to assign to "AES256". Any help on this is appreciated?

dynamic "server_side_encryption_configuration" {
    for_each = local.encryption == "SSE-KMS" ? [true] : []
    content {
      rule {
        apply_server_side_encryption_by_default {
          sse_algorithm = "aws:kms"
          kms_master_key_id = local.kmsKey
        }
      }
    }
  }
1 Answers

You are rather close and merely need to remove the conditional dynamic block, and refactor the ternary logic to the sse_algorithm argument value:

rule {
  apply_server_side_encryption_by_default {
    sse_algorithm = local.encryption == "SSE-KMS" ? "aws:kms" : "AES256"
    kms_master_key_id = local.encryption == "SSE-KMS" ? local.kmsKey : null
  }
}
Related