0

I'm trying to create an Alert Rule for an Application Insights → Availability → Standard (preview) test. First off, how do you create a standard test? For now, I resorted to creating the resource by using a resource "azurerm_resource_group_template_deployment" …; see gist.github.com/alexs77/0b2bd07aae7fbf22bd3c145132475e7d for exactly how.

But even if it were a azurerm_application_insights_web_test, how would an Alert Rule (ie. azurerm_monitor_metric_alert - right?) look like? I'm confused about this part:

# …
resource "azurerm_monitor_metric_alert" "example" {
  # …
  criteria {
    metric_name      = "???"
    metric_namespace = "???"
    # …
  }
# …

What are the correct values to use there?

I am aware about this ancient blog post Creating an Application Insights Web Test and Alert Programmatically from 2015 - 6 years ago. It makes you go to the Azure Resource Explorer:

In Resource Explorer, open your subscription and resource group, then providers, Microsoft Insights. There you’ll see two folders that will be important to us today: webtests and alertrules.

When I go to "microsoft.insights", the "folder" alertrules isn't there.

Resource Explorer -> microsoft.insights: NO alertrules

Alexander Skwar
  • 875
  • 1
  • 9
  • 20
  • 1
    Updated the answer with the arm template – Ansuman Bal Nov 23 '21 at 13:34
  • If the answer was helpful, Please [Accept it as an Answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), so that others who encounter the same issue can find this solution and fix their problem. – Ansuman Bal Dec 23 '21 at 13:18

1 Answers1

2

I'm trying to create an Alert Rule for an Application Insights → Availability → Standard (preview) test. First off, how do you create a standard test?

As Standard Test is a preview feature , its currently not added in terraform-azurerm-provider. It can be only deployed from ARM templates as of now. Only Classic Test can be deployed from Terraform for now.


But even if it were a azurerm_application_insights_web_test, how would an Alert Rule (ie. azurerm_monitor_metric_alert - right?) look like?

You don't have to use criteria / dynamic criteria instead you should use application_insights_web_test_location_availability_criteria. So, metric_name and metric_namespace won't be required . Using that your code for classic web test with alert rule will look something like below:

provider "azurerm" {
  features{}
}
data "azurerm_application_insights" "example" {
  name="ansumantestapp"
  resource_group_name = "ansbalrg"
}

resource "azurerm_application_insights_web_test" "example" {
  name                    = "tf-test-appinsights-webtest"
  location                = data.azurerm_application_insights.example.location
  resource_group_name     = data.azurerm_application_insights.example.resource_group_name
  application_insights_id = data.azurerm_application_insights.example.id
  kind                    = "ping"
  frequency               = 300
  timeout                 = 60
  enabled                 = true
  geo_locations           = ["us-ca-sjc-azr", "us-va-ash-azr"]

  configuration = <<XML
<WebTest Name="WebTest1" Id="ABD48585-0831-40CB-9069-682EA6BB3583" Enabled="True" CssProjectStructure="" CssIteration="" Timeout="0" WorkItemIds="" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" Description="" CredentialUserName="" CredentialPassword="" PreAuthenticate="True" Proxy="default" StopOnError="False" RecordedResultFile="" ResultsLocale="">
  <Items>
    <Request Method="GET" Guid="a5f10126-e4cd-570d-961c-cea43999a200" Version="1.1" Url="http://microsoft.com" ThinkTime="0" Timeout="300" ParseDependentRequests="True" FollowRedirects="True" RecordResult="True" Cache="False" ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="200" ExpectedResponseUrl="" ReportingName="" IgnoreHttpStatusCode="False" />
  </Items>
</WebTest>
XML

}
resource "azurerm_monitor_action_group" "main" {
  name                = "example-actiongroup"
  resource_group_name = data.azurerm_application_insights.example.resource_group_name
  short_name          = "exampleact"
  email_receiver {
    name                    = "sendtoadmin"
    email_address           = "myemailid"
    use_common_alert_schema = true
  }
}

resource "azurerm_monitor_metric_alert" "example" {
  name                = "example-metricalert"
  resource_group_name = data.azurerm_application_insights.example.resource_group_name
  scopes = [azurerm_application_insights_web_test.example.id,data.azurerm_application_insights.example.id]
  description         = "PING test alert"

application_insights_web_test_location_availability_criteria {
  web_test_id = azurerm_application_insights_web_test.example.id
  component_id = data.azurerm_application_insights.example.id
  failed_location_count = 2
}

  action {
    action_group_id = azurerm_monitor_action_group.main.id
  }
}

Output:

enter image description here

enter image description here

enter image description here


Update for ARM template:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
      "appInsightsName": {"type": "String"},
      "certRemainingLifetimeCheck": {"type": "Int"},
      "resourceLocation": {"type": "String"},
      "testCategory": {"type": "String"},
      "testHostname": {"type": "String"},
      "testHostnameSafe": {"type": "String"},
      "testHttpCode": {"type": "String"},
      "testLocations": {"type": "String"},
      "appname":{"type": "String"}
    },
    "variables": {
      "requestUrl": "[concat('https://',parameters('testHostname'))]",
      "testLocations": "[split(parameters('testLocations'),',')]",
      "hiddenLink": "[concat('hidden-link:',resourceId('microsoft.insights/components',parameters('appInsightsName')))]",
      "pingTestName":"[concat(parameters('testHostnameSafe'),'-tls-ttl-', parameters('testCategory'), '-webtest')]",
      "pingAlertRuleName": "[concat('PingAlert-', toLower(parameters('appName')), '-', subscription().subscriptionId)]",
      "copy": [
        {
          "name": "locations",
          "count": "[length(variables('testLocations'))]",
          "input":{
              "Id": "[variables('testLocations')[copyIndex('locations')]]"
          }
        }
      ]
    },
    "resources": [
      {
        "type": "Microsoft.Insights/webtests",
        "apiVersion": "2018-05-01-preview",
        "name": "[variables('pingTestName')]",
        "location":"[parameters('resourceLocation')]",
        "tags": {
          "Managed By": "Terraform",
          "[variables('hiddenLink')]": "Resource"
        },
        "properties": {
          "SyntheticMonitorId": "[variables('pingTestName')]",
          "Name": "[variables('pingTestName')]",
          "Description": "[concat('Check lifetime of TLS certificate on ', parameters('testHostnameSafe'))]",
          "Enabled": true,
          "Frequency": 300,
          "Timeout": 120,
          "Kind": "standard",
          "RetryEnabled": true,
          "Locations": "[variables('locations')]",
          "Configuration": null,
          "Request": {
            "RequestUrl": "[variables('requestUrl')]",
            "Headers": null,
            "HttpVerb": "GET",
            "RequestBody": null,
            "ParseDependentRequests": false,
            "FollowRedirects": null
          },
          "ValidationRules": {
            "ExpectedHttpStatusCode": "[int(parameters('testHttpCode'))]",
            "IgnoreHttpsStatusCode": false,
            "ContentValidation": null,
            "SSLCheck": true,
            "SSLCertRemainingLifetimeCheck": "[parameters('certRemainingLifetimeCheck')]"
          }
        }
      },
      {
      "name": "[variables('pingAlertRuleName')]",
      "type": "Microsoft.Insights/metricAlerts",
      "apiVersion": "2018-03-01",
      "location": "global",
      "dependsOn": [
        "[resourceId('Microsoft.Insights/webtests', variables('pingTestName'))]"
      ],
      "tags": {
        "[variables('hiddenLink')]": "Resource",
        "[concat('hidden-link:', resourceId('Microsoft.Insights/webtests', variables('pingTestName')))]": "Resource"
      },
      "properties": {
        "description": "Alert for web test",
        "severity": 1,
        "enabled": true,
        "scopes": [
          "[resourceId('Microsoft.Insights/webtests',variables('pingTestName'))]",
          "[resourceId('microsoft.insights/components',parameters('appInsightsName'))]"
        ],
        "evaluationFrequency": "PT1M",
        "windowSize": "PT5M",
        "criteria": {
          "odata.type": "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria",
          "webTestId": "[resourceId('Microsoft.Insights/webtests', variables('pingTestName'))]",
          "componentId": "[resourceId('microsoft.insights/components',parameters('appInsightsName'))]",
          "failedLocationCount": 2
        }
      }
    }
  ]
}

