You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform azurerm_monitor_scheduled_query_rules_alert_v2无法运行Azure资源图查询

问题:Terraform使用azurerm_monitor_scheduled_query_rules_alert_v2创建Azure Resource Graph查询告警规则失败

尝试通过Terraform的azurerm provider创建监控Azure Update Manager补丁评估失败的告警规则,对应的resource配置如下:

resource "azurerm_monitor_scheduled_query_rules_alert_v2" "patch_assessment_failure" {
  name                 = "Patch-Assessment-Failure"
  description          = "Alert when the patch assessment operation for a specific VM is failed."
  resource_group_name  = "ospm-rg"
  location             = "northeurope"
  evaluation_frequency = "P1D"
  window_duration      = "P1D"
  scopes               = ["/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/ospm-rg/providers/microsoft.operationalinsights/workspaces/ospm-la"]
  severity             = 1

  criteria {
    query = <<-QUERY
      arg('').patchassessmentresources
      | where type in~ ("microsoft.compute/virtualmachines/patchassessmentresults", "microsoft.hybridcompute/machines/patchassessmentresults")
      | where properties.status =~ "Failed"
      | where properties.lastModifiedDateTime > ago(1d)
      | project vmResourceId
    QUERY

    time_aggregation_method = "Count"
    threshold               = 0
    operator                = "GreaterThan"

    dimension {
      name     = "vmResourceId"
      operator = "Include"
      values   = ["*"]
    }

    failing_periods {
      minimum_failing_periods_to_trigger_alert = 1
      number_of_evaluation_periods             = 1
    }
  }

  auto_mitigation_enabled = false
  enabled                 = true
  skip_query_validation   = true

  action {
    action_groups = ["/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/ospm-rg/providers/microsoft.insights/actiongroups/ospm-ag"]
  }
}

执行terraform apply时创建失败,报错信息:

Error: creating Scheduled Query Rule (Subscription: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
│ Resource Group Name: "ospm-rg"
│ Scheduled Query Rule Name: "Assessment-Failure"): unexpected status 400 with error: DraftClientException: The request had some invalid properties Activity ID: 174a8ae7-808c-4ceb-af13-fce8fdef28fe.

经排查发现:azurerm_monitor_scheduled_query_rules_alert_v2本质是针对Log Analytics/Application Insights的日志查询告警,不支持直接执行Azure Resource Graph查询——移除查询中的arg('').部分后,Terraform能成功创建资源,但生成的告警规则查询会失效,因为目标表patchassessmentresources并非存在于Log Analytics工作区,而是来自Azure Resource Graph。

需要解决的问题:如何在azurerm_monitor_scheduled_query_rules_alert_v2资源块中正确实现Azure Resource Graph查询的告警逻辑,或有什么替代方案?


解决办法

方案1:改用Azure Resource Graph计划查询+逻辑应用触发告警

由于azurerm_monitor_scheduled_query_rules_alert_v2不支持Resource Graph查询,可拆分逻辑实现需求:

  1. 创建Resource Graph查询:用azurerm_resource_graph_query定义目标查询,再通过Azure Portal/CLI配置查询计划(Terraform暂不支持直接配置Resource Graph查询的计划)。
  2. 触发告警动作:用逻辑应用监听计划查询的执行结果,当检测到失败的补丁评估记录时,调用动作组发送告警通知。

示例Terraform代码创建Resource Graph查询:

resource "azurerm_resource_graph_query" "patch_assessment_failure" {
  name                = "Patch-Assessment-Failure"
  resource_group_name = "ospm-rg"
  query               = <<-QUERY
    patchassessmentresources
    | where type in~ ("microsoft.compute/virtualmachines/patchassessmentresults", "microsoft.hybridcompute/machines/patchassessmentresults")
    | where properties.status =~ "Failed"
    | where properties.lastModifiedDateTime > ago(1d)
    | project vmResourceId
  QUERY
  description         = "Query to identify failed patch assessment operations"
}

方案2:将Resource Graph数据同步到Log Analytics工作区

如果业务允许,可通过自动化账户定期拉取Resource Graph数据并写入Log Analytics自定义表,再基于该表创建标准告警规则:

  1. 创建自动化账户运行册,执行Resource Graph查询并将结果推送到Log Analytics工作区的自定义表。
  2. 修改Terraform告警规则的查询语句,指向该自定义表。

方案3:通过REST API直接创建Resource Graph类型的告警规则

如果必须用Terraform实现,可通过azurerm_rest_api_deployment调用Azure Monitor REST API,创建支持Resource Graph查询的告警规则(这类规则属于"Resource Graph查询类型"的计划查询规则,而非Log Analytics类型)。

示例Terraform代码(简化版):

resource "azurerm_rest_api_deployment" "patch_assessment_alert" {
  name                = "Patch-Assessment-Failure-API"
  resource_group_name = "ospm-rg"
  location            = "northeurope"
  content_uri         = "https://management.azure.com/subscriptions/${var.subscription_id}/resourceGroups/${azurerm_resource_group.rg.name}/providers/Microsoft.Insights/scheduledQueryRules/Patch-Assessment-Failure?api-version=2022-06-01"
  http_method         = "PUT"
  content {
    properties = {
      displayName = "Patch-Assessment-Failure"
      description = "Alert when the patch assessment operation for a specific VM is failed."
      enabled = true
      schedule = {
        frequencyInMinutes = 1440
        timeWindowInMinutes = 1440
      }
      criteria = {
        allOf = [
          {
            query = <<-QUERY
              patchassessmentresources
              | where type in~ ("microsoft.compute/virtualmachines/patchassessmentresults", "microsoft.hybridcompute/machines/patchassessmentresults")
              | where properties.status =~ "Failed"
              | where properties.lastModifiedDateTime > ago(1d)
              | project vmResourceId
            QUERY
            queryType = "ResourceGraphQuery"
            timeAggregation = "Count"
            operator = "GreaterThan"
            threshold = 0
            dimensions = [
              {
                name = "vmResourceId"
                operator = "Include"
                values = ["*"]
              }
            ]
            failingPeriods = {
              minimumFailingPeriodsToTriggerAlert = 1
              numberOfEvaluationPeriods = 1
            }
          }
        ]
      }
      actions = {
        actionGroups = ["/subscriptions/${var.subscription_id}/resourceGroups/ospm-rg/providers/microsoft.insights/actiongroups/ospm-ag"]
      }
    }
  }
}

注意:使用该方式需确保Terraform服务主体拥有足够权限,且严格遵循API请求格式。


内容的提问来源于stack exchange,提问作者altruistcoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 11:18:21