Connect Application Insights to your Azure Functions App in Terraform


This goes into the “notes for Scott” category, where I post things to my blog for me. I hope this is somewhat useful for you too!

I’m in the process of writing Terraform automation for an Azure Functions application I’ve built. When the deployment completed and I went to the Azure Functions application in the Azure portal (https://portal.azure.com), I got a message stating that Application Insights wasn’t connected to the Functions App:

Application Insights is not configured. Configure Application Insights to capture function logs.

The fix isn’t well documented, yet. After deploying a functions app via the portal, I found the link and it’s pretty simple: Azure Functions uses an app setting named APPINSIGHTS_INSTRUMENTATIONKEY. Just add that with the right value and things work.

To put it all together, you will deploy an app service plan, Application Insights, and an Azure Function App:

resource "azurerm_app_service_plan" "app_service_plan" {
  name                = "${var.base_name}appserv"
  location            = "${azurerm_resource_group.rg.location}"
  resource_group_name = "${azurerm_resource_group.rg.name}"
  kind                = "Linux"
  reserved            = true
  sku {
    tier = "Basic"
    size = "B1"
  }
}
resource "azurerm_application_insights" "ai" {
  name                = "${var.base_name}ai"
  location            = "${azurerm_resource_group.rg.location}"
  resource_group_name = "${azurerm_resource_group.rg.name}"
  application_type    = "web"
}
Once created, the azurerm_application_insights resource has a value called instrumentation_key. Connect that to the APPINSIGHTS_INSTRUMENTATIONKEY app setting in your azurerm_function_app to connect AppInsights to your Azure Functions.
resource "azurerm_function_app" "apis" {
  name                      = "${var.base_name}func"
  location                  = "${azurerm_resource_group.rg.location}"
  resource_group_name       = "${azurerm_resource_group.rg.name}"
  app_service_plan_id       = "${azurerm_app_service_plan.app_service_plan.id}"
  storage_connection_string = "${azurerm_storage_account.az_backend.primary_connection_string}"
  https_only                = true
  version                   = "~2"

  app_settings = {
    APPINSIGHTS_INSTRUMENTATIONKEY = "${azurerm_application_insights.ai.instrumentation_key}"
  }

  site_config {
    cors { 
      allowed_origins = ["https://www.${var.domain_name}"]
    }
  }
}

Upon running this, the error message went away and Azure Functions showed I had connected everything correctly.