Outputs:

enter image description here

enter image description here

enter image description here

Ansuman Bal
  • 9,705
  • 2
  • 10
  • 27
  • Thanks, that's been helpful. But actually, I'd need to have a standard test, as I'd need to check the validity of a TLS certificate. And that can't be done with "Classic", can it? So, the only reason why it's not yet in Tf is because it's preview? It's been preview for 3+ years now. :( If ARM template would be the way that one is forced to go, how to use this then in a azurerm_monitor_metric_alert? – Alexander Skwar Nov 23 '21 at 12:01
  • let me add the arm template answer as well – Ansuman Bal Nov 23 '21 at 12:06
  • https://gist.github.com/alexs77/0b2bd07aae7fbf22bd3c145132475e7d - that's how I'm doing it. – Alexander Skwar Nov 23 '21 at 12:29
  • 1
    will add the metric alert to that template – Ansuman Bal Nov 23 '21 at 12:31
  • 1
    @AlexanderSkwar , please find the arm template in the update section, I have modified your arm template only by adding the alert rule resource. – Ansuman Bal Nov 23 '21 at 15:22
  • awesome. so you're also setting up the alert with ARM. that is not so nice, but I suppose that's the way to go for now. – Alexander Skwar Nov 24 '21 at 06:53
  • this does not seem to work. I ran a deployment with your ARM template and it created a Microsoft.Insights/metricAlerts resource, per the deployment log of the resource group on portal. But I cannot find this alert anywhere. Also when I go the web test - edit - alerts, it says "disabled". – Alexander Skwar Dec 01 '21 at 09:36
  • @AlexanderSkwar, it is a metric alert only with availability test criteria , it was the same for me as well if you see the screenshot and for the alert rule it can be found in the `webapp>>monitoring>>alerts.` – Ansuman Bal Dec 01 '21 at 09:48
  • Thx. Seems to have been some sort of glitch. Maybe because I was reusing the name or something. Don't know. But now it is working :) BTW: Can you please have a look at https://stackoverflow.com/q/70184826/5295392 ? – Alexander Skwar Dec 01 '21 at 13:11
  • taking a look if i can help on the other OP – Ansuman Bal Dec 01 '21 at 13:12