Managing Azure Application Insights with Terraform

Learn how to deploy and manage Azure Application Insights using Terraform

Managing Azure Application Insights with Terraform

Azure Application Insights provides application performance monitoring and analytics. This guide shows you how to manage Application Insights using Terraform.

Video Tutorial

Prerequisites

  • Azure subscription
  • Terraform installed
  • Azure CLI installed
  • Basic understanding of application monitoring concepts

Project Structure

.
├── main.tf                   # Main Terraform configuration file
├── variables.tf              # Variable definitions
├── outputs.tf               # Output definitions
├── terraform.tfvars         # Variable values
└── modules/
    └── app-insights/
        ├── main.tf          # Application Insights specific configurations
        ├── variables.tf      # Module variables
        ├── alerts.tf        # Alert configurations
        └── outputs.tf       # Module outputs

Basic Configuration

Here’s a basic example of setting up Application Insights:

resource "azurerm_resource_group" "monitoring_rg" {
  name     = "monitoring-resources"
  location = "eastus"
}

resource "azurerm_log_analytics_workspace" "workspace" {
  name                = "monitoring-workspace"
  location           = azurerm_resource_group.monitoring_rg.location
  resource_group_name = azurerm_resource_group.monitoring_rg.name
  sku                = "PerGB2018"
  retention_in_days  = 30
}

resource "azurerm_application_insights" "app_insights" {
  name                = "app-insights"
  location           = azurerm_resource_group.monitoring_rg.location
  resource_group_name = azurerm_resource_group.monitoring_rg.name
  application_type    = "web"
  workspace_id       = azurerm_log_analytics_workspace.workspace.id

  retention_in_days = 90
}

output "instrumentation_key" {
  value     = azurerm_application_insights.app_insights.instrumentation_key
  sensitive = true
}

output "app_id" {
  value = azurerm_application_insights.app_insights.app_id
}

Advanced Features

Web Tests

Configure availability tests:

resource "azurerm_application_insights_web_test" "availability_test" {
  name                    = "availability-test"
  location               = azurerm_resource_group.monitoring_rg.location
  resource_group_name     = azurerm_resource_group.monitoring_rg.name
  application_insights_id = azurerm_application_insights.app_insights.id
  kind                   = "ping"
  frequency              = 300
  timeout                = 30
  enabled                = true
  geo_locations          = ["us-ca-sjc-azr", "us-tx-sn1-azr", "us-il-ch1-azr"]

  configuration = <<XML
<WebTest Name="availability-test" Enabled="True" Timeout="30" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
  <Items>
    <Request Method="GET" Version="1.1" Url="https://www.example.com" ThinkTime="0" />
  </Items>
  <ValidationRules>
    <ValidationRule Classname="Microsoft.VisualStudio.TestTools.WebTesting.Rules.ValidationRuleFindText, Microsoft.VisualStudio.QualityTools.WebTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" DisplayName="Find Text" Description="Verifies the existence of the specified text in the response." Level="High" ExectuionOrder="BeforeDependents">
      <RuleParameters>
        <RuleParameter Name="FindText" Value="Welcome" />
        <RuleParameter Name="IgnoreCase" Value="False" />
        <RuleParameter Name="UseRegularExpression" Value="False" />
        <RuleParameter Name="PassIfTextFound" Value="True" />
      </RuleParameters>
    </ValidationRule>
  </ValidationRules>
</WebTest>
XML
}

Smart Detection Rules

Configure smart detection rules:

resource "azurerm_application_insights_smart_detection_rule" "failure_anomalies" {
  name                    = "Failure Anomalies"
  application_insights_id = azurerm_application_insights.app_insights.id
  enabled                = true
}

Best Practices

  1. Use workspace-based Application Insights
  2. Configure appropriate retention periods
  3. Set up proper access control
  4. Use action groups for alerts
  5. Implement proper sampling for high-volume applications

Security Considerations

  1. Use Azure Key Vault for storing instrumentation keys
  2. Implement proper RBAC
  3. Use private endpoints where possible
  4. Enable diagnostic settings
  5. Regularly audit access

Monitoring Configuration

Set up monitoring and alerts:

resource "azurerm_monitor_action_group" "critical" {
  name                = "critical-alerts"
  resource_group_name = azurerm_resource_group.monitoring_rg.name
  short_name         = "critical"

  email_receiver {
    name          = "admin"
    email_address = "admin@example.com"
  }
}

resource "azurerm_monitor_metric_alert" "response_time" {
  name                = "response-time-alert"
  resource_group_name = azurerm_resource_group.monitoring_rg.name
  scopes             = [azurerm_application_insights.app_insights.id]
  description        = "Alert when response time exceeds threshold"

  criteria {
    metric_namespace = "microsoft.insights/components"
    metric_name      = "requests/duration"
    aggregation      = "Average"
    operator         = "GreaterThan"
    threshold        = 3
  }

  action {
    action_group_id = azurerm_monitor_action_group.critical.id
  }
}

Cost Management

Configure daily data cap:

resource "azurerm_application_insights" "app_insights" {
  # ... other configurations ...

  daily_data_cap_in_gb = 100
  daily_data_cap_notifications_disabled = false
}

Integration with Other Services

Integration with Azure Functions:

resource "azurerm_function_app" "function" {
  # ... other configurations ...

  app_settings = {
    "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.app_insights.instrumentation_key
    "APPLICATIONINSIGHTS_CONNECTION_STRING" = azurerm_application_insights.app_insights.connection_string
  }
}

Integration with App Service:

resource "azurerm_app_service" "webapp" {
  # ... other configurations ...

  site_config {
    app_command_line = ""
  }

  app_settings = {
    "APPINSIGHTS_INSTRUMENTATIONKEY" = azurerm_application_insights.app_insights.instrumentation_key
    "APPLICATIONINSIGHTS_CONNECTION_STRING" = azurerm_application_insights.app_insights.connection_string
  }
}

Conclusion

Azure Application Insights with Terraform provides comprehensive application monitoring capabilities. By following these best practices and configurations, you can create effective monitoring solutions for your applications in Azure.