Azure - Развертывание правил оповещения с помощью шаблона ARM с метрикой c Параметр измерения (не счетчик результатов) - PullRequest
0 голосов
/ 30 марта 2020

У меня есть небольшая проблема с развертыванием правильного правила оповещения в Azure.

Мои оповещения - это Log Analytics Query, и развертывание работает нормально. Но все мои оповещения были созданы с «Число результата», а я хочу «Метри c Измерение».

Тип оповещения

Alert type

Я пытался создать правильное оповещение в Azure и использовать JSON параметры в журналах активности, но я не понимаю, где находится этот параметр.

Я также ищу в https://docs.microsoft.com/en-us/rest/api/monitor/scheduledqueryrules/createorupdate#alertingaction но там только "ResultCount".

Знаешь ли ты, что является хорошим параметром для этого?

Мой шаблон. json

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "actionGroup": {
      "defaultValue": "",
      "metadata": {
        "description": "The ID of the action group that is triggered when the alert is activated or deactivated"
      },
      "type": "string"
    },
    "alertDescription": {
      "defaultValue": "This is a metric alert",
      "metadata": {
        "description": "Description of alert"
      },
      "type": "string"
    },
    "alertName": {
      "metadata": {
        "description": "Name of the alert"
      },
      "type": "string"
    },
    "alertSeverity": {
      "allowedValues": [
        0,
        1,
        2,
        3,
        4
      ],
      "defaultValue": 3,
      "metadata": {
        "description": "Severity of alert {0,1,2,3,4}"
      },
      "type": "int"
    },
    "consecutiveBreachTrigger": {
      "defaultValue": "",
      "metadata": {
        "description": ""
      },
      "type": "string"
    },
  //"isEnabled": {
  //    "defaultValue": true,
  //    "metadata": {
  //      "description": "Specifies whether the alert is enabled"
  //    },
  //    "type": "bool"
  //  },
    "metricColumn": {
      "defaultValue": "",
      "metadata": {
        "description": "Metric type of trigger"
      },
      "type": "string"
    },
    "metricTriggerTypeMetricTrigger": {
      "defaultValue": "",
      "metadata": {
        "description": "Metric type of trigger"
      },
      "type": "string"
    },
    "metricTriggerTypeTrigger": {
      "defaultValue": "",
      "metadata": {
        "description": "Metric type of trigger"
      },
      "type": "string"
    },
    "operatorMetricTrigger": {
      "allowedValues": [
        "Equals",
        "NotEquals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "defaultValue": "GreaterThan",
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      },
      "type": "string"
    },
    "operatorTrigger": {
      "allowedValues": [
        "Equals",
        "NotEquals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "defaultValue": "GreaterThan",
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      },
      "type": "string"
    },
    "PfrequencyInMin": {
      "defaultValue": "",
      "metadata": {
        "description": "Time along the query is running"
      },
      "type": "string"
    },
    "PtimeWindowFrequency": {
      "defaultValue": "",
      "metadata": {
        "description": "Frequency of often should be run the alert"
      },
      "type": "string"
    },
    "query": {
      "defaultValue": "",
      "metadata": {
        "description": "Query to use for this alert"
      },
      "type": "string"
    },
   "queryType": {
    "defaultValue": "",
     "metadata": {
        "description": "Type of the query"
    },
     "type": "string"
   },
    "region": {
      "defaultValue": "",
      "metadata": {
        "description": "Region of the workspace"
      },
      "type": "string"
    },
    "resourceId": {
      "metadata": {
        "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
      },
      "minLength": 1,
      "type": "string"
    },
    "thresholdMetricTrigger": {
      "defaultValue": "0",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      },
      "type": "string"
    },
    "thresholdTrigger": {
      "defaultValue": "0",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      },
      "type": "string"
    }
  },
  "resources": [
    {
      "apiVersion": "2018-04-16",
      "location": "[parameters('region')]",
      "name": "[parameters('alertName')]",
      "properties": {
        "action": {
          "aznAction": {
            "actionGroup": "[parameters('actionGroup')]"
          },
          "metricTrigger": {
            "metricColumn": "[parameters('metricColumn')]",
            "metricTriggerType": "[parameters('metricTriggerTypeMetricTrigger')]",
            "threshold": "[parameters('thresholdMetricTrigger')]",
            "thresholdOperator": "[parameters('operatorMetricTrigger')]"
          },
          "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
          "severity": "[parameters('alertSeverity')]",
          "trigger": {
            "consecutiveBreach": "[parameters('consecutiveBreachTrigger')]",
            "metricTriggerType": "[parameters('metricTriggerTypeTrigger')]",
            "threshold": "[parameters('thresholdTrigger')]",
            "thresholdOperator": "[parameters('operatorTrigger')]"
          }
        },
        "description": "[parameters('alertDescription')]",
        "displayname": "[parameters('alertName')]",
        "enabled": "true",
        "schedule": {
          "frequencyInMinutes": "[parameters('PfrequencyInMin')]",
          "timeWindowInMinutes": "[parameters('PtimeWindowFrequency')]"
        },
        "source": {
          "datasourceID": "[parameters('resourceId')]",
          "query": "[parameters('query')]",
          "queryType": "[parameters('queryType')]"
        }
      },
      "tags": {},
      "type": "microsoft.insights/scheduledqueryrules"
    }
  ],
  "variables": {}
}

Параметры. json

