Примеры шаблонов Resource Manager для правил генерации оповещений метрик в Azure Monitor

В этой статье приведены примеры использования шаблонов Azure Resource Manager для настройки правил генерации оповещений метрик в Azure Monitor. Каждый пример включает файл шаблона и файл параметров с примерами значений для предоставления шаблона.

Примечание.

Примеры Azure Resource Manager для Azure Monitor см. в списке доступных примеров и рекомендаций по развертыванию их в подписке Azure.

Список ресурсов, которые можно использовать с правилами генерации оповещений метрик, см. в разделе Поддерживаемые ресурсы для оповещений метрик в Azure Monitor. Описание схемы и свойств правила генерации оповещений см. в статье Оповещения метрик: создание или обновление.

Примечание.

Шаблон ресурса для создания оповещений метрик для типа ресурса: рабочая область Azure Log Analytics (т.е.) Microsoft.OperationalInsights/workspacesтребует дополнительных действий. Дополнительные сведения см. в статье: Оповещения метрик для журналов: шаблон ресурса.

Ссылки на шаблоны

Один критерий, статический порог

В следующем примере создается правило генерации оповещений метрик с использованием одного критерия и статического порога.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@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)
param resourceId string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'Equals'
  'GreaterThan'
  'GreaterThanOrEqual'
  'LessThan'
  'LessThanOrEqual'
])
param operator string = 'GreaterThan'

@description('The threshold value at which the alert is activated.')
param threshold int = 0

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria'
      allOf: [
        {
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          criterionType: 'StaticThresholdCriterion'
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "New Metric Alert"
    },
    "alertDescription": {
      "value": "New metric alert created via template"
    },
    "alertSeverity": {
      "value":3
    },
    "isEnabled": {
      "value": true
    },
    "resourceId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourceGroup-name/providers/Microsoft.Compute/virtualMachines/replace-with-resource-name"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterThan"
    },
    "threshold": {
      "value": "80"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group"
    }
  }
}

Один критерий, динамический порог

В следующем примере создается правило генерации оповещений метрик с использованием одного критерия и динамического порога.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@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)
param resourceId string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'GreaterThan'
  'LessThan'
  'GreaterOrLessThan'
])
param operator string = 'GreaterOrLessThan'

@description('Tunes how \'noisy\' the Dynamic Thresholds alerts will be: \'High\' will result in more alerts while \'Low\' will result in fewer alerts.')
@allowed([
  'High'
  'Medium'
  'Low'
])
param alertSensitivity string = 'Medium'

@description('The number of periods to check in the alert evaluation.')
param numberOfEvaluationPeriods int = 4

@description('The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods).')
param minFailingPeriodsToAlert int = 3

@description('Use this option to set the date from which to start learning the metric historical data and calculate the dynamic thresholds (in ISO8601 format, e.g. \'2019-12-31T22:00:00Z\').')
param ignoreDataBefore string = ''

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one hour. ISO 8601 duration format.')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT5M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          criterionType: 'DynamicThresholdCriterion'
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          alertSensitivity: alertSensitivity
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
          ignoreDataBefore: ignoreDataBefore
          timeAggregation: timeAggregation
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "New Metric Alert with Dynamic Thresholds"
    },
    "alertDescription": {
      "value": "New metric alert with Dynamic Thresholds created via template"
    },
    "alertSeverity": {
      "value":3
    },
    "isEnabled": {
      "value": true
    },
    "resourceId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourceGroup-name/providers/Microsoft.Compute/virtualMachines/replace-with-resource-name"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterOrLessThan"
    },
    "alertSensitivity": {
      "value": "Medium"
    },
    "numberOfEvaluationPeriods": {
      "value": "4"
    },
    "minFailingPeriodsToAlert": {
      "value": "3"
    },
    "ignoreDataBefore": {
      "value": ""
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group"
    }
  }
}

Несколько критериев, статический порог

Оповещения метрик поддерживают создание оповещений для многомерных метрик и до 5 критериев для каждого правила генерации оповещений. В следующем примере создается правило генерации оповещений метрик для метрик измерений и задается несколько критериев.

При использовании измерений в правиле генерации оповещений, которое содержит несколько критериев, действуют следующие ограничения:

  • В каждом из критериев можно выбрать только одно значение для каждого измерения.

  • Невозможно использовать "*" в качестве значения измерения.

  • Если метрики, настроенные в разных критериях, поддерживают одно и то же измерение, то настроенное значение измерения должно быть явно задано одинаковым способом для всех этих метрик в соответствующем критерии.

    • В приведенном ниже примере, поскольку в метриках Transactions и SuccessE2ELatency есть измерение ApiName, а параметр criterion1 определяет значение "GetBlob" для измерения ApiName, то для параметра criterion2 также нужно задать значение "GetBlob" для измерения ApiName.

Файл шаблона

@description('Name of the alert')
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Resource ID of the resource emitting the metric that will be used for the comparison.')
param resourceId string = ''

@description('Criterion includes metric name, dimension values, threshold and an operator. The alert rule fires when ALL criteria are met')
param criterion1 object

@description('Criterion includes metric name, dimension values, threshold and an operator. The alert rule fires when ALL criteria are met')
param criterion2 object

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

