6

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.

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry thought I'd commented on this earlier. I was so close but thank you for the fix and explanation :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.