Terraform 0.13-模块,for_each和提供者

时间:2020-09-16 07:35:30

标签: terraform terraform-provider-azure

已更新

我正在尝试使用Terraform在Azure中配置多个SQL数据库。

我的子模块具有以下提供SQL数据库的代码:

providers.tf

// default provider
provider "azurerm" {
  alias = "main"
  features {}
}

// The provider that can access the storage account to store diagnostics
provider "azurerm" {
  alias = "storage_account"
  features {}
}

sql_db.tf

resource "azurerm_mssql_database" "default" {
  name      = var.name
  base_name = var.base_name
  ...
  tags      = var.tags
  
  provider = azurerm.main
}

data.tf

data "azurerm_storage_account" "storage" {
  name = var.storage_account_name
  resource_group_name = var.storage_account_rg
  provider = azurerm.storage_account
}

我在 main.tf 文件中调用此模块,如下所示,我想使用for_each设置多个SQL数据库:

module "sql_db" {
  for_each = var.sql_db

  source = "...../sql_db.git"

  base_name = each.value.base_name
  name      = each.value.name

  providers = {
    azurerm.main = azurerm.main
    azurerm.storage_account = azurerm.storage_account
  }
}

provider "azurerm" {
  features {}
  version  = "=2.20.0"
}

// default provider
provider "azurerm" {
  alias = "main"
  features {}
}

provider "azurerm" {
  alias = "storage_account"
  features {}
}

运行计划时,出现以下错误:

Error: Module does not support for_each

  on main.tf line 35, in module "sql_db":
  35:   for_each = var.sql_db

Module "sql_db" cannot be used with for_each because it contains a nested
provider configuration for "azurerm.main", at
.terraform\modules\sql_db\providers.tf:2,10-19.

This module can be made compatible with for_each by changing it to receive all
of its provider configurations from the calling module, by using the
"providers" argument in the calling module block.


Error: Module does not support for_each

  on main.tf line 35, in module "sql_db":
  35:   for_each = var.sql_db

Module "sql_db" cannot be used with for_each because it contains a nested
provider configuration for "azurerm.storage_account", at
.terraform\modules\sql_db\providers.tf:8,10-19.

This module can be made compatible with for_each by changing it to receive all
of its provider configurations from the calling module, by using the
"providers" argument in the calling module block.

1 个答案:

答案 0 :(得分:0)

简单的答案是,它不受支持。来自Terraform documentation

<块引用>

包含自己的提供者配置的模块与 Terraform v0.13 中引入的 for_each、count 和 depends_on 参数不兼容。

HashiCorp 一直坚信提供者永远不能动态声明,这就是为什么他们不允许在 for_each 块中使用 count/provider,也不允许 for_each /count 在包含 provider 块的模块上。