Is it possible to use the Azure CLI for setting up a monitoring URL Ping test?

Viewed 1400
4 Answers

There is no built-in cli command to do this, your option is to use az rest call the REST API - Web Tests - Create Or Update directly.

First, store a webtest.json file as below to your powershell execute location e.g. my location is PS C:\Users\Administrator>, I store the file in C:\Users\Administrator folder.

In this file, the centralus is the location of my appinsight, /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/microsoft.insights/components/<appinsight-name> is the resource id of my appinsight, joytest1 is the name of the ping test, joyfun2 is the name of the appinsight, https://joyfun2.azurewebsites.net is the URL you want to test, please replace them with your values.

{
  "location": "centralus",
  "kind": "ping",
  "tags": {
    "hidden-link:/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/microsoft.insights/components/<appinsight-name>": "Resource"
  },
  "properties": {
    "Name": "joytest1",
    "SyntheticMonitorId": "joytest1-joyfun2",
"Configuration": {
      "WebTest": "<WebTest         Name=\"joytest1\"         Id=\"ec14f587-a3f6-40ac-8952-75c900e1d153\"         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\"         Guid=\"a7247e6c-29c1-2451-f4c8-78afe599253d\"         Version=\"1.1\"         Url=\"https://joyfun2.azurewebsites.net\"         ThinkTime=\"0\"         Timeout=\"120\"         ParseDependentRequests=\"False\"         FollowRedirects=\"True\"         RecordResult=\"True\"         Cache=\"False\"         ResponseTimeGoal=\"0\"         Encoding=\"utf-8\"         ExpectedHttpStatusCode=\"200\"         ExpectedResponseUrl=\"\"         ReportingName=\"\"         IgnoreHttpStatusCode=\"False\" />        </Items>        </WebTest>"
    },
    "Enabled": true,
    "Frequency": 900,
    "Timeout": 120,
    "Kind": "ping",
    "RetryEnabled": true,
    "Locations": [
      {
        "Id": "us-fl-mia-edge"
      },
      {
        "Id": "us-tx-sn1-azr"
      },
      {
        "Id": "emea-au-syd-edge"
      }
    ]
  }
}

Then run the command below, also replace the values like above.