var criterion1_var = array(criterion1)
var criterion2_var = array(criterion2)
var criteria = concat(criterion1_var, criterion2_var)

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria'
      allOf: criteria
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "New Multi-dimensional Metric Alert (Replace with your alert name)"
    },
    "alertDescription": {
      "value": "New multi-dimensional metric alert created via template (Replace with your alert description)"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "resourceId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourcegroup-name/providers/Microsoft.Storage/storageAccounts/replace-with-storage-account"
    },
    "criterion1": {
      "value": {
        "name": "1st criterion",
        "metricName": "Transactions",
        "dimensions": [
          {
            "name": "ResponseType",
            "operator": "Include",
            "values": [ "Success" ]
          },
          {
            "name": "ApiName",
            "operator": "Include",
            "values": [ "GetBlob" ]
          }
        ],
        "operator": "GreaterThan",
        "threshold": "5",
        "timeAggregation": "Total"
      }
    },
    "criterion2": {
      "value": {
        "name": "2nd criterion",
        "metricName": "SuccessE2ELatency",
        "dimensions": [
          {
            "name": "ApiName",
            "operator": "Include",
            "values": [ "GetBlob" ]
          }
        ],
        "operator": "GreaterThan",
        "threshold": "250",
        "timeAggregation": "Average"
      }
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-actiongroup-name"
    }
  }
}

Несколько измерений, статический порог

Одно правило генерации оповещений может отслеживать несколько временных рядов за один раз, что позволяет сократить количество правил генерации оповещений. В следующем примере создается статическое правило генерации оповещений метрики для метрик измерений.

В этом примере правило генерации оповещений отслеживает сочетания значений измерений ResponseType и ApiName для метрики Transactions:

  1. ResponsType — использование подстановочного знака "*" означает, что для каждого значения измерения ResponseType, включая будущие значения, каждый временной ряд отслеживается отдельно.
  2. ApiName — другой временный ряд, который отслеживается только для значений измерений GetBlob и PutBlob.

Например, вот несколько возможных временных рядов, которые отслеживаются этим правилом генерации оповещений:

  • Metric = Transactions, ResponseType = Success, ApiName = GetBlob
  • Metric = Transactions, ResponseType = Success, ApiName = PutBlob
  • Metric = Transactions, ResponseType = Server Timeout, ApiName = GetBlob
  • Metric = Transactions, ResponseType = Server Timeout, ApiName = PutBlob

Файл шаблона

@description('Name of the alert')
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Resource ID of the resource emitting the metric that will be used for the comparison.')
param resourceId string = ''

@description('Criterion includes metric name, dimension values, threshold and an operator. The alert rule fires when ALL criteria are met')
param criterion object

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

var criteria = array(criterion)

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria'
      allOf: criteria
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "New multi-dimensional metric alert rule (replace with your alert name)"
    },
    "alertDescription": {
      "value": "New multi-dimensional metric alert rule created via template (replace with your alert description)"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "resourceId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourcegroup-name/providers/Microsoft.Storage/storageAccounts/replace-with-storage-account"
    },
    "criterion": {
      "value": {
        "name": "Criterion",
        "metricName": "Transactions",
        "dimensions": [
          {
            "name": "ResponseType",
            "operator": "Include",
            "values": [ "*" ]
          },
          {
            "name": "ApiName",
            "operator": "Include",
            "values": [ "GetBlob", "PutBlob" ]
          }
        ],
        "operator": "GreaterThan",
        "threshold": "5",
        "timeAggregation": "Total"
      }
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-actiongroup-name"
    }
  }
}

Примечание.

"Все" в качестве значения измерения эквивалентно выбору "Все текущие и будущие значения".

Несколько измерений, динамические пороги

Отдельное правило генерации оповещений с динамическими порогами может создать точно настроенные пороги для нескольких сотен временных рядов метрик (различных типов) одновременно, что приведет к управлению небольшим числом правил генерации оповещений. В следующем примере создается правило генерации оповещений метрик с динамическими порогами для метрик измерений.

В этом примере правило генерации оповещений отслеживает сочетания значений измерений ResponseType и ApiName для метрики Transactions:

  1. ResponsType — для каждого значения измерения ResponseType, включая будущие значения, каждый временный ряд отслеживается отдельно.
  2. ApiName — другой временный ряд, который отслеживается только для значений измерений GetBlob и PutBlob.

Например, вот несколько возможных временных рядов, которые отслеживаются этим правилом генерации оповещений:

  • Metric = Transactions, ResponseType = Success, ApiName = GetBlob
  • Metric = Transactions, ResponseType = Success, ApiName = PutBlob
  • Metric = Transactions, ResponseType = Server Timeout, ApiName = GetBlob
  • Metric = Transactions, ResponseType = Server Timeout, ApiName = PutBlob

Примечание.

В настоящее время несколько критериев для правил генерации оповещений метрик, использующих динамические пороги, не поддерживаются.

Файл шаблона

@description('Name of the alert')
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Resource ID of the resource emitting the metric that will be used for the comparison.')
param resourceId string = ''

@description('Criterion includes metric name, dimension values, threshold and an operator.')
param criterion object

@description('Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one hour. ISO 8601 duration format.')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT5M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

