How to conditionally remove / add object from a dynamic content

Please help me to update the terraform script if i want to conditionally remove replication_time from the dynamically created content, say if a var.rm == true then dont set replication_time.

resource "aws_s3_bucket_replication_configuration" "replication" {
  dynamic "rule" {
    # we use deploy flag so rule value may be null
    for_each = {
      for k, v in var.replication_rules :
      k => v if v != null
    }

    content {
      destination {
         replication_time {
          status = rule.value.replication_time_control
          time {
            minutes = 15
          }
        }
      }
    }
  }
}

[Charlotte v2.1 Transformer - Goggle DeepMind Assist]

To conditionally include or exclude the replication_time block based on a variable, such as var.rm, you can use Terraform’s dynamic block inside the destination block. This approach allows you to conditionally add the entire replication_time block based on the value of var.rm.

Here’s an updated version of your Terraform script with a conditional dynamic block for replication_time:

hclCopy code

resource "aws_s3_bucket_replication_configuration" "replication" {
  dynamic "rule" {
    for_each = {for k, v in var.replication_rules : k => v if v != null}

    content {
      destination {
        # Conditional dynamic block for replication_time
        dynamic "replication_time" {
          for_each = var.rm == true ? [] : [1]  # If var.rm is true, don't include replication_time, otherwise include it.
          content {
            status = rule.value.replication_time_control
            time {
              minutes = 15
            }
          }
        }
      }
    }
  }
}

In this script, the dynamic "replication_time" block will only be included if var.rm is not true. The for_each in the dynamic "replication_time" block is set to an empty list [] if var.rm is true, effectively removing the block, and to [1] (a list with a single element) if var.rm is not true, which includes the block exactly once.

This approach maintains the dynamic nature of your Terraform configuration while allowing you to conditionally include or exclude specific parts of the configuration. Make sure that var.rm is defined in your variables file or passed as an input variable to your Terraform configuration.

1 Like

Thank you @rtwolfe :slight_smile: it works. Appreciate your timely response. :pray: