Guy Wood
Guy Wood

Reputation: 307

Terraform Dynamic Block with conditional based on variable string values

I'm after a dynamic block only when a string var is a certain 2 values (stg or prod). This code doesn't work:

dynamic "log" {
  for_each = var.environment == "stg" || var.environment == "prod" ? [1] : [0]
    content {
      category  = "AppServiceAntivirusScanAuditLogs"
      enabled   = true
    }
}

So I want this block when environment is "stg" or "prod" but don't want it when it is anything else. This runs but the logic doesn't work.

I've done something similar in the past using a boolean variable and this has worked but am reluctant to add another variable when I can surely evaluate these strings somehow?

Also tried moving the logic to the "enabled =" field which works but due to the nature of the issue I'm having, I need to do it at the block level.

Upvotes: 6

Views: 11046

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28884

Your conditionals for the ternary are correct, but the return values are not. When coding a ternary for an optional nested block, the "falsey" return value must be empty. This can be an empty set, list, object, or map type. The type does need to be consistent with your "truthy" return value. In your situation, you are returning a list type for the "truthy" value, so we need to return an empty list type for the "falsey" value:

dynamic "log" {
  for_each = var.environment == "stg" || var.environment == "prod" ? [1] : []
  
  content {
    category  = "AppServiceAntivirusScanAuditLogs"
    enabled   = true
  }
}

As expected, there will be zero iterations on an empty value, which is the desired behavior for the return on the "falsey" conditional. As a side note, my personal preference is to return ["this"] for the "truthy" conditional on optional nested block ternaries to be consistent with recommended practices in Terraform around non-specific block naming conventions.

Upvotes: 10

Related Questions