{
    "$schema":  "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
    "contentVersion":  "1.0.0.0",
  "parameters": {
    "actionGroup": {
      "value": "Production Server"
    },
    "alertDescription": {
      "value": "RAM used in percentage"
    },
    "alertName": {
      "value": "VM - Memory Usage (Metric)"
    },
    "alertSeverity": {
      "value": 3
    },
    "consecutiveBreachTrigger": {
      "value": "1"
    },
   // "isEnabled": {
   //   "value": true
   // },
    "metricColumn": {
      "value": "Computer"
    },
    "metricTriggerTypeMetricTrigger": {
      "value": "Consecutive"
    },
    "metricTriggerTypeTrigger": {
      "value": "Consecutive"
    },
    "operatorMetricTrigger": {
      "value": "GreaterThan"
    },
    "operatorTrigger": {
      "value": "GreaterThan"
    },
    "PfrequencyInMin": {
      "value": "30"
    },
    "PtimeWindowFrequency": {
      "value": "60"
    },
    "query": {
      "value": "InsightsMetrics | where Namespace == 'Memory' and Name == 'AvailableMB'  | extend Max=parsejson(tostring(Tags)) | mvexpand Max | extend memorySizeMB=todecimal(Max['vm.azm.ms/memorySizeMB']) | project TimeGenerated, Computer , Namespace, Val ,  Mem = round(memorySizeMB, 1)| extend Percentage = Val / Mem * 100 | summarize AggregatedValue = avg(Percentage) by Computer, bin(TimeGenerated, 30m)"
    },
    "queryType": {
      "value": "Metric"
    },
    "region": {
      "value": "westeurope"
    },
    "resourceId": {
      "value": "/subscriptions/efcfb0fe-d308-4c80-9615-57eddb9b2d2a/resourceGroups/Gizmo-hosted-logs/providers/Microsoft.OperationalInsights/workspaces/Gizmo-hosted-logs"
    },
    "thresholdMetricTrigger": {
      "value": "1"
    },
    "thresholdTrigger": {
      "value": "80"
    }
  }
}

Заранее благодарим.

С уважением,

Aurélien

1 Ответ

0 голосов
/ 31 марта 2020

Если вы хотите создать оповещение об исследовании журнала, измените тип запроса на ResultCount, и нам также нужно указать триггер, например

"trigger": {
        "thresholdOperator": "<>",
        "threshold": 0,
        "metricTrigger": {
          "thresholdOperator": "<>",
          "threshold": 1,
          "metricTriggerType": "Consecutive",
          "metricColumn": "<your colum>"
        }

Например

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
    },
    "variables": {
        "alertLocation": "Region Name for your Application Insights App or Log Analytics Workspace",
        "alertName": "test",
        "alertDescr": "test",
        "alertStatus": "true",
        "alertSource":{
            "Query":"Perf\r\n| where CounterName == \"Free Megabytes\" and InstanceName == \"D:\"\r\n| where TimeGenerated > ago(7d)\r\n| where Computer == \"win2012\"\r\n| summarize AggregatedValue = min(CounterValue) by bin(TimeGenerated, 5m)\n",

            "SourceId": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.OperationalInsights/workspaces/servicews",
            "Type":"ResultCount"
        },
        "alertSchedule":{
            "Frequency": 5,
            "Time": 5
        },
        "alertActions":{
            "SeverityLevel": "3",
            "SuppressTimeinMin": 20
        },
        "alertTrigger":{
            "Operator":"GreaterThan",
            "Threshold":"1"
        },
        "metricMeasurement": {
            "thresholdOperator": "GreaterThan",
          "threshold": 1,
          "metricTriggerType": "Consecutive",
          "metricColumn": "TimeGenerated"
        },
        "actionGrp":{
            "ActionGroup": "/subscriptions/a123d7efg-123c-1234-5678-a12bc3defgh4/resourceGroups/contosoRG/providers/microsoft.insights/actiongroups/sampleAG"

        }
    },
    "resources":[ {
        "name":"[variables('alertName')]",
        "type":"Microsoft.Insights/scheduledQueryRules",
        "apiVersion": "2018-04-16",
        "location": "[variables('alertLocation')]",
        "properties":{
            "description": "[variables('alertDescr')]",
            "enabled": "[variables('alertStatus')]",
            "source": {
                "query": "[variables('alertSource').Query]",
                "authorizedResources": "[concat(array(variables('alertSource').Resource1), array(variables('alertSource').Resource2))]",
                "dataSourceId": "[variables('alertSource').SourceId]",
                "queryType":"[variables('alertSource').Type]"
            },
            "schedule":{
                "frequencyInMinutes": "[variables('alertSchedule').Frequency]",
                "timeWindowInMinutes": "[variables('alertSchedule').Time]"
            },
            "action":{
                "odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
                "severity":"[variables('alertActions').SeverityLevel]",
                "throttlingInMin": "[variables('alertActions').SuppressTimeinMin]",
                "aznsAction":{
                    "actionGroup": "[array(variables('actionGrp').ActionGroup)]"
                },
                "trigger":{
                    "thresholdOperator":"[variables('alertTrigger').Operator]",
                    "threshold":"[variables('alertTrigger').Threshold]",
                    "metricTrigger":{
                        "thresholdOperator": "[variables('metricMeasurement').thresholdOperator]",
                        "threshold": "[variables('metricMeasurement').threshold]",
                        "metricColumn": "[variables('metricMeasurement').metricColumn]",
                        "metricTriggerType": "[variables('metricMeasurement').metricTriggerType]"
                    }
                }
            }
        }
    } ]
}

Результат enter image description here

Для получения более подробной информации, пожалуйста, обратитесь к

https://docs.microsoft.com/en-us/rest/api/monitor/scheduledqueryrules/createorupdate

https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-log#managing -log-сигналы-using- azure -resource-шаблон

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...