如何在 terraform 中为 SQL 数据库创建警报规则

How to create alert rule in terraform for SQL DB

我似乎找不到任何示例,而且我 运行 根据我正在做的事情陷入不同的错误。

我正在努力让它发挥作用,但它就是没有发生......有什么想法吗?

resource "azurerm_monitor_metric_alert" "example" {
  name                = "example-metricalert"
  resource_group_name = azurerm_resource_group.example.name
  scopes              = [azurerm_mssql_database.test.server_id]
  description         = "Action will be triggered when cpu is greater than 80%."

  criteria {
    metric_namespace = "Microsoft.Sql/servers/databases"
    metric_name      = "CPU_percentage"
    aggregation      = "Average"
    operator         = "GreaterThan"
    threshold        = 80
}

}

您可以使用以下代码为 SQL 数据库创建指标警报。我已经针对现有的 SQL 数据库对其进行了测试,因此使用了数据块。

Main.tf

   provider "azurerm" {
  features {}
}


data "azurerm_mssql_server" "example" {
  name                = "ztestansumanserver"
  resource_group_name = "yourresourcegroup"
}

data "azurerm_mssql_database" "dbtomonitor" {
  name      = "testansumandb"
  server_id = data.azurerm_mssql_server.example.id
}

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

  email_receiver {
    name                    = "sendtoadmin"
    email_address           = "youremailid"
    use_common_alert_schema = true
  }
}

resource "azurerm_monitor_metric_alert" "example" {
  name                = "example-metricalert"
  resource_group_name = data.azurerm_mssql_server.example.resource_group_name
  scopes              = [data.azurerm_mssql_database.dbtomonitor.id]
  description         = "Action will be triggered when cpu percent is greater than 80."

  criteria {
    metric_namespace = "Microsoft.Sql/servers/databases"
    metric_name      = "cpu_percent"
    aggregation      = "Average"
    operator         = "GreaterThan"
    threshold        = 80
  }
 action {
    action_group_id = azurerm_monitor_action_group.example.id
  }
}

输出:

注意: 按照上面的脚本警报创建成功,它也会在 cpu_percent > 80 时触发邮件给您。

参考:

Azure Monitor supported metrics by resource type - Azure Monitor | Microsoft Docs