### Complete Provider Configuration Example Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md A minimal, complete provider configuration suitable for most deployments, including version constraints for multiple providers. ```hcl terraform { required_version = ">= 1.9, < 2.0" required_providers { azurerm = { source = "hashicorp/azurerm" version = ">=3.71, <5.0.0" } azapi = { source = "Azure/azapi" version = "~> 2.4, < 3.0.0" } modtm = { source = "azure/modtm" version = "~> 0.3" } random = { source = "hashicorp/random" version = "~> 3.5" } } } provider "azurerm" { features { resource_group { prevent_deletion_if_contains_resources = true } } } provider "azapi" {} provider "modtm" {} provider "random" {} ``` -------------------------------- ### Terraform Registry Module Source Example Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/AGENTS.md This example demonstrates how to reference an AVM module from the Terraform Registry. Replace '{module}' with the specific AVM module name. ```terraform source = "https://registry.terraform.io/modules/Azure/{module}/azurerm/latest" ``` -------------------------------- ### GitHub AVM Module Source Example Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/AGENTS.md This example shows how to reference an AVM module directly from GitHub. Adjust '{type}', '{service}', and '{resource}' according to the module's specifics. ```terraform source = "https://github.com/Azure/terraform-azurerm-avm-{type}-{service}-{resource}" ``` -------------------------------- ### Example: Configuring Diagnostic Settings for Log Analytics Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/input-variables.md This example demonstrates how to configure diagnostic settings to send Application Insights logs to a Log Analytics workspace. It specifies retention policies for 'AppRequests' and 'AppExceptions'. ```hcl diagnostic_settings = { analytics_logs = { name = "diag-analytics" workspace_resource_id = azurerm_log_analytics_workspace.analytics.id logs = [ { category = "AppRequests" enabled = true retention_policy = { days = 30 enabled = true } }, { category = "AppExceptions" enabled = true } ] } storage_archive = { ``` -------------------------------- ### Example Custom Timeouts for Application Insights Component Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/input-variables.md Provides an example of how to set custom timeout values for the create and delete operations of an Application Insights component. ```hcl timeouts = { create = "1h" delete = "30m" } ``` -------------------------------- ### Pinning Provider Versions in Production Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Specify exact provider versions for production environments to ensure consistent deployments. This example pins the `azurerm` and `azapi` providers. ```hcl terraform { required_providers { azurerm = { source = "hashicorp/azurerm" version = "= 4.5.2" # Exact version } azapi = { source = "Azure/azapi" version = "= 2.4.8" } } } ``` -------------------------------- ### Development Environment Provider Configuration Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Set up Terraform and provider versions for a development environment. This example specifies version constraints and configures the `azurerm`, `azapi`, `modtm`, and `random` providers. ```hcl terraform { required_version = ">= 1.9, < 2.0" required_providers { azurerm = { source = "hashicorp/azurerm", version = ">=3.71, <5.0" } azapi = { source = "Azure/azapi", version = "~> 2.4" } modtm = { source = "azure/modtm", version = "~> 0.3" } random = { source = "hashicorp/random", version = "~> 3.5" } } } provider "azurerm" { features {} } provider "azapi" {} provider "modtm" {} provider "random" {} ``` -------------------------------- ### Configuring Multi-Region Deployments with Provider Aliases Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Use provider aliases to configure and deploy resources to multiple Azure regions. This example sets up `azurerm` providers for primary and secondary regions and assigns them to modules. ```hcl provider "azurerm" { alias = "primary" features {} # Configure for primary region } provider "azurerm" { alias = "secondary" features {} # Configure for secondary region } module "app_insights_primary" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" providers = { azurerm = azurerm.primary azapi = azapi.primary modtm = modtm.primary random = random.primary } # Configuration for primary region } module "app_insights_secondary" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" providers = { azurerm = azurerm.secondary azapi = azapi.secondary modtm = modtm.secondary random = random.secondary } # Configuration for secondary region } ``` -------------------------------- ### Example Kusto Query for Dedicated Tables Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md Demonstrates a typical Kusto query for retrieving data from dedicated tables, specifically summarizing request counts by client type. ```kusto AppRequests_CL | where timestamp > ago(1d) | summarize count() by strcat(client_Type) ``` -------------------------------- ### Module Usage Telemetry Data Example Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/quick-reference.md This JSON object represents the metadata sent when module telemetry is enabled. It includes subscription ID, tenant ID, module source and version, location, and a random tracking ID. No application data is included. ```json { "subscription_id": "anonymized-uuid", "tenant_id": "anonymized-uuid", "module_source": "registry.terraform.io/Azure/avm-res-insights-component/azurerm", "module_version": "0.x.x", "location": "eastus", "random_id": "random-tracking-uuid" } ``` -------------------------------- ### Terraform Provider Version Constraint Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/AGENTS.md For providers used with AVM modules, it is recommended to use pessimistic version constraints. This example shows how to set a version constraint for the 'azurerm' provider. ```terraform version = "~> 1.0" ``` -------------------------------- ### Deploy Secure Application Insights Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/usage-examples.md Configure Application Insights with network isolation and enhanced security controls. This example disables internet ingestion and query, enforces local authentication, and enables IP masking. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = azurerm_resource_group.this.location name = "appinsights-secure" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id # Network isolation internet_ingestion_enabled = false internet_query_enabled = false monitor_private_link_scope = { ampls = { resource_id = azurerm_monitor_private_link_scope.this.id kind = "Resource" } } # Authentication security local_authentication_disabled = true # Data protection disable_ip_masking = false # Keep IP masking enabled for privacy sampling_percentage = 100 # Access control role_assignments = { monitoring_admin = { role_definition_id_or_name = "Monitoring Contributor" principal_id = data.azuread_group.monitoring_admins.object_id principal_type = "Group" } metrics_publisher = { role_definition_id_or_name = "Monitoring Metrics Publisher" principal_id = azurerm_user_assigned_identity.app.principal_id principal_type = "ServicePrincipal" } } # Resource protection lock = { kind = "CanNotDelete" name = "appinsights-lock" } enable_telemetry = false # Disable telemetry in high-security environment tags = { security_level = "high" compliance = "pci-dss" } } ``` -------------------------------- ### Pinning AVM Module Version in Terraform Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/AGENTS.md When using AVM modules, it's crucial to pin to a specific version for predictable deployments. This example shows how to specify the version. ```terraform version = "1.2.3" ``` -------------------------------- ### Terraform Configuration with Diagnostic Settings Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/examples/diagnostic_settings/README.md This snippet shows a basic Terraform configuration including provider setup and module calls for deploying resources with diagnostic settings enabled. It utilizes helper modules for region and naming conventions. ```hcl terraform { required_version = "~> 1.3" required_providers { azapi = { source = "Azure/azapi" version = ">=2.9.0, < 3.0.0" } azurerm = { source = "hashicorp/azurerm" version = ">=3.71, < 5.0.0" } random = { source = "hashicorp/random" version = "~> 3.5" } } } provider "azurerm" { features {} } provider "azapi" {} ## Section to provide a random Azure region for the resource group # This allows us to randomize the region for the resource group. module "regions" { source = "Azure/avm-utl-regions/azurerm" version = "0.12.0" is_recommended = true } # This allows us to randomize the region for the resource group. resource "random_integer" "region_index" { max = length(module.regions.regions) - 1 min = 0 } ## End of section to provide a random Azure region for the resource group # This ensures we have unique CAF compliant names for our resources. module "naming" { source = "Azure/naming/azurerm" version = "0.4.3" } resource "azapi_resource" "resource_group" { location = module.regions.regions[random_integer.region_index.result].name name = module.naming.resource_group.name_unique type = "Microsoft.Resources/resourceGroups@2024-03-01" response_export_values = [] } #Log Analytics Workspace for diagnostic settings. Required for workspace-based diagnostic settings. resource "azapi_resource" "log_insights" { location = azapi_resource.resource_group.location name = "${module.naming.log_analytics_workspace.name_unique}-ai" parent_id = azapi_resource.resource_group.id type = "Microsoft.OperationalInsights/workspaces@2025-07-01" body = { properties = { sku = { name = "PerGB2018" } retentionInDays = 30 } } response_export_values = [] } resource "azapi_resource" "log_diagnostic" { location = azapi_resource.resource_group.location name = "${module.naming.log_analytics_workspace.name_unique}-diag" parent_id = azapi_resource.resource_group.id type = "Microsoft.OperationalInsights/workspaces@2025-07-01" body = { properties = { sku = { name = "PerGB2018" } retentionInDays = 30 features = { disableLocalAuth = true } } } response_export_values = [] } # This is the module call # Do not specify location here due to the randomization above. # Leaving location as `null` will cause the module to use the resource group location ``` -------------------------------- ### Upgrade azapi Provider Locally Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md Execute 'terraform init -upgrade=azapi' after modifying the 'azapi' provider version constraint. This command updates your local installation to use the newly specified 'azapi' provider version. ```bash # Update provider constraint terraform init -upgrade=azapi ``` -------------------------------- ### Configure Application Insights Instrumentation Key Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Provides examples for using the Application Insights instrumentation key, including setting it in local variables for application configuration, storing it in Azure Key Vault, and passing it during application deployment. Treat this key as a credential. ```hcl # Provide to application configuration locals { app_config = { APPINSIGHTS_INSTRUMENTATIONKEY = module.app_insights.instrumentation_key } } # Store in Azure Key Vault resource "azurerm_key_vault_secret" "instrumentation_key" { name = "appinsights-instrumentation-key" value = module.app_insights.instrumentation_key key_vault_id = azurerm_key_vault.this.id } # Pass to application deployment locals { app_settings = { "APPINSIGHTS_INSTRUMENTATIONKEY" = module.app_insights.instrumentation_key } } ``` -------------------------------- ### Terraform Initialization and Deployment Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/quick-reference.md Commands to initialize, validate, plan, and apply Terraform configurations. Use `terraform plan -out` to save the execution plan for later application. ```bash terraform init terraform validate terraform plan -out=tfplan terraform apply tfplan terraform destroy terraform output instrumentation_key terraform state show 'module.app_insights.azurerm_application_insights.this' terraform state list | grep app_insights ``` -------------------------------- ### Initialize Terraform and Upgrade Providers Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Run `terraform init -upgrade` to initialize the Terraform working directory and upgrade providers. This is a common solution for 'Invalid or Unknown Provider' issues. ```bash terraform init -upgrade ``` -------------------------------- ### Configure Application Insights SDK with Instrumentation Key Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Demonstrates how to configure Application Insights SDKs using the instrumentation key in C#, Python, and JavaScript. ```csharp // C# / .NET using Microsoft.ApplicationInsights; var telemetryClient = new TelemetryClient(); telemetryClient.InstrumentationKey = "instrumentation-key-from-output"; telemetryClient.TrackEvent("Event"); ``` ```python # Python from opencensus.ext.azure.log_exporter import AzureLogHandler import logging handler = AzureLogHandler( instrumentation_key="instrumentation-key-from-output" ) logging.getLogger(__name__).addHandler(handler) ``` ```javascript // JavaScript appInsights.config.instrumentationKey = "instrumentation-key-from-output"; appInsights.start(); ``` -------------------------------- ### Configure Application Insights with Connection String Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Shows how to use the Application Insights connection string for SDK initialization, which is the preferred method for modern implementations. This output is marked as sensitive. ```hcl # Provide to application configuration locals { app_config = { APPLICATIONINSIGHTS_CONNECTION_STRING = module.app_insights.connection_string } } ``` -------------------------------- ### Typical Kusto Query for AzureDiagnostics Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md An example Kusto query to filter logs from the AzureDiagnostics table for a specific resource type and category. Useful for analyzing data when using the legacy destination type. ```kusto AzureDiagnostics | where ResourceType == "COMPONENTS" | where Category == "AppRequests" ``` -------------------------------- ### Configure Application Insights in C# / .NET Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Initializes the TelemetryClient for Application Insights in a C# .NET application using a connection string. ```csharp using Microsoft.ApplicationInsights; var connectionString = "connection-string-from-output"; var telemetryClient = new TelemetryClient( new TelemetryConfiguration(connectionString) ); ``` -------------------------------- ### Configuring Azure Authentication Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Set environment variables to authenticate with Azure using different methods: CLI, Service Principal, Managed Service Identity (MSI), or OpenID Connect (OIDC). ```bash # CLI authentication az login # Service principal export ARM_CLIENT_ID="client-id" export ARM_CLIENT_SECRET="client-secret" export ARM_TENANT_ID="tenant-id" export ARM_SUBSCRIPTION_ID="subscription-id" # MSI (Azure-hosted) export ARM_USE_MSI=true # OIDC (GitHub Actions, etc.) export ARM_USE_OIDC=true ``` -------------------------------- ### Terraform Resource Migration Example Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/resource-definitions.md These `moved` blocks in Terraform HCL are used to migrate existing resources from older versions to newer ones without causing destruction and recreation. They specify the source and destination of the resource. ```hcl moved { from = azurerm_management_lock.this to = azapi_resource.lock } moved { from = azurerm_role_assignment.this to = azapi_resource.role_assignment } ``` -------------------------------- ### Verify Diagnostic Setting Creation (Azure CLI) Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md A bash command using the Azure CLI to list diagnostic settings for a specific Application Insights resource and check the configured log categories. Useful for troubleshooting. ```bash az monitor diagnostic-settings list \ --resource /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Insights/components/{name} \ --query "[].{name:name, logs:logs[0].category}" ``` -------------------------------- ### Terraform Safe Upgrade Pattern Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md Follow this step-by-step pattern for safely upgrading Terraform configurations, including backing up state, planning changes, reviewing the plan, testing in a non-production environment, and finally applying the changes in production. ```bash # 1. Backup state terraform state pull > backup.tfstate # 2. Plan upgrade terraform plan -out=upgrade.tfplan # 3. Review plan output terraform show upgrade.tfplan | grep -E "^ (~|-|\+) " # 4. Test in non-prod first cd ../non-prod # Repeat steps 1-3 # 5. Apply in production terraform apply upgrade.tfplan # 6. Verify terraform refresh terraform show ``` -------------------------------- ### Minimal Application Insights Deployment Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/usage-examples.md This snippet shows the most basic configuration for deploying an Application Insights component with only the required variables. It includes setting up prerequisites like resource group and Log Analytics workspace. ```hcl terraform { required_version = ">= 1.9" required_providers { azurerm = { source = "hashicorp/azurerm" version = ">=3.71, <5.0" } } } provider "azurerm" { features {} } # Create prerequisites resource "azurerm_resource_group" "this" { name = "rg-myapp" location = "eastus" } resource "azurerm_log_analytics_workspace" "this" { name = "law-myapp" location = azurerm_resource_group.this.location resource_group_name = azurerm_resource_group.this.name sku = "PerGB2018" } # Deploy Application Insights module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = azurerm_resource_group.this.location name = "appinsights-myapp" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id } # Outputs output "instrumentation_key" { value = module.app_insights.instrumentation_key sensitive = true description = "Use in SDK configuration" } output "connection_string" { value = module.app_insights.connection_string sensitive = true description = "Use in SDK initialization" } ``` -------------------------------- ### Event Hub and Stream Analytics for Log Filtering Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md Streams logs to an Event Hub and uses Stream Analytics to filter them before storage. This example shows how to configure streaming for 'AppRequests' and implies a Stream Analytics job that filters for errors. ```hcl diagnostic_settings = { streaming = { event_hub_authorization_rule_resource_id = azurerm_eventhub_authorization_rule.this.id logs = [ { category = "AppRequests", enabled = true } ] } } # Stream Analytics job filters and archives only errors resource "azurerm_stream_analytics_job" "filter" { name = "sa-filter-errors" # Queries for errors only, writes to storage } ``` -------------------------------- ### Reference Application Insights Resource ID Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Shows how to reference the Application Insights resource ID in other Terraform modules or for external use via Terraform outputs. Also includes an example of querying the resource using Azure CLI. ```hcl # Reference in another module module "diagnostics" { source = "./modules/diagnostics" target_resource_id = module.app_insights.resource_id workspace_resource_id = azurerm_log_analytics_workspace.this.id } # Output for external use output "app_insights_id" { value = module.app_insights.resource_id } # Query with Azure CLI # az resource show --id $(terraform output -raw resource_id) ``` -------------------------------- ### Configure Application Insights with Alerts and Actions Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/usage-examples.md This snippet demonstrates setting up Application Insights with specific application types and configuring metric alerts for high failure rates and low availability. Ensure an action group is defined separately. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = azurerm_resource_group.this.location name = "appinsights-alert" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id application_type = "web" tags = { monitoring = "enabled" } } # Alert rule for high failure rate resource "azurerm_monitor_metric_alert" "failure_rate" { name = "alert-appinsights-high-failure" resource_group_name = azurerm_resource_group.this.name scopes = [module.app_insights.resource_id] description = "Alert when request failure rate exceeds 5%" criteria { metric_name = "failedRequests" metric_namespace = "Microsoft.Insights/components" aggregation = "Total" operator = "GreaterThan" threshold = "5" } window_size = "PT5M" frequency = "PT1M" action { action_group_id = azurerm_monitor_action_group.this.id } } # Alert rule for availability tests resource "azurerm_monitor_metric_alert" "availability" { name = "alert-appinsights-low-availability" resource_group_name = azurerm_resource_group.this.name scopes = [module.app_insights.resource_id] description = "Alert when availability drops below 99%" criteria { metric_name = "availabilityResults/availabilityPercentage" metric_namespace = "Microsoft.Insights/components" aggregation = "Average" operator = "LessThan" threshold = "99" } window_size = "PT15M" frequency = "PT5M" action { action_group_id = azurerm_monitor_action_group.this.id } } ``` -------------------------------- ### Update azurerm Provider Version Constraint Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md Modify the 'azurerm' provider version constraint in your 'terraform.tf' file to allow for upgrades. This example shows changing the constraint from '< 4.0' to '< 5.0' to accommodate newer provider versions while maintaining compatibility with the module. ```hcl # Old azurerm = ">= 3.71, < 4.0" # New azurerm = ">= 3.71, < 5.0" ``` -------------------------------- ### Upgrading Terraform Providers Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Use `terraform init -upgrade` to upgrade all providers within their version constraints. You can also upgrade specific providers or check for available upgrades. ```bash # Upgrade all providers within constraints terraform init -upgrade # Upgrade specific provider terraform init -upgrade=azurerm # Check for available upgrades terraform version ``` -------------------------------- ### Terraform Apply Command Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/INDEX.md This represents the final deployment step for most common tasks. Ensure your Terraform configuration is complete before running. ```bash terraform apply ``` -------------------------------- ### High-Security Application Insights with Private Link Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/quick-reference.md Configure Application Insights for high-security environments by disabling public internet ingestion and querying, and enabling local authentication. This setup is suitable for scenarios requiring strict network isolation and enhanced security controls. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = "eastus" name = "appinsights-secure" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id internet_ingestion_enabled = false internet_query_enabled = false local_authentication_disabled = true disable_ip_masking = false monitor_private_link_scope = { ampls = { resource_id = azurerm_monitor_private_link_scope.this.id } } lock = { kind = "CanNotDelete" } } ``` -------------------------------- ### Standard Diagnostic Settings for Application Insights Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md This configuration provides a balanced approach for typical production workloads, including requests, exceptions, traces, metrics, and dependencies. ```hcl diagnostic_settings = { standard = { workspace_resource_id = azurerm_log_analytics_workspace.this.id logs = [ { category = "AppRequests", enabled = true }, { category = "AppExceptions", enabled = true }, { category = "AppTraces", enabled = true }, { category = "AppMetrics", enabled = true }, { category = "AppDependencies", enabled = true } ] metrics = [ { category = "AllMetrics", enabled = true } ] } } ``` -------------------------------- ### Use Application Insights Name Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Demonstrates how to use the Application Insights resource name in local variables for constructing diagnostic setting names or in resource tags. Also shows how to output the name for script consumption. ```hcl # Use in diagnostic setting names locals { app_insights_name = module.app_insights.name diag_setting_name = "diag-${local.app_insights_name}" } # Reference in tags or naming conventions tags = { associated_app_insights = module.app_insights.name } # Output for script consumption output "app_insights_name" { value = module.app_insights.name } ``` -------------------------------- ### Update azapi Provider Version Constraint Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md Adjust the 'azapi' provider version constraint to specify the desired future minor versions. This example shows updating from '~> 2.4' (allowing 2.4.x) to '~> 2.5' (allowing 2.5.x) for future minor releases. ```hcl # Old azapi = "~> 2.4" # Allows 2.4.x through 2.x # New (when available) azapi = "~> 2.5" # Future minor versions ``` -------------------------------- ### Terraform Configuration with Attached Storage Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/examples/attach_storage/README.md Full Terraform configuration for deploying an Azure Application Insights component with attached storage enabled for the profiler. It includes provider configurations, module definitions for regions and naming, resource group, log analytics workspace, and storage account setup. ```hcl terraform { required_version = "~> 1.3" required_providers { azurerm = { source = "hashicorp/azurerm" version = ">=3.71, < 5.0.0" } random = { source = "hashicorp/random" version = "~> 3.5" } } } provider "azurerm" { features { resource_group { prevent_deletion_if_contains_resources = false } } } module "regions" { source = "Azure/avm-utl-regions/azurerm" version = "0.12.0" is_recommended = true } resource "random_integer" "region_index" { max = length(module.regions.regions) - 1 min = 0 } module "naming" { source = "Azure/naming/azurerm" version = "0.4.3" } resource "azurerm_resource_group" "this" { location = module.regions.regions[random_integer.region_index.result].name name = module.naming.resource_group.name_unique } resource "azurerm_log_analytics_workspace" "this" { location = azurerm_resource_group.this.location name = module.naming.log_analytics_workspace.name_unique resource_group_name = azurerm_resource_group.this.name sku = "PerGB2018" } resource "azurerm_storage_account" "this" { account_replication_type = "ZRS" account_tier = "Standard" location = azurerm_resource_group.this.location name = module.naming.storage_account.name_unique resource_group_name = azurerm_resource_group.this.name min_tls_version = "TLS1_2" } module "test" { source = "../../" location = azurerm_resource_group.this.location name = module.naming.application_insights.name_unique resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id enable_telemetry = var.enable_telemetry force_customer_storage_for_profiler = true linked_storage_account = { profiler = { resource_id = azurerm_storage_account.this.id } } } ``` -------------------------------- ### Configure Application Insights in JavaScript (Node.js) Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Initializes Application Insights in a Node.js application using the 'applicationinsights' package and a connection string. ```javascript const appInsights = require("applicationinsights"); appInsights .setup("connection-string-from-output") .start(); ``` -------------------------------- ### Configure Application Insights in Python Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Sets up an AzureLogHandler for Application Insights in a Python application using a connection string. ```python from opencensus.ext.azure.log_exporter import AzureLogHandler handler = AzureLogHandler( connection_string="connection-string-from-output" ) ``` -------------------------------- ### Terraform State Management for Downgrades Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md If state compatibility issues arise after downgrading, pull the current state to a backup file, remove the Terraform state, and re-initialize. ```bash # If downgrading and state issues occur terraform state pull > backup.tfstate rm -rf .terraform terraform init terraform plan ``` -------------------------------- ### Minimal Diagnostic Settings for Application Insights Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md Use this configuration for cost-optimized environments, focusing on essential logs like exceptions and requests. ```hcl diagnostic_settings = { minimal = { workspace_resource_id = azurerm_log_analytics_workspace.this.id logs = [ { category = "AppExceptions", enabled = true }, { category = "AppRequests", enabled = true } ] metrics = [ { category = "AllMetrics", enabled = true } ] } } ``` -------------------------------- ### Managing Terraform Lock File Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Add the `.terraform.lock.hcl` file to version control to ensure all team members use the same provider versions. Run `terraform init` after adding it. ```bash # Check in lock file to version control git add .terraform.lock.hcl # All team members get same provider versions terraform init ``` -------------------------------- ### Deploy Web Application with Application Insights Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/usage-examples.md This snippet shows how to deploy a web application and link it to an Application Insights component. It configures essential application settings for instrumentation. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = azurerm_resource_group.this.location name = "appinsights-web" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id } # Application Service Plan resource "azurerm_app_service_plan" "this" { name = "asp-myapp" location = azurerm_resource_group.this.location resource_group_name = azurerm_resource_group.this.name kind = "Linux" reserved = true sku { tier = "Basic" size = "B1" } } # Web App linked to Application Insights resource "azurerm_app_service" "web" { name = "app-myapp" app_service_plan_id = azurerm_app_service_plan.this.id location = azurerm_resource_group.this.location resource_group_name = azurerm_resource_group.this.name app_settings = { "APPINSIGHTS_INSTRUMENTATIONKEY" = module.app_insights.instrumentation_key "APPLICATIONINSIGHTS_CONNECTION_STRING" = module.app_insights.connection_string "ApplicationInsightsAgent_EXTENSION_VERSION" = "~3" } depends_on = [module.app_insights] } ``` -------------------------------- ### Azure CLI for Application Insights Management Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/quick-reference.md Commands to list, show, and retrieve details for Application Insights resources using the Azure CLI. Useful for managing and inspecting resources outside of Terraform. ```bash az monitor app-insights component list az monitor app-insights component show \ --resource-group \ --app az monitor app-insights component show \ --resource-group \ --app \ --query instrumentationKey -o tsv az monitor diagnostic-settings list \ --resource-group \ --resource-type components \ --resource-name az role assignment list \ --scope /subscriptions//resourceGroups//providers/Microsoft.Insights/components/ ``` -------------------------------- ### Time-Based Sampling for High-Volume Applications Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md Configures a sampling percentage for logging requests. This reduces data ingestion and associated costs by only logging a fraction (e.g., 50%) of high-volume application requests. ```hcl variable "sampling_percentage" { default = 50 # Log 50% of requests to reduce costs } ``` -------------------------------- ### Terraform Plan for azurerm_management_lock Migration Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md After updating the module to a version that uses 'azapi_resource.lock', run 'terraform plan' to observe the planned migration of the lock resource in the state. This step verifies the automatic migration before applying. ```bash # Ensure you have the latest module version in your configuration # In your module block: module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" # Use latest # ... rest of configuration } # Run plan to see migration terraform plan # Output will show: # azurerm_management_lock.this has moved to azapi_resource.lock[0] ``` -------------------------------- ### Production Application Insights with Diagnostic Settings Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/usage-examples.md This configuration is suitable for production workloads, enabling comprehensive logging through diagnostic settings. It includes application configuration, security settings, and resource management tags. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = azurerm_resource_group.this.location name = "appinsights-prod" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id # Application configuration application_type = "web" retention_in_days = 90 sampling_percentage = 100 daily_data_cap_in_gb = 100 # Security disable_ip_masking = false internet_ingestion_enabled = true internet_query_enabled = true local_authentication_disabled = false # Diagnostic settings for centralized logging diagnostic_settings = { to_analytics = { name = "diag-appinsights-prod" workspace_resource_id = azurerm_log_analytics_workspace.diagnostics.id logs = [ { category = "AppRequests" enabled = true }, { category = "AppExceptions" enabled = true }, { category = "AppTraces" enabled = true }, { category = "AppMetrics" enabled = true } ] metrics = [ { category = "AllMetrics" enabled = true } ] } } # Resource management enable_telemetry = true tags = { environment = "production" application = "myapp" team = "platform" cost_center = "engineering" } } ``` -------------------------------- ### Export Application Insights Outputs Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/output-reference.md Demonstrates how to define outputs for Application Insights module, including instrumentation key, connection string, and resource ID. These outputs are useful for configuring SDKs and for referencing the resource in other modules. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" # ... configuration ... } output "app_insights_instrumentation_key" { description = "Application Insights instrumentation key for SDK configuration" value = module.app_insights.instrumentation_key sensitive = false } output "app_insights_connection_string" { description = "Application Insights connection string for SDK initialization" value = module.app_insights.connection_string sensitive = true } output "app_insights_resource_id" { description = "Azure resource ID of the Application Insights component" value = module.app_insights.resource_id sensitive = false } ``` -------------------------------- ### Migrate to Private Link with Cutover Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md This three-step process allows for zero-downtime migration to private link. It involves creating private link infrastructure, updating the module to accept both internet and private link, and finally disabling internet access. ```hcl # Step 1: Create private link infrastructure (before any changes) resource "azurerm_virtual_network" "this" { # ... configuration } resource "azurerm_subnet" "private_endpoints" { # ... configuration } resource "azurerm_monitor_private_link_scope" "this" { name = "ampls-myapp-new" resource_group_name = azurerm_resource_group.this.name } resource "azurerm_private_endpoint" "ampls" { name = "pe-ampls" location = azurerm_resource_group.this.location resource_group_name = azurerm_resource_group.this.name subnet_id = azurerm_subnet.private_endpoints.id private_service_connection { name = "psc-ampls" private_connection_resource_id = azurerm_monitor_private_link_scope.this.id subresource_names = ["azuremonitor"] is_manual_connection = false } } # Step 2: Update application insights to accept both internet and private link module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.3.0" location = "eastus" name = "myappinsights" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id # Keep internet access open initially internet_ingestion_enabled = true internet_query_enabled = true # Add private link monitor_private_link_scope = { ampls = { resource_id = azurerm_monitor_private_link_scope.this.id } } } # Step 3: After verifying private link is working, disable internet access module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.3.0" location = "eastus" name = "myappinsights" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id # Disable public internet after private link is active internet_ingestion_enabled = false internet_query_enabled = false monitor_private_link_scope = { ampls = { resource_id = azurerm_monitor_private_link_scope.this.id } } } ``` -------------------------------- ### Set Daily Data Ingestion Cap Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/input-variables.md Configures the daily limit for data ingestion in gigabytes. A value of 0 indicates unlimited ingestion. Helps control costs. ```hcl daily_data_cap_in_gb = 50 # Cap at 50 GB per day ``` -------------------------------- ### Terraform Provider State Gitignore Entries Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md Provides recommended entries for a .gitignore file to exclude Terraform provider state and lock files from version control, while including Terraform configuration files. ```bash # Gitignore entries .terraform/ .terraform.lock.hcl # Shared via version control # Safe to commit *.tf files ``` -------------------------------- ### Import Role Assignment into New Location Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md Check the current state for role assignments and then import them into a new location using this command to resolve migration conflicts. ```bash # Check current state terraform state list | grep role_assignment # Import into new location terraform import \ 'module.app_insights.azapi_resource.role_assignment["key"]' \ '/subscriptions/.../providers/Microsoft.Authorization/roleAssignments/...' ``` -------------------------------- ### Terraform Plan Command Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/INDEX.md Used to review changes before applying an upgrade. This command helps in understanding the impact of module version changes. ```bash terraform plan ``` -------------------------------- ### Comprehensive Diagnostic Settings for Application Insights Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md Configure this for detailed monitoring, troubleshooting, or high-value applications, including all available log categories. Be aware of the high data volume and cost implications. ```hcl diagnostic_settings = { comprehensive = { workspace_resource_id = azurerm_log_analytics_workspace.this.id logs = [ { category = "AppAvailabilityResults", enabled = true }, { category = "AppEvents", enabled = true }, { category = "AppExceptions", enabled = true }, { category = "AppMetrics", enabled = true }, { category = "AppPerformanceCounters", enabled = true }, { category = "AppRequests", enabled = true }, { category = "AppSystemEvents", enabled = true }, { category = "AppTraces", enabled = true }, { category = "AppBrowserTimings", enabled = true }, { category = "AppDependencies", enabled = true }, { category = "AppPageViews", enabled = true }, { category = "OTelResources", enabled = true } ] metrics = [ { category = "AllMetrics", enabled = true } ] } } ``` -------------------------------- ### Cost-Optimized Application Insights for Development Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/quick-reference.md Set up a cost-optimized Application Insights instance for development environments. This configuration includes specific data retention, sampling, and daily data cap settings to manage costs effectively while enabling telemetry. ```hcl module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = "eastus" name = "appinsights-dev" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id retention_in_days = 30 sampling_percentage = 25 daily_data_cap_in_gb = 10 enable_telemetry = true tags = { environment = "development" } } ``` -------------------------------- ### Selective Category Logging for Optimized Diagnostics Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/diagnostic-settings-guide.md Configures diagnostic settings to enable only critical log categories like 'AppExceptions' and 'AppRequests', and 'AllMetrics'. This reduces data volume and cost by logging only essential information. ```hcl diagnostic_settings = { optimized = { workspace_resource_id = azurerm_log_analytics_workspace.this.id logs = [ { category = "AppExceptions", enabled = true }, # Critical errors { category = "AppRequests", enabled = true } # Request latency ] metrics = [ { category = "AllMetrics", enabled = true } ] } } ``` -------------------------------- ### Verify azapi_resource.lock in Terraform State Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/migration-guide.md After applying the migration, use 'terraform state list' to confirm that the lock resource has been successfully moved to the 'azapi_resource.lock' identifier in your Terraform state. ```bash # Check state contains new resource terraform state list | grep azapi_resource.lock ``` -------------------------------- ### Terraform Resource for Creating Diagnostic Settings Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/resource-definitions.md Creates diagnostic settings for Application Insights using the azapi_resource. It iterates over the configured settings and applies them to the specified Application Insights instance. ```hcl # Creates diagnostic settings resource "azapi_resource" "diagnostic_settings" { for_each = module.avm_interfaces.diagnostic_settings_azapi_v2 name = each.value.name parent_id = azurerm_application_insights.this.id type = each.value.type body = each.value.body } ``` -------------------------------- ### Resolving Provider Version Constraint Mismatches Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/terraform-requirements.md If a provider version constraint mismatch occurs, you can resolve it by removing the lock file and re-initializing, or by specifying an exact version during initialization. ```bash # Update lock file rm .terraform.lock.hcl terraform init -upgrade # Or specify exact version terraform init -upgrade=azurerm ``` -------------------------------- ### Deploy Application Insights with Profiler Storage Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/_autodocs/usage-examples.md Configure Application Insights to use custom storage for profiler data. This requires creating a storage container and linking it to the Application Insights module. ```hcl resource "azurerm_storage_container" "profiler_data" { name = "appinsights-profiler" storage_account_name = azurerm_storage_account.profiler.name container_access_type = "private" } module "app_insights" { source = "Azure/avm-res-insights-component/azurerm" version = "0.x.x" location = azurerm_resource_group.this.location name = "appinsights-with-profiler" resource_group_name = azurerm_resource_group.this.name workspace_id = azurerm_log_analytics_workspace.this.id # Profiler configuration force_customer_storage_for_profiler = true linked_storage_account = { profiler = { resource_id = azurerm_storage_account.profiler.id } } application_type = "web" tags = { profiler_enabled = "true" } } ``` -------------------------------- ### Tags Configuration Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/README.md Applies tags to the Application Insights resource for organization and management. ```HCL map(string) ``` -------------------------------- ### Retry Configuration for azapi Resources Source: https://github.com/azure/terraform-azurerm-avm-res-insights-component/blob/main/README.md Sets up retry logic for azapi resource operations. Includes a list of regex patterns for error messages that trigger a retry, and optional intervals for retries. ```HCL object({ error_message_regex = optional(list(string), ["ScopeLocked"]) interval_seconds = optional(number, null) max_interval_seconds = optional(number, null) }) ```