首页 > 解决方案 > 提供者变量是否可以在 terraform 中使用?

问题描述

在 Terraform v0.12.6 中仍然无法使用变量提供程序吗?在 *.tfvars 我有列表变量 供应商

supplier = ["azurerm.core-prod","azurerm.core-nonprod"]

和 provider.tf 中定义的提供者:

provider "azurerm" {
  ...
  alias           = "core-prod"
}

provider "azurerm" {
  ...
  alias = "core-nonprod"

然后我想在 *.tf 中引用它。下面的示例使用“数据”,但同样适用于“资源”

data "azurerm_public_ip" "pip" {
  count = "${var.count}"
   ....
   provider = "${var.supplier[count.index]}"
} 

什么是解决方法?错误:无效的提供者配置参考,显示提供者参数需要提供者类型名称,可选地后跟一个句点,然后是配置别名

标签: terraformterraform-provider-azure

解决方案


无法将资源与提供者动态关联。与在静态类型的编程语言中通常无法在运行时动态切换特定符号以引用不同库的方式类似,Terraform 需要在表达式评估可能之前将资源块绑定到提供程序配置。

可以做的是编写一个模块,该模块期望从其调用者那里接收提供者配置,然后为该模块的每个实例静态选择一个提供者配置:

provider "azurerm" {
  # ...

  alias = "core-prod"
}

module "provider-agnostic-example" {
  source = "./modules/provider-agnostic-example"

  providers = {
    # This means that the default configuration for "azurerm" in the
    # child module is the same as the "core-prod" alias configuration
    # in this parent module.
    azurerm = azurerm.core-prod
  }
}

在这种情况下,模块本身与提供者无关,因此它可以在您的生产和非生产设置中使用,但是该模块的任何特定用途都必须指定它的用途。

一种常见的方法是为每个环境进行单独的配置,共享模块代表环境具有的任何共同特征,但提供了代表它们之间可能需要存在的任何差异的机会。在最简单的情况下,这可能只是由一个module块和一个provider块组成的两个配置,每个配置都有一些不同的参数表示该环境的配置,并且共享模块包含所有resourcedata块。在更复杂的系统中,可能有多个模块使用模块组合技术集成在一起。


推荐阅读