Activity Log Alerts in Azure - azure

I have created an Activity Log Alert in Azure that does a custom log search against an Application Insights instance.
The alert is working and action groups is notified through the channels I have set up.
The problem I'm having is to create that alert in the arm template we are using to deploy the resources.
When looking at the automation script in the portal the alerts are left out and is not visible. (microsoft.insights/scheduledqueryrules)
I can't find any information online on how to write the condition in the template so it works with a custom log search.
Any suggestions where to find info on how to write the condition or how to extract the template from the portal for those alerts.

This is an ARM template part that creates an alert with a scheduled query. It also adds an array of action groups that get notified when the alert is triggered:
{
"name": "[parameters('scheduleQueryMonitorApplicationError')]",
"type": "microsoft.insights/scheduledqueryrules",
"apiVersion": "2018-04-16",
"location": "[resourceGroup().location]",
"tags": {
"[concat('hidden-link:', resourceGroup().id, '/resourceGroups/', parameters('resourceGroupName'), '/providers/microsoft.insights/components/', parameters('applicationInsightsName'))]": "Resource"
},
"properties": {
"description": "[parameters('scheduleQueryMonitorApplicationError')]",
"enabled": "true",
"source": {
"query": "traces | where severityLevel == 3",
"queryType": "ResultCount",
"dataSourceId": "[resourceId('microsoft.insights/components', parameters('applicationInsightsName'))]"
},
"schedule": {
"frequencyInMinutes": 5,
"timeWindowInMinutes": 5
},
"action": {
"odata.type": "Microsoft.WindowsAzure.Management.Monitoring.Alerts.Models.Microsoft.AppInsights.Nexus.DataContracts.Resources.ScheduledQueryRules.AlertingAction",
"severity": "3",
"aznsAction": {
"actionGroup": "[array( resourceId('microsoft.insights/actiongroups', parameters('actionGroupName')) )]"
},
"trigger": {
"threshold": 1,
"thresholdOperator": "GreaterThan"
}
}
},
"dependsOn": [
"[resourceId('microsoft.insights/components', parameters('applicationInsightsName'))]"
]
},

Please see this stackoverflow thread, where a similar question was asked. Elfocrash mentions that he wrote a blog post about that, explaining how it works. I tried his method and it works.

Related

"Cannot read properties of undefined" when using ResourceSelector on UIDefinition

