TerraForm仅在值大于1时才使用属性? [英] terraform only use properties if value is greater than one?
本文介绍了TerraForm仅在值大于1时才使用属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个变量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)
这篇关于TerraForm仅在值大于1时才使用属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文