var criteria = array(criterion)

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: criteria
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "New Multi-dimensional Metric Alert with Dynamic Thresholds (Replace with your alert name)"
    },
    "alertDescription": {
      "value": "New multi-dimensional metric alert with Dynamic Thresholds created via template (Replace with your alert description)"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "resourceId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourcegroup-name/providers/Microsoft.Storage/storageAccounts/replace-with-storage-account"
    },
    "criterion": {
      "value": {
        "criterionType": "DynamicThresholdCriterion",
        "name": "1st criterion",
        "metricName": "Transactions",
        "dimensions": [
          {
            "name": "ResponseType",
            "operator": "Include",
            "values": [ "*" ]
          },
          {
            "name": "ApiName",
            "operator": "Include",
            "values": [ "GetBlob", "PutBlob" ]
          }
        ],
        "operator": "GreaterOrLessThan",
        "alertSensitivity": "Medium",
        "failingPeriods": {
          "numberOfEvaluationPeriods": "4",
          "minFailingPeriodsToAlert": "3"
        },
        "timeAggregation": "Total"
      }
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-actiongroup-name"
    }
  }
}

Пользовательская метрика, статический порог

Приведенный ниже шаблон можно использовать для создания более сложного правила генерации оповещений метрики со статическим порогом для своей метрики.

Дополнительные сведения о пользовательских метриках в Azure Monitor см. в разделе Пользовательские метрики в Azure Monitor.

При создании правила генерации оповещений для пользовательской метрики необходимо указать как имя метрики, так и пространство имен метрик. Также следует убедиться, что эта пользовательская метрика уже передает данные, так как невозможно создать правило генерации оповещений для пользовательской метрики, которая еще не существует.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@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)
param resourceId string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Namespace of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricNamespace string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'Equals'
  'GreaterThan'
  'GreaterThanOrEqual'
  'LessThan'
  'LessThanOrEqual'
])
param operator string = 'GreaterThan'

@description('The threshold value at which the alert is activated.')
param threshold int = 0

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('How often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria'
      allOf: [
        {
          name: '1st criterion'
          metricName: metricName
          metricNamespace: metricNamespace
          dimensions: []
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          criterionType: 'StaticThresholdCriterion'
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "New alert rule on a custom metric"
    },
    "alertDescription": {
      "value": "New alert rule on a custom metric created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "resourceId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourceGroup-name/providers/microsoft.insights/components/replace-with-application-insights-resource-name"
    },
    "metricName": {
      "value": "The custom metric name"
    },
    "metricNamespace": {
      "value": "Azure.ApplicationInsights"
    },
    "operator": {
      "value": "GreaterThan"
    },
    "threshold": {
      "value": "80"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group"
    }
  }
}

Примечание.

Пространство имен метрик определенной пользовательской метрики можно найти, просмотрев пользовательские метрики на портале Azure

Несколько ресурсов

Azure Monitor поддерживает мониторинг нескольких ресурсов одного типа с одним правилом генерации оповещений метрик для ресурсов, которые существуют в одном регионе Azure. В настоящее время эта функция поддерживается только в общедоступном облаке Azure и только для виртуальных машин, баз данных SQL Server, эластичных пулов SQL Server и пограничных устройств Azure Stack Edge. Кроме того, эта функция доступна только для метрик платформы и не поддерживается для пользовательских метрик.

Правило генерации оповещений с динамическим пороговым значением также может помочь в создании точно настроенных порогов для нескольких сотен метрик (различных типов) одновременно, что приведет к управлению небольшим числом правил генерации оповещений.

В этом разделе описываются шаблоны Azure Resource Manager для трех сценариев мониторинга нескольких ресурсов с помощью одного правила.

  • Мониторинг всех виртуальных машин (в одном регионе Azure) в одной или нескольких группах ресурсов.
  • Мониторинг всех виртуальных машин (в одном регионе Azure) в одной подписке.
  • Мониторинг списка виртуальных машин (в одном регионе Azure) в одной подписке.

Примечание.

  • В правиле оповещения метрики, отслеживающем несколько ресурсов, допускается только одно условие.
  • Если вы создаете оповещение метрик для одного ресурса, шаблон использует ResourceId целевой ресурс. Если вы создаете оповещение метрик для нескольких ресурсов, шаблон использует scopeTargetResourceTypeTargetResourceRegion и целевые ресурсы.

Оповещение со статическим пороговым значением на всех виртуальных машинах в одной или нескольких группах ресурсов

Этот шаблон позволяет создать правило генерации оповещений о метрике со статическим пороговым значением, которое отслеживает процент загрузки ЦП для всех виртуальных машин (в одном регионе Azure) в одной или нескольких группах ресурсов.

Для работы с этим пошаговым руководством сохраните приведенный ниже JSON в виде файла all-vms-in-resource-group-static.json.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Full path of the resource group(s) where target resources to be monitored are in. For example - /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName')
@minLength(1)
param targetResourceGroup array

