如何使用 for_each 和一组字符串创建多个 Application Insights,并将其中的每一个引用到 Web 应用程序?

How to create multiple Application Insights using for_each and a set of strings, and reference each of these to a web app?

我有许多 Web 应用程序将创建自己的 Application Insights 资源。在我的 main.tf 文件中,当我为 Web 应用程序编写配置时,我想引用创建的 AI 资源并使用它的 instrumentation_key 将其设置在 app_settings 块中,如下所示:

  app_settings = {
    "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.webapp1.instrumentation_key
  }

我想尝试使用 for_each 函数来创建所有这些 AI 资源,因为它们很相似。所以我写了下面的代码:

variables.tf

variable "applicationInsights" {
    type    = set(string)
    default = [
        "webapp1",
        "webapp2",
        "webapp3",
        "webapp4"
    ]
}

main.tf

resource "azurerm_app_service" "webapp1" {
  name                = "${var.deploymentEnvironment}-webapp1"
  location            = azurerm_resource_group.frontendResourceGroup.location
  resource_group_name = azurerm_resource_group.frontendResourceGroup.name
  app_service_plan_id = azurerm_app_service_plan.appSvcPlan.id
  app_settings = {
    "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.webapp1.instrumentation_key
  }
}

resource "azurerm_application_insights" "applicationInsights" {
  for_each = toset(var.applicationInsights)
  name                = join("-", [var.deploymentEnvironment, each.key, "appinsights"])
  location            = azurerm_resource_group.frontendResourceGroup.location
  resource_group_name = azurerm_resource_group.frontendResourceGroup.name
  application_type    = "web"
}

但是,我 运行 遇到的问题是,我不知道在 azurerm_app_service 块中为资源名称引用放置什么。如何引用 for_each 创建的另一个资源? For_each 正在创建许多具有相同“本地名称”的 azurerm_application_insights。

如何在使用 for_each 时动态命名 azurerm_application_insights 资源?我希望能够使用某种资源元参数。我基本上运行遇到这个问题:

Error: Reference to undeclared resource

on main.tf line 906, in resource "azurerm_app_service" "webapp1": 906: app_settings = merge({"APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.webapp1.instrumentation_key}, var.wbpdr_app_settings)

A managed resource "azurerm_application_insights" "webapp1" has not been declared in the root module.

设置了 for_eachresource 块作为映射出现在表达式中,使用与您传递给 for_each 的值相同的键。

在这种情况下,键 webapp1azurerm_application_insights.applicationInsights 实例将是 azurerm_application_insights.applicationInsights["webapp1"],因此如果您特别需要该对象,您可以编写以下内容:

  app_settings = {
    "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.applicationInsights["webapp1"].instrumentation_key
  }