I'm building an ARM template that deploys some variables and runbooks to the automation account that the user selects.
To guide the user, I use a
{
"name": "AutomationAccount",
"type": "Microsoft.Solutions.ResourceSelector",
"resourceType": "Microsoft.Automation/automationAccounts",
"label": "Automation Account",
"toolTip": "The Automation Account that will host these runbooks.",
"filter": {
"subscription": "onBasics",
"location": "onBasics"
},
"visible": true
}
This correctly displays a dropdown that allows me to select the Automation Account filtered to the subscription and the resource group.
At the end of the UIDefinition.json file, I output the selected value like so:
"outputs": {
"parameters": {
...
"AutomationAccountId": "[steps('basics').AutomationAccount.id]",
...
}
}
(based on the sample output from the documentation for the ResourceSelector)
My ARM template is then supposed to use this value as a parameter:
"parameters": {
...
"AutomationAccountId": {
"type": "string",
"metadata": {
"description": "The resourceId of the Automation Account that will host this runbook."
}
},
...
}
which I then use as part of the name for a new variable:
"resources": [
...
{
"name": "[concat(parameters('AutomationAccountId'), '/MyVariableName')]",
"type": "Microsoft.Automation/automationAccounts/variables",
"apiVersion": "2019-06-01",
"dependsOn": [ ],
"properties": {
"value": "[parameters('SomeVariableValueParameter')]",
"description": "Some description')",
"isEncrypted": false
}
...
The UI displays correctly, allowing me to pick an Automation Account, but when I get to the Review & Create stage, validation fails with the following error message:
with the following error detail:
ERROR TYPE
Cannot read properties of undefined (reading 'subscriptionId')
Can anyone help out?

Microsoft.ApiManagement/service/diagnostics/loggers in Azure API Manager ARM template

This is how the chunk of the ARM template looks:
{
"type": "Microsoft.ApiManagement/service/diagnostics/loggers",
"apiVersion": "2018-01-01",
"name": "[concat(variables('gatewayName'), '/applicationinsights/', variables('gatewayName'))]",
"dependsOn": [
"[resourceId('Microsoft.ApiManagement/service/diagnostics', variables('gatewayName'), 'applicationinsights')]",
"[resourceId('Microsoft.ApiManagement/service', variables('gatewayName'))]"
],
"properties": {
"loggerType": "applicationInsights",
"credentials": {
"instrumentationKey": "[reference(resourceId('Microsoft.Insights/components', variables('appInsights')), '2014-04-01').InstrumentationKey]"
},
"isBuffered": true,
"resourceId": "[variables('appInsights')]"
}
},
For two days our ARM template deployment is failing with the error:
{"status":"Failed","error":{"code":"DeploymentFailed","message":"At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.","details":[{"code":"BadRequest","message":"{\r\n \"error\": {\r\n \"code\": \"MethodNotAllowedInPricingTier\",\r\n \"message\": \"Method not allowed in this pricing tier\",\r\n \"details\": null\r\n }\r\n}"}]}}
Although the error states the pricing tier, there were no changes in the template.
Verbatim google search result shows that the resource existed before as the first result item.
The documentation does not mention it anymore in the diagnostics section.
GitHub, though, remembers the resource but mentions different properties within the object:
"service_diagnostics_loggers": {
"type": "object",
"properties": {
"apiVersion": {
"type": "string",
"enum": [
"2018-01-01"
]
},
"name": {
"oneOf": [
{
"type": "string",
"pattern": "(^[\\w]+$)|(^[\\w][\\w\\-]+[\\w]$)",
"maxLength": 80
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "Logger identifier. Must be unique in the API Management service instance."
},
"type": {
"type": "string",
"enum": [
"Microsoft.ApiManagement/service/diagnostics/loggers"
]
}
},
"required": [
"apiVersion",
"name",
"type"
],
"description": "Microsoft.ApiManagement/service/diagnostics/loggers"
}
It looks like the resource was removed from the ARM template infrastructure silently. What is wrong my analysis?
diagnostics/loggers resource does exist in 2018-01-01 API version: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2018-01-01/apimdiagnostics.json
After that though it was removed and replaced by loggerId property on diagnostic entity itself: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2019-01-01/definitions.json#L1771
We'll check why older API version doesn't seem to work, meanwhile you could try migrating to a newer API version.

Logic App posting to Microsoft Teams data not showing in fields

I've created an Alert in my App Service that sends an Alert to a logic app, the logic app is then posting a message to Microsoft Teams.
https://learn.microsoft.com/en-us/azure/azure-monitor/platform/action-groups-logic-app
Everything is working as expected accept that i can get the data out of the individual into my Message.
I've used the following in schema in my logic App
{
"schemaId": "azureMonitorCommonAlertSchema",
"data": {
"essentials": {
"alertId": "/subscriptions/MyAlert",
"alertRule": "Web - Test teams",
"severity": "Sev1",
"signalType": "Metric",
"monitorCondition": "Fired",
"monitoringService": "Platform",
"alertTargetIDs": [
"/subscriptions/MySub"
],
"originAlertId": "bd40051b-35fa-,
"firedDateTime": "2020-06-03T14:53:34.0942607Z",
"description": "",
"essentialsVersion": "1.0",
"alertContextVersion": "1.0"
},
"alertContext": {
"properties": null,
"conditionType": "SingleResourceMultipleMetricCriteria",
"condition": {
"windowSize": "PT5M",
"allOf": [
{
"metricName": "Http2xx",
"metricNamespace": "Microsoft.Web/sites",
"operator": "GreaterThan",
"threshold": "5",
"timeAggregation": "Total",
"dimensions": [
{
"name": "ResourceId",
"value": "MyWebs.com"
}
],
"metricValue": 24,
"webTestName": null
}
],
"windowStartTime": "2020-06-03T14:45:23.095Z",
"windowEndTime": "2020-06-03T14:50:23.095Z"
}
}
}
}
Then in the designer added the fields
Here is the details from the Logic code view for the message body
"content": "Your Azure Monitor alert was triggered\nAzure monitor alert rule Web - Test teams was triggered at #{triggerBody()?['body']?['data']?['alertContext']?['condition']?['windowEndTime']}\n\nRule: #{triggerBody()?['body']?['data']?['essentials']?['alertRule']}\nBody:#{triggerBody()}\nHeader:#{triggerOutputs()['headers']}\nheaders:#{triggerBody()?['headers']}\nessentials:#{triggerBody()?['body']?['data']?['essentials']}\ndata:#{triggerBody()?['body']?['data']}\nbody:#{triggerBody()?['body']}"
The only field that gets populated is the body and none of the specific fields
Your Azure Monitor alert was triggered
Azure monitor alert rule Web - Test teams was triggered at
Rule:
Body:{"schemaId":"azureMonitorCommonAlertSchema","data":{"essentials":{"alertId":"/subscriptions/bresourceGroups/Microsoft.AlertsManagement/alerts","alertRule":"Web - Test Alert","severity":"Sev0","signalType":"Metric","monitorCondition":"Fired","monitoringService":"Platform","alertTargetIDs":[""],"originAlertId":"":"2020-06-03T15:49:20.1712118Z","description":"","essentialsVersion":"1.0","alertContextVersion":"1.0"},"alertContext":{"properties":null,"conditionType":"SingleResourceMultipleMetricCriteria","condition":{"windowSize":"PT5M","allOf":[{"metricName":"Http2xx","metricNamespace":"Microsoft.Web/sites","operator":"GreaterThan","threshold":"3","timeAggregation":"Count","dimensions":[{"name":"ResourceId","value":""}],"metricValue":7.0,"webTestName":null}],"windowStartTime":"2020-06-03T15:41:05.994Z","windowEndTime":"2020-06-03T15:46:05.994Z"}}}}
Header:{"Connection":"Keep-Alive","Expect":"100-continue","Host":"prod-06.uksouth.logic.azure.com","User-Agent":"IcMBroadcaster/1.0","X-CorrelationContext":"RkkKACgAAAACAAAAEABEgMLahbH0Sqw1EVoRy7Y8AQAQANlpmHhZlSRMkU6bLTb+DSk=","Content-Length":"1254","Content-Type":"application/json; charset=utf-8"}
headers:
essentials:
data:
body:
I had to manually update the Logic Code and remove the additional body tag
original
#{triggerBody()?['body']?['data']?['alertContext']?['condition']?['windowEndTime']}
to this
#{triggerBody()?['data']?['alertContext']?['condition']?['windowEndTime']}

ARM template deployment fails for Azure Function Event Grid Subscription to custom topic

I can successfully deploy a Custom Event Grid Topic and Azure Function app via ARM templates.
After that, in a separate ARM deployment, an Azure Function Event Grid Subscription to this custom topic fails at validation stage with the following error:
The template resource 'Microsoft.EventGrid/topics/EventGridCustomTopicName/providers/Microsoft.EventGrid/eventSubscriptions/EventGridSubscriptionName' cannot reference itself.
'EventGridSubscriptionName' is the same as the name of my function app, if that matters.
Again: I have a Topic and a Function app already created.
I have gone through the official examples and documentation, but it does not work for me nevertheless.
Here is my template defined as a root resource:
{
"name": "[concat(parameters('EventGridCustomTopicName'), '/Microsoft.EventGrid/', variables('EventGridSubscriptionName'))]",
"type": "Microsoft.EventGrid/topics/providers/eventSubscriptions",
"location": "[resourceGroup().location]",
"apiVersion": "2018-01-01",
"dependsOn": [
"[parameters('FunctionAppName')]"
],
"properties": {
"destination": {
"endpointType": "WebHook",
"properties": {
"endpointUrl": "[concat('https://', parameters('FunctionAppName'), '.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName=TopicSubscriber&code=', variables('funcCode'))]"
}
},
"filter": {
"includedEventTypes": [
"All"
]
}
}
}
Any help is highly appreciated!
i think whats happening the name is ambiguous and it cannot understand what to depends on. try doing something like this:
"dependsOn": [
"[resourceId('Microsoft.Web/sites', parameters('FunctionAppName'))]"
],

I want to create a runbook on an automation account with a shedule already connected to it through arm

With my ARM template I want to create an automation account with a runbook and a shedule , so far so good. But if i want to connect my shedule to my runbook through the template I can't seem to find the working way to do this.
First try (working) : create automation account with a runbook and a shedule
"variables": {
"name": "StartAllVM",
"url": "https://gallery.technet.microsoft.com/scriptcenter/Start-Azure-V2-VMs-6352312e/file/147007/1/Start-AzureV2VMs.ps1",
"version": "1.0.0.0",
"type": "PowerShell",
"description": "This PowerShell script runbook connects to Azure and starts all VMs in an Azure subscription or cloud service"
},
"resources": [
{
"name": "AutomationDev",
"type": "Microsoft.Automation/automationAccounts",
"apiVersion": "2015-10-31",
"properties": {
"sku": {
"name": "Free"
}
},
"location": "[parameters('location')]",
"tags": {},
"resources": [
{
"name": "[variables('name')]",
"type": "runbooks",
"apiVersion": "2015-01-01-preview",
"location": "[resourceGroup().location]",
"dependsOn": [
"[concat('Microsoft.Automation/automationAccounts/', 'AutomationDev')]"
],
"properties": {
"runbookType": "PowerShell",
"logProgress": false,
"logVerbose": true,
"publishContentLink": {
"uri": "[variables('url')]",
"version": "[variables('version')]"
}
}
},
{
"comments": "",
"type": "schedules",
"name": "shedule1",
"apiVersion": "2015-10-31",
"location": "[resourceGroup().location]",
"dependsOn": [
"[concat('Microsoft.Automation/automationAccounts/', 'AutomationDev')]",
"[variables('name')]"
],
"properties": {
"description": "VM Patch Automation Schedule",
"startTime": "06:00PM",
"expiryTime": "",
"isEnabled": true,
"interval": 1,
"frequency": "Week",
"timeZone": "UTC",
"advancedSchedule": {
"weekDays": [
"Monday"
]
}
}
}
]
}
]
Second try here i don't get errors but the shedule is not connected to the runbook
- I added "runbook": "variables('name')", to the shedule properties
third try (here i get errors that my dependes on is not right configured
i tried to add the shedule block inside a resource value of the runbook like this
{
"name": "[variables('name')]",
"type": "runbooks",
"apiVersion": "2015-01-01-preview",
"location": "[resourceGroup().location]",
"dependsOn": [
"[concat('Microsoft.Automation/automationAccounts/', 'AutomationDev')]"
],
"properties": {
"runbookType": "PowerShell",
"logProgress": false,
"logVerbose": true,
"publishContentLink": {
"uri": "[variables('url')]",
"version": "[variables('version')]"
}
},
"resources": [
{
"comments": "",
"type": "schedules",
"name": "shedule1",
"apiVersion": "2015-10-31",
"location": "[resourceGroup().location]",
"dependsOn": [
"[concat('Microsoft.Automation/automationAccounts/', 'AutomationDev' , variables('name'))]",
],
"properties": {
"description": "VM Patch Automation Schedule",
"runbook": "variables('name')",
"startTime": "06:00PM",
"expiryTime": "",
"isEnabled": true,
"interval": 1,
"frequency": "Week",
"timeZone": "UTC",
"advancedSchedule": {
"weekDays": [
"Monday"
]
}
}
}
]
}
The error i got is as followed:
New-AzureRmResourceGroupDeployment : 16:43:44 - Error: Code=InvalidTemplate; Message=Deployment template validation fai
led: 'The resource '/subscriptions/xxxxxxxx/resourceGroups/xxxx/providers/Microsoft.Automa
tion/automationAccounts/AutomationDev/runbooks/StartAllVM/schedules/shedule1' at line '54' and column '17' doesn't depe
nd on parent resource '/subscriptions/xxxxxxxx/resourceGroups/xxx/providers/Microsoft.Aut
omation/automationAccounts/AutomationDev/runbooks/StartAllVM'. Please add dependency explicitly using the 'dependsOn' s
yntax. Please see https://aka.ms/arm-template/#resources for usage details.'.
I have no clue which option is the right one, i think my third try is the right way to add a shedule to a runbook but i can't seem to find the right way to use the right depends on
[Edit]
Like the answers mentioned my depends on structure was not good , after I changed this I keep getting following error. And I am looking some time now for a solution but can't seem to find which resource they are mentioning that is missing
I used following depends on :
"[resourceId('Microsoft.Automation/automationAccounts/runbooks', 'AutomationDev' , variables('name'))]"
And got this error.
New-AzureRmResourceGroupDeployment : 9:03:47 - Resource Microsoft.Automation/automationAccounts/runbooks/schedules 'AutomationDev/StartAllVM/shedule1' failed with message '{
"error": {
"code": "BadRequest",
"message": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n<head>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>\
r\n<title>404 - File or directory not found.</title>\r\n<style type=\"text/css\">\r\n<!--\r\nbody{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}\r\nfieldset{padding:0 15px 10px 15px;} \r\nh1{font-size:2.4em;margin:0;color:
#FFF;}\r\nh2{font-size:1.7em;margin:0;color:#CC0000;} \r\nh3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} \r\n#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:\"trebuchet MS\", Verdana, sans-serif;color:#FFF;\r\nbackground-color:#555555;}\r\n#cont
ent{margin:0 0 0 2%;position:relative;}\r\n.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}\r\n-->\r\n</style>\r\n</head>\r\n<body>\r\n<div id=\"header\"><h1>Server Error</h1></div>\r\n<div id=\"content\">\r\n <div class=\"con
tent-container\"><fieldset>\r\n <h2>404 - File or directory not found.</h2>\r\n <h3>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</h3>\r\n </fieldset></div>\r\n</div>\r\n</body>\r\n</html>\r\n"
}
I know this question was asked a while ago, but I just worked out how to do this for myself and thought I'd post in case it can help anyone else:
Adding a schedule block inside the template will create the schedule but not connect it to the runbook. To connect the two together, you have to create a job schedule as well.
The steps I took to fix this are as follows:
1. Add the runbook block as a child resource of the Automation Account
2. Add the schedule block as a child resource of the Automation Account (not as a child of the runbook - this is what threw the last error)
3. Add a job schedule block as a child resource of the Automation Account, and pass in the name of the runbook and the name of the schedule:
{
"name": "string",
"type": "Microsoft.Automation/automationAccounts/jobSchedules",
"apiVersion": "2015-10-31",
"properties": {
"schedule": {
"name": "string"
},
"runbook": {
"name": "string"
}
}
}
Obviously you might need to mess around a bit more to get yours working properly but these are the general steps I took :)
-NOTE- don't forget to add dependencies where necessary (e.g. job schedule will depend on the runbook and the schedule already existing)
References:
jobSchedules
Dependencies
Your depends on should be:
"dependsOn": [
"[concat('Microsoft.Automation/automationAccounts/', 'AutomationDev/runbooks/' , variables('name'))]",
],
Alternatively, you can use resourceId() function, which gives a more readable result:
"dependsOn": [
"[resourceId('Microsoft.Automation/automationAccounts/runbooks', 'AutomationDev' , variables('name'))]",
]
with resourceId you can, also, construct resourceId for resources in other subscriptions \ resourcegroups easily.
resourceId([subscriptionId], [resourceGroupName], resourceType, resourceName1, [resourceName2]...)
https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-functions-resource#resourceid
Using Bicep this is a lot simpler.
Create a schedules.bicep file with the following content:
param guidValue string = newGuid()
var aaName = 'your-automation-account-name'
var runbookName = 'your-runbook-name'
var scheduleName = 'the-desired-schedule-name'
var scheduleFullName = '${aaName}/${scheduleName}'
var scheduleAssignment = '${aaName}/${guidValue}'
resource schedule 'Microsoft.Automation/automationAccounts/schedules#2020-01-13-preview' = {
name: scheduleFullName
properties: {
frequency: 'Day'
interval: any(6)
startTime: '2021-10-10'
}
}
resource jobSchedule 'Microsoft.Automation/automationAccounts/jobSchedules#2020-01-13-preview' = {
name: scheduleAssignment
properties: {
runbook: {
name: runbookName
}
schedule: {
name: scheduleName
}
}
}
Then using Azure CLI just run az deployment group create -f schedules.bicep -g your-resourcegroup-name.
Note: I was referencing an existing Automation Account and Runbook but you could add those resources to the template as well. Also to generate the classic JSON ARM Templates you could run az bicep build -f schedules.bicep.

Resources