@description('Azure region in which target resources to be monitored are in (without spaces). For example: EastUS')
@allowed([
  'EastUS'
  'EastUS2'
  'CentralUS'
  'NorthCentralUS'
  'SouthCentralUS'
  'WestCentralUS'
  'WestUS'
  'WestUS2'
  'CanadaEast'
  'CanadaCentral'
  'BrazilSouth'
  'NorthEurope'
  'WestEurope'
  'FranceCentral'
  'FranceSouth'
  'UKWest'
  'UKSouth'
  'GermanyCentral'
  'GermanyNortheast'
  'GermanyNorth'
  'GermanyWestCentral'
  'SwitzerlandNorth'
  'SwitzerlandWest'
  'NorwayEast'
  'NorwayWest'
  'SoutheastAsia'
  'EastAsia'
  'AustraliaEast'
  'AustraliaSoutheast'
  'AustraliaCentral'
  'AustraliaCentral2'
  'ChinaEast'
  'ChinaNorth'
  'ChinaEast2'
  'ChinaNorth2'
  'CentralIndia'
  'WestIndia'
  'SouthIndia'
  'JapanEast'
  'JapanWest'
  'KoreaCentral'
  'KoreaSouth'
  'SouthAfricaWest'
  'SouthAfricaNorth'
  'UAECentral'
  'UAENorth'
])
param targetResourceRegion string

@description('Resource type of target resources to be monitored.')
@minLength(1)
param targetResourceType string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'Equals'
  'GreaterThan'
  'GreaterThanOrEqual'
  'LessThan'
  'LessThanOrEqual'
])
param operator string = 'GreaterThan'

@description('The threshold value at which the alert is activated.')
param threshold string = '0'

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: targetResourceGroup
    targetResourceType: targetResourceType
    targetResourceRegion: targetResourceRegion
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          criterionType: 'StaticThresholdCriterion'
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "Multi-resource metric alert via Azure Resource Manager template"
    },
    "alertDescription": {
      "value": "New Multi-resource metric alert created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "targetResourceGroup": {
      "value": [
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name1",
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name2"
      ]
    },
    "targetResourceRegion": {
      "value": "SouthCentralUS"
    },
    "targetResourceType": {
      "value": "Microsoft.Compute/virtualMachines"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterThan"
    },
    "threshold": {
      "value": "0"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group-name"
    }
  }
}

Оповещение с динамическим пороговым значением на всех виртуальных машинах в одной или нескольких группах ресурсов

Этот пример позволяет создать правило генерации оповещений метрики с динамическим порогом, которое отслеживает процент загрузки ЦП для всех виртуальных машин в одном регионе Azure в одной или нескольких группах ресурсов.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Full path of the resource group(s) where target resources to be monitored are in. For example - /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName')
@minLength(1)
param targetResourceGroup array

@description('Azure region in which target resources to be monitored are in (without spaces). For example: EastUS')
@allowed([
  'EastUS'
  'EastUS2'
  'CentralUS'
  'NorthCentralUS'
  'SouthCentralUS'
  'WestCentralUS'
  'WestUS'
  'WestUS2'
  'CanadaEast'
  'CanadaCentral'
  'BrazilSouth'
  'NorthEurope'
  'WestEurope'
  'FranceCentral'
  'FranceSouth'
  'UKWest'
  'UKSouth'
  'GermanyCentral'
  'GermanyNortheast'
  'GermanyNorth'
  'GermanyWestCentral'
  'SwitzerlandNorth'
  'SwitzerlandWest'
  'NorwayEast'
  'NorwayWest'
  'SoutheastAsia'
  'EastAsia'
  'AustraliaEast'
  'AustraliaSoutheast'
  'AustraliaCentral'
  'AustraliaCentral2'
  'ChinaEast'
  'ChinaNorth'
  'ChinaEast2'
  'ChinaNorth2'
  'CentralIndia'
  'WestIndia'
  'SouthIndia'
  'JapanEast'
  'JapanWest'
  'KoreaCentral'
  'KoreaSouth'
  'SouthAfricaWest'
  'SouthAfricaNorth'
  'UAECentral'
  'UAENorth'
])
param targetResourceRegion string

@description('Resource type of target resources to be monitored.')
@minLength(1)
param targetResourceType string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'GreaterThan'
  'LessThan'
  'GreaterOrLessThan'
])
param operator string = 'GreaterOrLessThan'

@description('Tunes how \'noisy\' the Dynamic Thresholds alerts will be: \'High\' will result in more alerts while \'Low\' will result in fewer alerts.')
@allowed([
  'High'
  'Medium'
  'Low'
])
param alertSensitivity string = 'Medium'

@description('The number of periods to check in the alert evaluation.')
param numberOfEvaluationPeriods int = 4

@description('The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods).')
param minFailingPeriodsToAlert int = 3

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one hour. ISO 8601 duration format.')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT5M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: targetResourceGroup
    targetResourceType: targetResourceType
    targetResourceRegion: targetResourceRegion
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          criterionType: 'DynamicThresholdCriterion'
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          alertSensitivity: alertSensitivity
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
          timeAggregation: timeAggregation
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "Multi-resource metric alert with Dynamic Thresholds via Azure Resource Manager template"
    },
    "alertDescription": {
      "value": "New Multi-resource metric alert with Dynamic Thresholds created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "targetResourceGroup": {
      "value": [
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name1",
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name2"
      ]
    },
    "targetResourceRegion": {
      "value": "SouthCentralUS"
    },
    "targetResourceType": {
      "value": "Microsoft.Compute/virtualMachines"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterOrLessThan"
    },
    "alertSensitivity": {
      "value": "Medium"
    },
    "numberOfEvaluationPeriods": {
      "value": "4"
    },
    "minFailingPeriodsToAlert": {
      "value": "3"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group-name"
    }
  }
}