az rest --method PUT --uri "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<group-name>/providers/Microsoft.Insights/webtests/joytest1-joyfun2?api-version=2015-05-01" --headers 'Content-Type=application/json' --body `@webtest.json

It works fine on my side.

enter image description here

Check in the portal:

enter image description here

You can do it via deploying ARM template. Here is an example of a template. It creates an availability test and sets up an alert.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "webTestLocation": {
            "type": "String"
        },
        "componentName": {
            "type": "String"
        },
        "testName": {
            "type": "String"
        },
        "testEndpoint": {
            "type": "String"
        },
        "testLocations": {
            "type": "Array"
        },
        "numLocationsToAlertOn": {
            "type": "Int" 
        },
        "alertDescription": {
            "type": "String"
        }
    },
    "resources": [
        {
            "type": "microsoft.insights/webtests",
            "apiVersion": "2015-05-01",
            "name": "[parameters('testName')]",
            "location": "[parameters('webTestLocation')]",
            "tags": {
                "[concat('hidden-link:',resourceId('microsoft.insights/components',parameters('componentName')))]": "Resource"
            },
            "properties": {
                "SyntheticMonitorId": "[parameters('testName')]",
                "Name": "[parameters('testName')]",
                "Enabled": true,
                "Frequency": 300,
                "Timeout": 120,
                "Kind": "ping",
                "RetryEnabled": false,
                "Locations": "[parameters('testLocations')]",
                "Configuration": {
                    "WebTest": "[concat('<WebTest         Name=\"',parameters('testName'),'\"         Id=\"00000000-0000-0000-0000-000000000000\"         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\"         Guid=\"a86e39d1-b852-55ed-a079-23844e235d01\"         Version=\"1.1\"         Url=\"',parameters('testEndpoint'),'\"         ThinkTime=\"0\"         Timeout=\"120\"         ParseDependentRequests=\"False\"         FollowRedirects=\"True\"         RecordResult=\"True\"         Cache=\"False\"         ResponseTimeGoal=\"0\"         Encoding=\"utf-8\"         ExpectedHttpStatusCode=\"200\"         ExpectedResponseUrl=\"\"         ReportingName=\"\"         IgnoreHttpStatusCode=\"False\" />        </Items>        </WebTest>')]"
                }
            }
        },
        {
            "type": "microsoft.insights/metricalerts",
            "name": "[parameters('testName')]",
            "apiVersion": "2018-03-01",
            "location": "global",
            "tags": {
                "[concat('hidden-link:',resourceId('microsoft.insights/components',parameters('componentName')))]": "Resource",
                "[concat('hidden-link:',resourceId('microsoft.insights/webtests',parameters('testName')))]": "Resource"
            },
            "properties": {
                "description": "[parameters('alertDescription')]",
                "enabled": true,
                "severity": 3,
                "windowSize": "PT5M",
                "evaluationFrequency": "PT1M",
                "criteria": {
                    "failedLocationCount": "[parameters('numLocationsToAlertOn')]",
                    "webTestId": "[resourceId('microsoft.insights/webtests/',parameters('testName'))]",
                    "componentId": "[resourceId('microsoft.insights/components/',parameters('componentName'))]",
                    "odata.type": "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria"
                },
                "actions": [
                    {
                        "actionGroupId": "[resourceId('microsoft.insights/actiongroups', 'IcM')]",
                        "webhookProperties": {}
                    }
                ],
                "scopes": [ "[resourceId('microsoft.insights/webtests/',parameters('testName'))]", "[resourceId('microsoft.insights/components/',parameters('componentName'))]" ]
            },
            "dependsOn": [
                "[resourceId('microsoft.insights/webtests', parameters('testName'))]"
            ]
        }
    ]
}

Here is an example of how to do it using Powershell Az module:

  $result = New-AzResourceGroupDeployment `
    -Name $stampHealthCheckScaleTestName `
    -ResourceGroupName $appInsightsResourceGroupName `
    -Mode Incremental `
    -TemplateFile $scriptRoot\ArmTemplates\HealthCheckScaleArmTemplate.json `
    -webTestLocation $appInsightsComponentLocation `
    -componentName $appInsightsComponentName `
    -testName $stampHealthCheckScaleTestName `
    -testEndpoint "https://$($customDomainName)/healthcheckscale/status" `
    -testLocations $testLocations `
    -numLocationsToAlertOn $numLocationsToAlertOn `
    -alertDescription $alertDescription

Here is an example of generic ARM template deployment using az cli: https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/deploy-cli#inline-parameters

Here is another example to create a classic URL Ping Test with bicep-lang. Unfortunately, the format of the WebTest XML is not documented.

Pay attention to the hidden-link tag, which should point to your app insights resource.

var name = 'demo-url-ping-web-test'
var rg = 'rg-article'
var subscriptionId = '<your_subscription_id>'
var appInsightsName = 'appi-demo'

var id = guid('seed')
var timeout = 120
var frequency = 300
var guidId = guid('seed')
var method = 'GET'
var url = 'https://www.azureblue.io'
var expectedHttpStatusCode = 200
var version = '1.1'
var followRedirects = 'True'
var recordResults = 'True'
var cache = 'False'
var parseDependentRequests = 'False'
var ignoreHttpStatusCode = 'False'

