0
votes

I have many web apps that will have their own Application Insights resource created. In my main.tf file, When I write the configuration for the web app, I want to reference the created AI resource and use it's instrumentation_key to set it in the app_settings block, like this:

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

I wanted to try to use the for_each function to create all of these AI resources because they will be similar. So I write the code below:

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

However, the problem I run into, is I dont know what to put for the resource name reference in the azurerm_app_service block. How do I reference another resource created by for_each? For_each is creating many azurerm_application_insights with the same "local name".

How do I dynamically name the azurerm_application_insights resources when using for_each? I was hoping to be able to use some kind of resource meta-argument. I basically run into this problem:

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.

1

1 Answers

2
votes

A resource block with for_each set appears in expressions as a map using the same keys as the value you passed to for_each.

In this case, the instance of azurerm_application_insights.applicationInsights for the key webapp1 would be azurerm_application_insights.applicationInsights["webapp1"], so if you need that object specifically you could write the following:

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