Оповещение со статическим пороговым значением на всех виртуальных машинах в подписке

Этот пример позволяет создать правило генерации оповещений метрики со статическим порогом, которое отслеживает процент загрузки ЦП для всех виртуальных машин в одном регионе Azure в подписке.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Azure Resource Manager path up to subscription ID. For example - /subscriptions/00000000-0000-0000-0000-0000-00000000')
@minLength(1)
param targetSubscription string

@description('Azure region in which target resources to be monitored are in (without spaces). For example: EastUS')
@allowed([
  'EastUS'
  'EastUS2'
  'CentralUS'
  'NorthCentralUS'
  'SouthCentralUS'
  'WestCentralUS'
  'WestUS'
  'WestUS2'
  'CanadaEast'
  'CanadaCentral'
  'BrazilSouth'
  'NorthEurope'
  'WestEurope'
  'FranceCentral'
  'FranceSouth'
  'UKWest'
  'UKSouth'
  'GermanyCentral'
  'GermanyNortheast'
  'GermanyNorth'
  'GermanyWestCentral'
  'SwitzerlandNorth'
  'SwitzerlandWest'
  'NorwayEast'
  'NorwayWest'
  'SoutheastAsia'
  'EastAsia'
  'AustraliaEast'
  'AustraliaSoutheast'
  'AustraliaCentral'
  'AustraliaCentral2'
  'ChinaEast'
  'ChinaNorth'
  'ChinaEast2'
  'ChinaNorth2'
  'CentralIndia'
  'WestIndia'
  'SouthIndia'
  'JapanEast'
  'JapanWest'
  'KoreaCentral'
  'KoreaSouth'
  'SouthAfricaWest'
  'SouthAfricaNorth'
  'UAECentral'
  'UAENorth'
])
param targetResourceRegion string

@description('Resource type of target resources to be monitored.')
@minLength(1)
param targetResourceType string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'Equals'
  'GreaterThan'
  'GreaterThanOrEqual'
  'LessThan'
  'LessThanOrEqual'
])
param operator string = 'GreaterThan'

@description('The threshold value at which the alert is activated.')
param threshold string = '0'

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      targetSubscription
    ]
    targetResourceType: targetResourceType
    targetResourceRegion: targetResourceRegion
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          criterionType: 'StaticThresholdCriterion'
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "Multi-resource sub level metric alert via Azure Resource Manager template"
    },
    "alertDescription": {
      "value": "New Multi-resource sub level metric alert created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "targetSubscription": {
      "value": "/subscriptions/replace-with-subscription-id"
    },
    "targetResourceRegion": {
      "value": "SouthCentralUS"
    },
    "targetResourceType": {
      "value": "Microsoft.Compute/virtualMachines"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterThan"
    },
    "threshold": {
      "value": "0"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group-name"
    }
  }
}

Оповещение с динамическим пороговым значением на всех виртуальных машинах в подписке

Этот пример позволяет создать правило генерации оповещений метрики с динамическим порогом, которое отслеживает процент загрузки ЦП для всех виртуальных машин (в одном регионе Azure) в подписке.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('Azure Resource Manager path up to subscription ID. For example - /subscriptions/00000000-0000-0000-0000-0000-00000000')
@minLength(1)
param targetSubscription string

@description('Azure region in which target resources to be monitored are in (without spaces). For example: EastUS')
@allowed([
  'EastUS'
  'EastUS2'
  'CentralUS'
  'NorthCentralUS'
  'SouthCentralUS'
  'WestCentralUS'
  'WestUS'
  'WestUS2'
  'CanadaEast'
  'CanadaCentral'
  'BrazilSouth'
  'NorthEurope'
  'WestEurope'
  'FranceCentral'
  'FranceSouth'
  'UKWest'
  'UKSouth'
  'GermanyCentral'
  'GermanyNortheast'
  'GermanyNorth'
  'GermanyWestCentral'
  'SwitzerlandNorth'
  'SwitzerlandWest'
  'NorwayEast'
  'NorwayWest'
  'SoutheastAsia'
  'EastAsia'
  'AustraliaEast'
  'AustraliaSoutheast'
  'AustraliaCentral'
  'AustraliaCentral2'
  'ChinaEast'
  'ChinaNorth'
  'ChinaEast2'
  'ChinaNorth2'
  'CentralIndia'
  'WestIndia'
  'SouthIndia'
  'JapanEast'
  'JapanWest'
  'KoreaCentral'
  'KoreaSouth'
  'SouthAfricaWest'
  'SouthAfricaNorth'
  'UAECentral'
  'UAENorth'
])
param targetResourceRegion string

@description('Resource type of target resources to be monitored.')
@minLength(1)
param targetResourceType string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'GreaterThan'
  'LessThan'
  'GreaterOrLessThan'
])
param operator string = 'GreaterOrLessThan'