resource urlPingWebTest 'Microsoft.Insights/webtests@2015-05-01' = {
  name: name
  location: 'westeurope'
  tags: {
    'hidden-link:/subscriptions/${subscriptionId}/resourceGroups/${rg}/providers/microsoft.insights/components/${appInsightsName}': 'Resource'
  }
  kind: 'ping'
  properties: {
    Configuration: {
      WebTest: '<WebTest xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" Name="${name}" Id="${id}" Enabled="True" CssProjectStructure="" CssIteration="" Timeout="${timeout}" WorkItemIds="" Description="" CredentialUserName="" CredentialPassword="" PreAuthenticate="True" Proxy="default" StopOnError="False" RecordedResultFile="" ResultsLocale=""> <Items> <Request Method="${method}" Guid="${guidId}" Version="${version}" Url="${url}" ThinkTime="0" Timeout="${timeout}" ParseDependentRequests="${parseDependentRequests}" FollowRedirects="${followRedirects}" RecordResult="${recordResults}" Cache="${cache}" ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="${expectedHttpStatusCode}" ExpectedResponseUrl="" ReportingName="" IgnoreHttpStatusCode="${ignoreHttpStatusCode}" /> </Items> </WebTest>'
    }
    Description: 'Runs a classic URL ping test'    
    Enabled: true
    Frequency: frequency
    Kind: 'ping'
    Locations: [
      {
        Id: 'emea-nl-ams-azr'
      }
      {
        Id: 'emea-ru-msa-edge'
      }
      {
        Id: 'apac-hk-hkn-azr'
      }
      {
        Id: 'latam-br-gru-edge'
      }
      {
        Id: 'emea-au-syd-edge'
      }
    ]
    Name: name
    RetryEnabled: true 
    SyntheticMonitorId: '${name}-id'
    Timeout: timeout
  }
}

You can deploy the template by using Azure CLI like so:

az deployment group create --name rollout01 --resource-group rg-article --subscription "your subscription" --template-file urlpingwebtest.bicep

If you are feeling brave you can also create a so-called Standard Test which is currently in preview but doesn't require the ominous WebTest XML string and works just well for me.

resource standardWebTest 'Microsoft.Insights/webtests@2018-05-01-preview' = {
  name: 'demo-webtest'
  location: 'westeurope'
  tags: {
    'hidden-link:/subscriptions/ade29918-737f-497e-8808-4bffda5cc46d/resourceGroups/rg-article/providers/microsoft.insights/components/appi-demo': 'Resource'
  }
  kind: 'standard'
  properties: {
    SyntheticMonitorId: 'demo-webtest-id'
    Name: 'demo-webtest'
    Description: null
    Enabled: true
    Frequency: 300
    Timeout: 120 
    Kind: 'standard'
    RetryEnabled: true
    Locations: [
      {
        Id: 'emea-nl-ams-azr'
      }
      {
        Id: 'emea-ru-msa-edge'
      }
      {
        Id: 'apac-hk-hkn-azr'
      }
      {
        Id: 'latam-br-gru-edge'
      }
      {
        Id: 'emea-au-syd-edge'
      }
    ]
    Configuration: null
    Request: {
      RequestUrl: 'https://www.azureblue.io'
      Headers: null
      HttpVerb: 'GET'
      RequestBody: null
      ParseDependentRequests: false
      FollowRedirects: null
    }
    ValidationRules: {
      ExpectedHttpStatusCode: 200
      IgnoreHttpsStatusCode: false
      ContentValidation: null
      SSLCheck: true
      SSLCertRemainingLifetimeCheck: 7
    }
  }
}

You can read more about this on my blog post, which can be found here

For the benefit of anyone that finds this discussion, this seems to be working now that I test it:

az monitor app-insights web-test create `
    --web-test-kind "standard" --enabled true `
    --location $location `
    --resource-group $rgName `
    --name "health-check" --defined-web-test-name "health-check" `
    --tags "hidden-link:$($appInsights.Id)=Resource" `
    --http-verb "GET" --request-url "$appBaseUrl/health" `
    --timeout 30 --frequency 300 --retry-enabled true `
    --locations Id="emea-nl-ams-azr" --locations Id="us-fl-mia-edge"

I assume that this is what @ZakiMa was referring to.

Related