terraform - 如果条件在 terraform 中
问题描述
我在 Azure cosmosdb 数据库中添加自动缩放设置,我的问题不是我们的所有数据库都需要自动缩放,只有选择的数据库需要自动缩放其余都是手动的。我将无法在同一资源中指定 autoscalse 块,因为这两者之间存在冲突。所以我想到了使用计数,但我将无法仅为其中一个数据库运行资源块。对于下面的例子
多变的
variable "databases" {
description = "The list of Cosmos DB SQL Databases."
type = list(object({
name = string
throughput = number
autoscale = bool
max_throughput = number
}))
default = [
{
name = "testcoll1"
throughput = 400
autoscale = false
max_throughput = 0
},
{
name = "testcoll2"
throughput = 400
autoscale = true
max_throughput = 1000
}
]
}
第一个我不需要自动缩放,下一个我需要。我的 main.tf 代码
resource "azurerm_cosmosdb_mongo_database" "database_manual" {
count = length(var.databases)
name = var.databases[count.index].name
resource_group_name = azurerm_cosmosdb_account.cosmosdb.resource_group_name
account_name = local.account_name
throughput = var.databases[count.index].throughput
}
resource "azurerm_cosmosdb_mongo_database" "database_autoscale" {
count = length(var.databases)
name = var.databases[count.index].name
resource_group_name = azurerm_cosmosdb_account.cosmosdb.resource_group_name
account_name = local.account_name
autoscale_settings {
max_throughput = var.databases[count.index].max_throughput
}
}
首先,我想运行两个块,一个带刻度,一个不带,但我将无法继续,因为它需要计数
计数 = var.autoscale_required == 真?长度(数据库):0
一开始,但就我而言,我只会在迭代时知道。我试图在块内使用动态但出错了。
*更新 我已切换到 foreach 并能够运行条件,但它仍然需要 2 个块资源“azurerm_cosmosdb_mongo_database”“database_autoscale”资源“azurerm_cosmosdb_mongo_database”“database_manual”
resource "azurerm_cosmosdb_mongo_database" "database_autoscale" {
for_each = {
for key, value in var.databases : key => value
if value.autoscale_required == true }
name = each.value.name
resource_group_name = azurerm_cosmosdb_account.cosmosdb.resource_group_name
account_name = local.account_name
autoscale_settings {
max_throughput = each.value.max_throughput
}
}
解决方案
如果我理解正确,我认为您可以使用以下方法做您想做的事情:
resource "azurerm_cosmosdb_mongo_database" "database_autoscale" {
count = length(var.databases)
name = var.databases[count.index].name
resource_group_name = azurerm_cosmosdb_account.cosmosdb.resource_group_name
account_name = local.account_name
throughput = var.databases[count.index].autoscale == false ? var.databases[count.index].throughput : null
dynamic "autoscale_settings" {
for_each = var.databases[count.index].autoscale == false ? [] : [1]
content {
max_throughput = var.databases[count.index].max_throughput
}
}
}
推荐阅读
- javascript - 单击按钮时,我无法从列表中搜索项目
- r - 使用传单在 rshiny 中创建缩略图
- c - GCC 不合格?
- scrapy - Scrapy 错误:TypeError:__init__() 得到了一个意外的关键字参数“cb_kwargs”
- c# - SqlGeography.STPolyFromText - 引发错误 24201:纬度值必须在 -90 到 90 度之间
- javascript - 从数组中获取对象并推送到新数组
- html - 使按钮不可见,仅在悬停在 div 上或输入内有文本时显示
- python - 在新的 Google 标签上粘贴数据
- reactjs - 过滤简单的平面列表
- firebase - Firestore 规则 - 用户可以在应用范围之外编写吗?