@description('Tunes how \'noisy\' the Dynamic Thresholds alerts will be: \'High\' will result in more alerts while \'Low\' will result in fewer alerts.')
@allowed([
  'High'
  'Medium'
  'Low'
])
param alertSensitivity string = 'Medium'

@description('The number of periods to check in the alert evaluation.')
param numberOfEvaluationPeriods int = 4

@description('The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods).')
param minFailingPeriodsToAlert int = 3

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one hour. ISO 8601 duration format.')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT5M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      targetSubscription
    ]
    targetResourceType: targetResourceType
    targetResourceRegion: targetResourceRegion
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          criterionType: 'DynamicThresholdCriterion'
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          alertSensitivity: alertSensitivity
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
          timeAggregation: timeAggregation
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "Multi-resource sub level metric alert with Dynamic Thresholds via Azure Resource Manager template"
    },
    "alertDescription": {
      "value": "New Multi-resource sub level metric alert with Dynamic Thresholds created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "targetSubscription": {
      "value": "/subscriptions/replace-with-subscription-id"
    },
    "targetResourceRegion": {
      "value": "SouthCentralUS"
    },
    "targetResourceType": {
      "value": "Microsoft.Compute/virtualMachines"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterOrLessThan"
    },
    "alertSensitivity": {
      "value": "Medium"
    },
    "numberOfEvaluationPeriods": {
      "value": "4"
    },
    "minFailingPeriodsToAlert": {
      "value": "3"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group-name"
    }
  }
}

Оповещение со статическим пороговым значением для списка виртуальных машин

Этот пример позволяет создать правило генерации оповещений метрики со статическим порогом, которое отслеживает процент загрузки ЦП для списка виртуальных машин в одном регионе Azure в подписке.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('array of Azure resource Ids. For example - /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroup/resource-group-name/Microsoft.compute/virtualMachines/vm-name')
@minLength(1)
param targetResourceId array

@description('Azure region in which target resources to be monitored are in (without spaces). For example: EastUS')
@allowed([
  'EastUS'
  'EastUS2'
  'CentralUS'
  'NorthCentralUS'
  'SouthCentralUS'
  'WestCentralUS'
  'WestUS'
  'WestUS2'
  'CanadaEast'
  'CanadaCentral'
  'BrazilSouth'
  'NorthEurope'
  'WestEurope'
  'FranceCentral'
  'FranceSouth'
  'UKWest'
  'UKSouth'
  'GermanyCentral'
  'GermanyNortheast'
  'GermanyNorth'
  'GermanyWestCentral'
  'SwitzerlandNorth'
  'SwitzerlandWest'
  'NorwayEast'
  'NorwayWest'
  'SoutheastAsia'
  'EastAsia'
  'AustraliaEast'
  'AustraliaSoutheast'
  'AustraliaCentral'
  'AustraliaCentral2'
  'ChinaEast'
  'ChinaNorth'
  'ChinaEast2'
  'ChinaNorth2'
  'CentralIndia'
  'WestIndia'
  'SouthIndia'
  'JapanEast'
  'JapanWest'
  'KoreaCentral'
  'KoreaSouth'
  'SouthAfricaWest'
  'SouthAfricaNorth'
  'UAECentral'
  'UAENorth'
])
param targetResourceRegion string

@description('Resource type of target resources to be monitored.')
@minLength(1)
param targetResourceType string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'Equals'
  'GreaterThan'
  'GreaterThanOrEqual'
  'LessThan'
  'LessThanOrEqual'
])
param operator string = 'GreaterThan'

@description('The threshold value at which the alert is activated.')
param threshold string = '0'

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT1M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: targetResourceId
    targetResourceType: targetResourceType
    targetResourceRegion: targetResourceRegion
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          criterionType: 'StaticThresholdCriterion'
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "Multi-resource metric alert by list via Azure Resource Manager template"
    },
    "alertDescription": {
      "value": "New Multi-resource metric alert by list created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "targetResourceId": {
      "value": [
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name1/Microsoft.Compute/virtualMachines/replace-with-vm-name1",
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name2/Microsoft.Compute/virtualMachines/replace-with-vm-name2"
      ]
    },
    "targetResourceRegion": {
      "value": "SouthCentralUS"
    },
    "targetResourceType": {
      "value": "Microsoft.Compute/virtualMachines"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterThan"
    },
    "threshold": {
      "value": "0"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group-name"
    }
  }
}

Оповещение с динамическим пороговым значением для списка виртуальных машин

Этот пример позволяет создать правило генерации оповещений метрики с динамическим порогом, которое отслеживает процент загрузки ЦП для списка виртуальных машин в одном регионе Azure в подписке.

Файл шаблона

@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'This is a metric alert'

@description('Severity of alert {0,1,2,3,4}')
@allowed([
  0
  1
  2
  3
  4
])
param alertSeverity int = 3

@description('Specifies whether the alert is enabled')
param isEnabled bool = true

@description('array of Azure resource Ids. For example - /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroup/resource-group-name/Microsoft.compute/virtualMachines/vm-name')
@minLength(1)
param targetResourceId array

