2

I have prepared Terraform scripts for azure resources like App Service, AppService Plan, Storage Account and Logic App etc.….

I have deployed the above Terraform scripts successfully. But I want to configure the alerts for the above resources using Terraform.

Is there any way to create alerts by using Terraform without ARM Template deployment?

Pradeep
  • 5,101
  • 14
  • 68
  • 140

1 Answers1

4

Sure there is. This is an example of a custom log search from Application Insights. But you can easily modify this for another source like Azure Monitor

resource "azurerm_application_insights" "example" {
  name                = "${var.prefix}-appinsights"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  application_type    = "web"
  retention_in_days   = 30
}

resource "azurerm_monitor_action_group" "example" {
  name                = "CriticalAlertsAction"
  resource_group_name = azurerm_resource_group.example.name
  short_name          = "p0action"

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

resource "azurerm_monitor_scheduled_query_rules_alert" "example-alert1" {
  name                = "${var.prefix}-alertrule1"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name

  action {
    action_group = [
      azurerm_monitor_action_group.example.id
    ]
  }
  data_source_id = azurerm_application_insights.example.id
  description    = "Exception threshold reached"
  enabled        = true
  # Count all requests with server error result code grouped into 5-minute bins
  query       = <<-QUERY
  requests
    | where cloud_RoleName == "frontend" and name !contains "Health" and resultCode startswith "5" 
  QUERY
  severity    = 1
  frequency   = 5
  time_window = 5
  trigger {
    operator  = "GreaterThan"
    threshold = 10
  }
}
silent
  • 14,494
  • 4
  • 46
  • 86
  • 1
    I don't have such examples. And SO is not for us to do all the work for you ;) This sample should be enough to get you going to figure out the rest on your own. Maybe start by creating such alerts manually through the portal and extract the required items such as the query from there into Terraform – silent Dec 22 '20 at 15:48
  • Reference: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/monitor_scheduled_query_rules_alert_v2 and https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/monitor_scheduled_query_rules_alert – Simao Gomes Viana Jun 12 '23 at 09:56