首页 > 解决方案 > 如果条件在 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
  }
}

标签: terraformazure-cosmosdbterraform-provider-azureazure-cosmosdb-mongoapi

解决方案


如果我理解正确,我认为您可以使用以下方法做您想做的事情:

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
      }
  }
}

推荐阅读