@description('Azure region in which target resources to be monitored are in (without spaces). For example: EastUS')
@allowed([
  'EastUS'
  'EastUS2'
  'CentralUS'
  'NorthCentralUS'
  'SouthCentralUS'
  'WestCentralUS'
  'WestUS'
  'WestUS2'
  'CanadaEast'
  'CanadaCentral'
  'BrazilSouth'
  'NorthEurope'
  'WestEurope'
  'FranceCentral'
  'FranceSouth'
  'UKWest'
  'UKSouth'
  'GermanyCentral'
  'GermanyNortheast'
  'GermanyNorth'
  'GermanyWestCentral'
  'SwitzerlandNorth'
  'SwitzerlandWest'
  'NorwayEast'
  'NorwayWest'
  'SoutheastAsia'
  'EastAsia'
  'AustraliaEast'
  'AustraliaSoutheast'
  'AustraliaCentral'
  'AustraliaCentral2'
  'ChinaEast'
  'ChinaNorth'
  'ChinaEast2'
  'ChinaNorth2'
  'CentralIndia'
  'WestIndia'
  'SouthIndia'
  'JapanEast'
  'JapanWest'
  'KoreaCentral'
  'KoreaSouth'
  'SouthAfricaWest'
  'SouthAfricaNorth'
  'UAECentral'
  'UAENorth'
])
param targetResourceRegion string

@description('Resource type of target resources to be monitored.')
@minLength(1)
param targetResourceType string

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param metricName string

@description('Operator comparing the current value with the threshold value.')
@allowed([
  'GreaterThan'
  'LessThan'
  'GreaterOrLessThan'
])
param operator string = 'GreaterOrLessThan'

@description('Tunes how \'noisy\' the Dynamic Thresholds alerts will be: \'High\' will result in more alerts while \'Low\' will result in fewer alerts.')
@allowed([
  'High'
  'Medium'
  'Low'
])
param alertSensitivity string = 'Medium'

@description('The number of periods to check in the alert evaluation.')
param numberOfEvaluationPeriods int = 4

@description('The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods).')
param minFailingPeriodsToAlert int = 3

@description('How the data that is collected should be combined over time.')
@allowed([
  'Average'
  'Minimum'
  'Maximum'
  'Total'
  'Count'
])
param timeAggregation string = 'Average'

@description('Period of time used to monitor alert activity based on the threshold. Must be between five minutes and one hour. ISO 8601 duration format.')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param windowSize string = 'PT5M'

@description('how often the metric alert is evaluated represented in ISO 8601 duration format')
@allowed([
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
])
param evaluationFrequency string = 'PT5M'

@description('The ID of the action group that is triggered when the alert is activated or deactivated')
param actionGroupId string = ''

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: alertName
  location: 'global'
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: targetResourceId
    targetResourceType: targetResourceType
    targetResourceRegion: targetResourceRegion
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria'
      allOf: [
        {
          criterionType: 'DynamicThresholdCriterion'
          name: '1st criterion'
          metricName: metricName
          dimensions: []
          operator: operator
          alertSensitivity: alertSensitivity
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
          timeAggregation: timeAggregation
        }
      ]
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "value": "Multi-resource metric alert with Dynamic Thresholds by list via Azure Resource Manager template"
    },
    "alertDescription": {
      "value": "New Multi-resource metric alert with Dynamic Thresholds by list created via template"
    },
    "alertSeverity": {
      "value": 3
    },
    "isEnabled": {
      "value": true
    },
    "targetResourceId": {
      "value": [
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name1/Microsoft.Compute/virtualMachines/replace-with-vm-name1",
        "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name2/Microsoft.Compute/virtualMachines/replace-with-vm-name2"
      ]
    },
    "targetResourceRegion": {
      "value": "SouthCentralUS"
    },
    "targetResourceType": {
      "value": "Microsoft.Compute/virtualMachines"
    },
    "metricName": {
      "value": "Percentage CPU"
    },
    "operator": {
      "value": "GreaterOrLessThan"
    },
    "alertSensitivity": {
      "value": "Medium"
    },
    "numberOfEvaluationPeriods": {
      "value": "4"
    },
    "minFailingPeriodsToAlert": {
      "value": "3"
    },
    "timeAggregation": {
      "value": "Average"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resource-group-name/providers/Microsoft.Insights/actionGroups/replace-with-action-group-name"
    }
  }
}

Тест доступности с помощью оповещения метрики

Тесты доступности Application Insights помогают отслеживать доступность веб-сайта или приложения из различных расположений по всему миру. Оповещения тестирования доступности уведомляют о том, что тесты доступности завершились ошибкой из определенного числа расположений. У оповещений тестирования доступности те же типы ресурсов, что и у оповещений метрик (Microsoft.Insights/metricAlerts). В следующем примере создается простой тест доступности и соответствующее оповещение.

Примечание.

& — это обозначение сущности HTML для &. Параметры URL-адреса все еще разделяются одним символом &, но если вы упомянули URL-адрес в формате HTML, его необходимо закодировать. Таким образом, если в значении параметра pingURL имеется символ "&", необходимо заменить его с помощью "&".

Файл шаблона

param appName string
param pingURL string
param pingText string = ''
param actionGroupId string
param location string

var pingTestName = 'PingTest-${toLower(appName)}'
var pingAlertRuleName = 'PingAlert-${toLower(appName)}-${subscription().subscriptionId}'

