首页 > 解决方案 > Terraform 0.13 - 模块、for_each 和提供程序

问题描述

更新

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

我的子模块具有以下代码,用于配置 SQL 数据库:

提供者.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
}

数据.tf

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

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

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.

标签: terraformterraform-provider-azure

解决方案


显然他们已在 0.15.x 中修复了此问题,请参见此处:

https://github.com/hashicorp/terraform/pull/27739


推荐阅读