terraform 仅在值大于 1 时才使用属性?

terraform only use properties if value is greater than one?

我有一个变量var.delete_retention_policy_days。如果变量设置为 0 那么我不希望启用策略天数块。在 terraform 中有没有一种巧妙的方法来做到这一点?

delete_retention_policy {
  days = var.delete_retention_policy_days
}

这是完整资源的示例

resource "azurerm_storage_account" "example2" {
  name                     = var.azurerm_storage_account_name
  resource_group_name      = azurerm_resource_group.parameters.name
  location                 = azurerm_resource_group.parameters.location
  account_tier             = var.azurerm_storage_account_account_tier
  account_replication_type = var.azurerm_storage_account_account_replication_type
  allow_blob_public_access = var.azurerm_storage_account_allow_blob_public_access
  blob_properties {
    delete_retention_policy {
      days = var.delete_retention_policy_days
    }
    versioning_enabled = true
    change_feed_enabled = true
  }

在资源内部有条件地配置块的能力仍然是一个突出的功能请求。对于请求此功能的 Github 问题,内部开发团队提供了以下算法作为当前解决方法:

dynamic "<block name>" {
  for_each = range(<conditional> ? 1 : 0)

  content {
    ...
  }
}

对于 delete_retention_policy_days 已经是 number 类型的特定情况,这变得稍微简单一些:

dynamic "delete_retention_policy" {
  for_each = range(length(var.delete_retention_policy_days) > 0 ? 1 : 0)

  content {
    days = var.delete_retention_policy_days
  }
}

请注意,对于使用 for_each 元参数的这种条件能力,还有一些更有趣的函数:

# useful for objects with optional keys to iterate on them only if they exist
for_each = try(var.value, [])
# useful for objects with optional keys to conditionally configure a block only if they exist
for_each = range(can(var.value) ? 1 : 0)