resource pingTest 'Microsoft.Insights/webtests@2020-10-05-preview' = {
  name: pingTestName
  location: location
  tags: {
    'hidden-link:${resourceId('Microsoft.Insights/components', appName)}': 'Resource'
  }
  properties: {
    Name: pingTestName
    Description: 'Basic ping test'
    Enabled: true
    Frequency: 300
    Timeout: 120
    Kind: 'ping'
    RetryEnabled: true
    Locations: [
      {
        Id: 'us-va-ash-azr'
      }
      {
        Id: 'emea-nl-ams-azr'
      }
      {
        Id: 'apac-jp-kaw-edge'
      }
    ]
    Configuration: {
      WebTest: '<WebTest   Name="${pingTestName}"   Enabled="True"         CssProjectStructure=""    CssIteration=""  Timeout="120"  WorkItemIds=""         xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"         Description=""  CredentialUserName=""  CredentialPassword=""         PreAuthenticate="True"  Proxy="default"  StopOnError="False"         RecordedResultFile=""  ResultsLocale="">  <Items>  <Request Method="GET"    Version="1.1"  Url="${pingURL}" ThinkTime="0"  Timeout="300" ParseDependentRequests="True"         FollowRedirects="True" RecordResult="True" Cache="False"         ResponseTimeGoal="0"  Encoding="utf-8"  ExpectedHttpStatusCode="200"         ExpectedResponseUrl="" ReportingName="" IgnoreHttpStatusCode="False" />        </Items>  <ValidationRules> <ValidationRule  Classname="Microsoft.VisualStudio.TestTools.WebTesting.Rules.ValidationRuleFindText, Microsoft.VisualStudio.QualityTools.WebTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" DisplayName="Find Text"         Description="Verifies the existence of the specified text in the response."         Level="High"  ExecutionOrder="BeforeDependents">  <RuleParameters>        <RuleParameter Name="FindText" Value="${pingText}" />  <RuleParameter Name="IgnoreCase" Value="False" />  <RuleParameter Name="UseRegularExpression" Value="False" />  <RuleParameter Name="PassIfTextFound" Value="True" />  </RuleParameters> </ValidationRule>  </ValidationRules>  </WebTest>'
    }
    SyntheticMonitorId: pingTestName
  }
}

resource metricAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = {
  name: pingAlertRuleName
  location: 'global'
  tags: {
    'hidden-link:${resourceId('Microsoft.Insights/components', appName)}': 'Resource'
    'hidden-link:${pingTest.id}': 'Resource'
  }
  properties: {
    description: 'Alert for web test'
    severity: 1
    enabled: true
    scopes: [
      pingTest.id
      resourceId('Microsoft.Insights/components', appName)
    ]
    evaluationFrequency: 'PT1M'
    windowSize: 'PT5M'
    criteria: {
      'odata.type': 'Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria'
      webTestId: pingTest.id
      componentId: resourceId('Microsoft.Insights/components', appName)
      failedLocationCount: 2
    }
    actions: [
      {
        actionGroupId: actionGroupId
      }
    ]
  }
}

Файл параметров

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "appName": {
      "value": "Replace with your Application Insights resource name"
    },
    "pingURL": {
      "value": "https://www.yoursite.com"
    },
    "actionGroupId": {
      "value": "/subscriptions/replace-with-subscription-id/resourceGroups/replace-with-resourceGroup-name/providers/microsoft.insights/actiongroups/replace-with-action-group-name"
    },
    "location": {
      "value": "Replace with the location of your Application Insights resource"
    },
    "pingText": {
      "defaultValue": "Optional parameter that allows you to perform a content-match for the presence of a specific string within the content returned from a pingURL response",
      "type": "String"
    },
  }
}

Дополнительные настройки параметра pingText сопоставления содержимого управляются в разделе Configuration/Webtest файла шаблона. Этот раздел показан ниже.

<RuleParameter Name=\"FindText\" Value=\"',parameters('pingText'), '\" />
<RuleParameter Name=\"IgnoreCase\" Value=\"False\" />
<RuleParameter Name=\"UseRegularExpression\" Value=\"False\" />
<RuleParameter Name=\"PassIfTextFound\" Value=\"True\" />

Расположения тестирования

ИД Регион
emea-nl-ams-azr Западная Европа
us-ca-sjc-azr западная часть США
emea-ru-msa-edge южная часть Соединенного Королевства
emea-se-sto-edge западная часть Соединенного Королевства
apac-sg-sin-azr Юго-Восточная Азия
us-tx-sn1-azr Центрально-южная часть США
us-il-ch1-azr Центрально-северная часть США
emea-gb-db3-azr Северная Европа
apac-jp-kaw-edge Восточная Япония
emea-fr-pra-edge Центральная Франция
emea-ch-zrh-edge Южная Франция
us-va-ash-azr Восточная часть США
apac-hk-hkn-azr Восточная Азия
us-fl-mia-edge Центральная часть США
latam-br-gru-edge Южная Бразилия
emea-au-syd-edge Восточная Австралия

Расположения для тестирования для государственных организаций США

ИД Регион
usgov-va-azr USGov Virginia
usgov-phx-azr USGov Arizona
usgov-tx-azr USGov Texas
usgov-ddeast-azr USDoD East
usgov-ddcentral-azr USDoD Central

Следующие шаги