This commit is contained in:
Matt Carlson 2018-11-01 22:32:56 -07:00
Родитель 6c1c0ff1d3
Коммит c9803e1213
8 изменённых файлов: 1695 добавлений и 10 удалений

Просмотреть файл

@ -0,0 +1,760 @@
{
"ConfigFileVersion": "1.3",
"ApiVersion": "2015-03-20",
"Alerts": [
{
"AlertName": "High CPU Usage",
"AlertGuid": "8a9b0a3b-5f17-4a55-8132-0fe6dcbf968f",
"Tags": ["Core"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - High CPU Usage",
"Query": "let _maxValue = 85; let _timeWindow = 4h; let _AvgCpu = Perf | where TimeGenerated >= ago(_timeWindow) | where CounterName == \"% Processor Time\" and InstanceName =~ \"_Total\" | summarize mtgPerf=max(TimeGenerated), CounterValue=round(avg(CounterValue)), SampleCount=count(CounterValue) by Computer, InstanceName, CounterName, ObjectName; _AvgCpu | where CounterValue > _maxValue | project Computer , ObjectName , CounterName , InstanceName , TimeGenerated=mtgPerf , CounterValue , AlertType_s = \"Sustained High CPU Utilization\" , Severity = 4 , SeverityName_s = \"WARNING\" , AffectedCI_s = strcat(Computer, \"/CPUPercent/\", InstanceName) , AlertTitle_s = strcat(Computer, \": Sustained High CPU Utilization\") , AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nAverage CPU Utilization: \", CounterValue, \"%\\r\\nSample Period: Last \", _timeWindow, \"\\r\\nSample Count: \", SampleCount, \"\\r\\nAlert Threshold: > \", _maxValue, \"%\")",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 240,
"Active": "true"
},
"AlertDefinition": {
"Name": "High CPU Usage",
"Description": "Triggers an alert for a high CPU usage condition",
"Version": "1",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - High CPU Usage"
}
}
},
{
"AlertName": "Low Disk Space Windows - Critical",
"AlertGuid": "844d2068-65ea-45d0-98d0-44e34a0548c6",
"Tags": ["Core"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - Low Disk Space Windows",
"Query": "let _minValue = 10; Perf | where TimeGenerated >= ago(1h) | where CounterValue <= _minValue | where CounterName == \"% Free Space\" and InstanceName in (\"C:\", \"E:\", \"F:\", \"G:\") | summarize mtgPerf=max(TimeGenerated), CounterValue=max(CounterValue) by Computer, InstanceName, CounterName, ObjectName, DriveLetter=replace(@\"(\\w).\",@\"\\1\", InstanceName) | join kind=inner ( Heartbeat | where OSType == \"Windows\" | summarize max(TimeGenerated) by Computer ) on Computer | project Computer , ObjectName , CounterName , InstanceName , TimeGenerated=mtgPerf , round(CounterValue) , DriveLetter , AlertType_s = \"Windows Low Disk Space\" , Severity = 3 , SeverityName_s = \"WARNING\" , AffectedCI_s = strcat(Computer, \"/\", DriveLetter) , AlertTitle_s = strcat(Computer, \": Low Disk Space on Drive \", DriveLetter) , AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nDrive Letter: \", DriveLetter, \"\\r\\nPercent Free Space: \", round(CounterValue), \"%\\r\\nAlert Threshold: <= \", _minValue, \"%\")",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 35,
"Active": "true"
},
"AlertDefinition": {
"Name": "Low Disk Space Windows",
"Description": "Triggers an alert for a low disk space condition",
"Version": "1",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - Low Disk Space Windows"
}
}
},
{
"AlertName": "Low Memory",
"AlertGuid": "1fcf8156-fcca-45d2-be45-aca07b90aee8",
"Tags": ["Core"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - Low Memory",
"Query": "let _minAvailableMB = 1024;\nlet _sampleInterval = 4h;\nlet _linuxMem = Perf\n| where TimeGenerated >= ago(_sampleInterval)\n| where CounterName == \"Available MBytes Memory\"\n| summarize mtgPerf=max(TimeGenerated), CounterValue=avg(CounterValue), SampleCount=count(CounterValue) by Computer\n| join kind=inner\n(\n Heartbeat\n | where OSType == \"Linux\"\n | summarize max(TimeGenerated) by Computer\n)\non Computer\n| project Computer, mtgPerf, AvailableMBytes=round(CounterValue), SampleCount;\nlet _windowsMem = Perf\n| where TimeGenerated >= ago(_sampleInterval)\n| where CounterName == \"Available MBytes\"\n//and ObjectName == \"Logical Disk\"\n\n//and InstanceName matches regex \"/.*\"\n| summarize mtgPerf=max(TimeGenerated), CounterValue=avg(CounterValue), SampleCount=count(CounterValue) by Computer\n| join kind=inner\n(\n Heartbeat\n | where OSType == \"Windows\"\n | summarize max(TimeGenerated) by Computer\n)\non Computer\n| project Computer, mtgPerf, AvailableMBytes=round(CounterValue), SampleCount;\n_linuxMem\n| union _windowsMem\n| where AvailableMBytes < _minAvailableMB\n| project Computer , TimeGenerated=mtgPerf , CounterValue=AvailableMBytes , AlertType_s = \"Low Available Memory\" , Severity = 4 , SeverityName_s = \"WARNING\" , AffectedCI_s = strcat(Computer, \"/FreeMemoryMB/\") , AlertTitle_s = strcat(Computer, \": Low Available Memory\") , AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nAverage Free Memory: \", AvailableMBytes, \" MB\\r\\nSample Period: Last \", _sampleInterval, \"\\r\\nSample Count: \", SampleCount, \"\\r\\nAlert Threshold: < \", _minAvailableMB, \" MB\")",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 240,
"Active": "true"
},
"AlertDefinition": {
"Name": "Low Memory",
"Description": "Triggers an alert for a low memory condition",
"Version": "1",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - Low Memory"
}
}
},
{
"AlertName": "NTFS - File System Corrupt",
"AlertGuid": "bb8527b1-6152-4d28-be04-c3d81cf98407",
"Tags": ["Core"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - NTFS - File System Corrupt",
"Query": "Event | where EventLog == \"System\" and Source == \"DISK\" or Source == \"Ntfs\" and EventID == 55 | project Computer, TimeGenerated, AlertType_s = \"NTFS - File System Corrupt\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = Computer, AlertTitle_s = strcat(Computer, \": NTFS - File System Corrupt\"), AlertDetails_s = strcat(\"Event Description:\\r\\n\", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "NTFS - File System Corrupt",
"Description": "Core monitoring alert for monitoring disk",
"Version": "1",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - NTFS - File System Corrupt"
}
}
},
{
"AlertName": "Unexpected shutdown",
"AlertGuid": "39128bb3-9a64-4d81-bc36-58be5e101514",
"Tags": ["Core"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - Unexpected shutdown",
"Query": "Event | where EventLog == \"System\" and EventID == 6008 | project Computer, TimeGenerated, AlertType_s = \"Unexpected shutdown\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer), AlertTitle_s = strcat(Computer, \": Unexpected Shutdown\"), AlertDetails_s = strcat(\"Multiple shutdowns detected in the past 24 hours\\r\\nEventID: 6008\\r\\nEvent Description: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 1440,
"QueryTimeSpan": 1440,
"Active": "true"
},
"AlertDefinition": {
"Name": "Unexpected shutdown",
"Version": "1",
"Description": "Unexpected shutdown monitoring from core monitoring",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 1
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - Unexpected shutdown"
}
}
},
{
"AlertName": "HP Windows (SNMP) Power sub system degraded or failed",
"AlertGuid": "c40aab23-0622-4648-9a67-6118858bdbd5",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Power sub system degraded or failed",
"Query": "Event | where EventLog == \"System\" | where EventID == 1103 or EventID == 1128 or EventID == 1126 or EventID == 1124 or EventID == 1125 or EventID == 1184 | where RenderedDescription contains \"System Information Agent: Health\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Power sub system degraded or failed\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Power sub system degraded or failed with Event ID \", EventID), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Power sub system degraded or failed",
"Description": "Power sub system degraded or failed. The fault tolerant power supply has degraded, failed or lost redundancy.",
"Version": "1",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - HP Windows (SNMP) Power sub system degraded or failed"
}
}
},
{
"AlertName": "HP Windows (SNMP) Fan degraded",
"AlertGuid": "804809b2-8cac-4d72-b186-ecd40f59ed95",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Fan degraded",
"Query": "Event | where EventLog == \"System\" | where Source == \"Server Agents\" | where EventID == 1131 or EventID == 1129 or EventID == 1086 | where RenderedDescription contains \"CPQHLTH.MIB\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Fan degraded\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Fan degraded with Event ID \", EventID), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Fan degraded",
"Description": "Fan degraded. A fault tolerant fan or system fan has been degraded.",
"Version": "1",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - HP Windows (SNMP) Fan degraded"
}
}
},
{
"AlertName": "HP Windows (SNMP) Rack Enclosure Fan Failed or Degraded",
"AlertGuid": "73032be3-1f4e-44a4-88be-ca25b797b1bc",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Rack Enclosure Fan Failed or Degraded",
"Query": "Event | where EventID == 1150 or EventID == 1151 | where RenderedDescription contains \"CPQRACK.MIB\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Rack Enclosure Fan Failed or Degraded\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Rack Enclosure Fan Failed or Degraded with Event ID\", EventID), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Rack Enclosure Fan Failed or Degraded",
"Version": "1",
"Description": "Rack fans have failed.",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - HP Windows (SNMP) Rack Enclosure Fan Failed or Degraded"
}
}
},
{
"AlertName": "HP Windows (SNMP) Drive Array Physical Drive degraded",
"AlertGuid": "eca68326-ebc4-490d-b33b-071af8380e81",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Drive Array Physical Drive degraded",
"Query": "Event | where EventID == 1202 or EventID == 1203 or EventID == 1216 | where RenderedDescription contains \"CPQIDA.MIB\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Drive Array Physical Drive degraded\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Drive Array Physical Drive degraded with Event ID \", EventID), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Drive Array Physical Drive degraded",
"Version": "1",
"Description": "The drive array physical drive has degraded.",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - HP Windows (SNMP) Drive Array Physical Drive degraded"
}
}
},
{
"AlertName": "HP Windows (SNMP) Drive Array Logical Drive Status is readyForRebuild",
"AlertGuid": "372ffd1b-2a78-4ef4-b801-2c902bc8d3c1",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Drive Array Logical Drive Status is readyForRebuild",
"Query": "Event | where EventLog == \"System\" | where EventID == 1200 | where Source == \"Storage Agents\" | where RenderedDescription contains \"new status of 6\" and RenderedDescription contains \"CPQIDA.MIB\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Drive Array Logical Drive Status is readyForRebuild\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID, \"/readyForRebuild\"), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Drive Array Logical Drive Status is readyForRebuild\"), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Drive Array Logical Drive Status is readyForRebuild",
"Version": "1",
"Description": "The drive array logical drive status has changed to 'readyForRebuild'",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert- HP Windows (SNMP) Drive Array Logical Drive Status is readyForRebuild"
}
}
},
{
"AlertName": "HP Windows (SNMP) Drive Array Logical Drive Status is failed",
"AlertGuid": "749aee97-1666-4635-8f88-38afd598e9b5",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Drive Array Logical Drive Status is failed",
"Query": "Event | where EventLog == \"System\" | where EventID == 1200 | where Source == \"Storage Agents\" | where RenderedDescription contains \"new status of 3\" and RenderedDescription contains \"CPQIDA.MIB\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Drive Array Logical Drive Status is failed\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID, \"/failed\"), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Drive Array Logical Drive Status is failed\"), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Drive Array Logical Drive Status is failed",
"Version": "1",
"Description": "The drive array logical drive status has changed to 'failed'",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 0
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - HP Windows (SNMP) Drive Array Logical Drive Status is failed"
}
}
},
{
"AlertName": "HP Windows (SNMP) Memory degraded",
"AlertGuid": "c1446d74-f632-49eb-b426-0e536386cfc6",
"Tags": ["Physical,HP"],
"SavedSearch": {
"Category": "Core",
"DisplayName": "Alert - HP Windows (SNMP) Memory degraded",
"Query": "Event | where EventLog == \"System\" | where Source == \"Server Agents\" | where EventID == 1025 or EventID == 1026 or EventID == 1027 or EventID == 1028 or EventID == 1031 or EventID == 1071 or EventID == 1035 or EventID == 1039 | where RenderedDescription contains \"CPQHLTH.MIB\" | project Computer, TimeGenerated, AlertType_s = \"HP Windows (SNMP) Memory degraded\", Severity = 4, SeverityName_s = \"WARNING\", AffectedCI_s = strcat(Computer, \"/EventId-\", EventID), AlertTitle_s = strcat(Computer, \": HP Windows (SNMP) Memory degraded with Event ID \", EventID), AlertDetails_s = strcat(\"Computer: \", Computer, \"\\r\\nEvent ID: \", EventID, \"\\r\\nRenderedDescription: \", RenderedDescription)",
"Version": "1"
},
"Schedule": {
"Interval": 30,
"QueryTimeSpan": 30,
"Active": "true"
},
"AlertDefinition": {
"Name": "HP Windows (SNMP) Memory degraded",
"Version": "1",
"Description": "Memory degraded. Advanced Memory Protection has detected a memory fault.",
"Severity": "critical",
"Type": "Alert",
"Threshold": {
"Operator": "gt",
"Value": 1
},
"AzNsNotification": {
"GroupIds": ["/subscriptions/subscrname/resourcegroups/resourcegrp/providers/microsoft.insights/actiongroups/samplecoreactiongroup"],
"CustomEmailSubject": "Alert - HP Windows (SNMP) Memory degraded"
}
}
}
],
"Events": [
{
"EventLogName": "Application",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-ClusterAwareUpdating/Admin",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-Desired State Configuration/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-FailoverClustering-CsvFs/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-FailoverClustering/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-GroupPolicy/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-Config/Admin",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-High-Availability/Admin",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-Integration/Admin",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-Shared-VHDX/Operational",
"Error": true,
"Warning": true,
"Information": false
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-SynthNic/Admin",
"Error": true,
"Warning": true,
"Information": false
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-VMMS/Admin",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-VMMS/Networking",
"Error": true,
"Warning": true,
"Information": false
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-VMMS/Storage",
"Error": true,
"Warning": true,
"Information": false
},
{
"EventLogName": "Microsoft-Windows-Hyper-V-Worker-Admin",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-NetworkProfile/Operationa",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-SMBServer/Operational",
"Error": true,
"Warning": true,
"Information": false
},
{
"EventLogName": "Microsoft-Windows-TaskScheduler/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Microsoft-Windows-VHDMP/Operational",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "MSNIPAK",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Operations Manager",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "Setup",
"Error": true,
"Warning": true,
"Information": true
},
{
"EventLogName": "System",
"Error": true,
"Warning": true,
"Information": true
}
],
"PerformanceCounters": [
{
"ObjectName": "Cluster CSV File System",
"CounterName": "IO Read Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Cluster CSV File System",
"CounterName": "IO Read Latency",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Cluster CSV File System",
"CounterName": "IO Reads/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Cluster CSV File System",
"CounterName": "IO Write Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Cluster CSV File System",
"CounterName": "IO Write Latency",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Cluster CSV File System",
"CounterName": "IO Writes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Hyper-V Dynamic Memory VM",
"CounterName": "Guest Visible Physical Memory",
"InstanceName": "*",
"intervalSeconds": 1800
},
{
"ObjectName": "Hyper-V Dynamic Memory VM",
"CounterName": "Physical Memory",
"InstanceName": "*",
"intervalSeconds": 1800
},
{
"ObjectName": "Hyper-V Hypervisor Logical Processor",
"CounterName": "% Total Run Time",
"InstanceName": "*",
"intervalSeconds": 60
},
{
"ObjectName": "Hyper-V Hypervisor Virtual Processor",
"CounterName": "% Total Run Time",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Hyper-V Virtual Storage Device",
"CounterName": "Read Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Hyper-V Virtual Storage Device",
"CounterName": "Read Operations/Sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Hyper-V Virtual Storage Device",
"CounterName": "Write Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Hyper-V Virtual Storage Device",
"CounterName": "Write Operations/Sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "% Free Space",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Avg. Disk sec/Read",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Avg. Disk sec/Transfer",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Avg. Disk sec/Write",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Current Disk Queue Length",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Disk Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Disk Read Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Disk Reads/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Disk Transfers/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Disk Write Bytes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Disk Writes/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "LogicalDisk",
"CounterName": "Free Megabytes",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Memory",
"CounterName": "% Committed Bytes In Use",
"InstanceName": "*",
"intervalSeconds": 1800
},
{
"ObjectName": "Memory",
"CounterName": "Available MBytes",
"InstanceName": "*",
"intervalSeconds": 1800
},
{
"ObjectName": "Memory",
"CounterName": "Commit Limit",
"InstanceName": "*",
"intervalSeconds": 1800
},
{
"ObjectName": "Memory",
"CounterName": "Committed Bytes",
"InstanceName": "*",
"intervalSeconds": 1800
},
{
"ObjectName": "Network Adapter",
"CounterName": "Bytes Received/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Network Adapter",
"CounterName": "Bytes Sent/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Network Interface",
"CounterName": "Bytes Total/sec",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "NUMA Node Memory",
"CounterName": "Available MBytes",
"InstanceName": "_Total",
"intervalSeconds": 1800
},
{
"ObjectName": "NUMA Node Memory",
"CounterName": "Total MBytes",
"InstanceName": "_Total",
"intervalSeconds": 1800
},
{
"ObjectName": "Processor",
"CounterName": "% Processor Time",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "Processor",
"CounterName": "% Processor Time",
"InstanceName": "_Total",
"intervalSeconds": 60
},
{
"ObjectName": "System",
"CounterName": "Processor Queue Length",
"InstanceName": "*",
"intervalSeconds": 300
},
{
"ObjectName": "TCPv4",
"CounterName": "Connections Established",
"InstanceName": "*",
"intervalSeconds": 300
}
]
}

Просмотреть файл

@ -0,0 +1,764 @@
<#
.SYNOPSIS
The Core Monitoring Toolkit automates the deployment of an example set of log alerts to Azure Monitor Log Analytics.
.DESCRIPTION
The Core Monitoring Toolkit automates the deployment of an example set of log alerts to Azure Monitor Log Analytics.
The toolkit consists of configuration file containing log alert definitions and a script that deploys the alerts.
.Parameter SubscriptionID
Specifies the Azure Subscription ID for the workspace where the alerts will be created.
.Parameter WorkspaceName
Specifies the name for the log analytics workspace where the alerts will be created.
.Parameter ResourceGroup
Specifies the resource group of the workspace where the alerts will be created.
.Parameter Location
Specifies the location of the workspace where the alerts will be created.
.Parameter NewActionGroupName
Specifies the name of the action group to be added to all alerts created by this toolkit. Default is '<workspacename>-email-ag1', where workspacename is the name of the workspace.
.Parameter ActionGroupShortName
Specifies the short name (12 char max, no spaces) of the action group to be added to all alerts created by this toolkit. Default is 'CoreAlert'.
.Parameter AlertEmailAddress
Specifies the email address that will be configured for the action group to be added to all alerts created by this toolkit.
.Parameter ExistingActionGroupName
Specifies the name of an existing action group to be added to all alerts created by this toolkit.
.Parameter ConfigPath
Specifies the path to the JSON file containing the alert configurations. Default is '.\DefaultAlertConfig.json'.
.EXAMPLE
.\New-CoreAlerts.ps1 -SubscriptionId 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' -WorkspaceName 'alertsWorkspace' -ResourceGroup 'alertsRG' -Location 'East US'
This command will run the Core Monitoring Toolkit script with the provided parameters.
.EXAMPLE
.\New-CoreAlerts.ps1
This command will run the Core Monitoring Toolkit script and prompt the user for required parameters.
.EXAMPLE
.\New-CoreAlerts.ps1 -SubscriptionId 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' -ExistingActionGroupName 'useractiongroupname' -WorkspaceName 'alertsWorkspace' -ResourceGroup 'alertsRG' -Location 'East US'
This command will run the Core Monitoring Toolkit script with the provided parameters, adding the existing action group named 'useractiongroupname' to all alerts created by the toolkit.
.LINK
https://github.com/Microsoft/manageability-toolkits
.Notes
NAME: New-CoreAlerts
AUTHOR(s): Arun Kumar Rajendra <arunkra@microsoft.com>, Matt Carlson <macarlso@microsoft.com>
LASTEDIT: 10/31/2018
KEYWORDS: OMS, Log Analytics, Alerts, Core Alerts, Log Alerts, Azure Monitor
#>
# TODO: Add parameter sets for action group parameters
param (
[Parameter(Mandatory=$true)]
[string]$SubscriptionId,
[Parameter(Mandatory=$true)]
[string]$WorkspaceName,
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,
[Parameter(Mandatory=$true)]
[string]$Location,
[Parameter(Mandatory=$false)]
[string]$NewActionGroupName,
[Parameter(Mandatory=$false)]
[string]$ActionGroupShortName = "CoreAlert",
[Parameter(Mandatory=$false)]
[string]$ExistingActionGroupName,
[Parameter(Mandatory=$false)]
[string]$AlertEmailAddress,
[Parameter(Mandatory=$false)]
[string]$ConfigPath = ".\DefaultAlertConfig.json"
)
# Create a new action group
function New-ActionGroup
{
param
(
[Parameter(Mandatory=$true)]
[string]$SubscriptionID,
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,
[Parameter(Mandatory=$true)]
[string]$AlertEmailAddress,
[Parameter(Mandatory=$true)]
[string]$ActionGroupName,
[Parameter(Mandatory=$true)]
[string]$ActionGroupShortName
)
try
{
<#
Extract the user name from the email address and build the email action name from it.
e.g.
If Email = emailaction@microsoft.com
$emailActionName = "email-emailaction"
#>
$emailUser = $AlertEmailAddress.Split("@")[0]
$emailActionName = "email-$emailUser"
Write-Verbose "Variable AlertEmailAddress = $AlertEmailAddress"
Write-Verbose "Variable emailUser = $emailUser"
Write-Verbose "Variable emailActionName = $emailActionName"
# Create the resource ID and properties to use when creating the action group using New-AzureRmResource cmdlet.
$ResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/microsoft.insights/actionGroups/$ActionGroupName"
$GroupProperties = [PSCustomObject]@{
groupShortName = $ActionGroupShortName
enabled = $true
emailReceivers = @([pscustomobject]@{name = $emailActionName;emailAddress = $AlertEmailAddress})
}
# Create the action group
New-AzureRmResource -Location "Global" -ResourceId $ResourceId -Properties $GroupProperties -ApiVersion "2017-04-01" -Force
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Error "Error occurred while creating action groups: $ErrorMessage"
Exit 1
}
}
# Create a new saved search
function New-AlertSavedSearch
{
param
(
[Parameter(Mandatory=$true)]
[string]$SubscriptionID,
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,
[Parameter(Mandatory=$true)]
[string]$WorkspaceName,
[Parameter(Mandatory=$true)]
[string]$Apiversion,
[Parameter(Mandatory=$true)]
[string]$SavedSearchId,
[Parameter(Mandatory=$true)]
[PSCustomObject]$Properties
)
Write-Verbose "Creating new alert saved search"
try
{
# Create the resource ID to use when creating the saved search using New-AzureRmResource cmdlet.
$ResourceId = "/subscriptions/$SubscriptionId/resourcegroups/$ResourceGroup/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/savedSearches/$SavedSearchId/"
Write-Verbose "ResourceId: $ResourceId"
Write-Verbose "Saved Search Query: $($Properties.Query)"
# Create the saved search
New-AzureRmResource -ResourceId $ResourceId -Properties $Properties -ApiVersion "2017-03-15-preview" -Force
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Error "Error occurred while creating Saved searches: $ErrorMessage"
Exit 1
}
}
# Create a new schedule for the saved search
function New-AlertSchedule
{
param
(
[Parameter(Mandatory=$true)]
[string]$SubscriptionID,
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,
[Parameter(Mandatory=$true)]
[string]$WorkspaceName,
[Parameter(Mandatory=$true)]
[string]$Apiversion,
[Parameter(Mandatory=$true)]
[string]$SavedSearchId,
[Parameter(Mandatory=$true)]
$BearerToken,
[Parameter(Mandatory=$true)]
[string]$ScheduleId,
[Parameter(Mandatory=$true)]
[PSCustomObject]$Properties
)
Write-Verbose "Creating new alert schedule"
try
{
# Get json in the format of "{'properties': { 'Interval': 10, 'QueryTimeSpan':10, 'Active':'true' }"
$scheduleJson = [PSCustomObject]@{properties = $Properties} | ConvertTo-Json
# Build the header for the API call
$header = @{
'Content-Type'='application\json'
'Authorization'= $BearerToken
}
# Build the URI for the API call
$uri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups/$ResourceGroup/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/savedSearches/$SavedSearchId/schedules/$($ScheduleId)?api-version=$($Apiversion)"
Write-Verbose "URI: $uri"
Write-Verbose "Json payload: $scheduleJson"
# Create the alert schedule
Invoke-RestMethod -Uri $uri -Headers $header -Method Put -Body $scheduleJson -ContentType "application/json"
<#
#Used only for New-AzureRmResource method which works, but is currently not supported.
$ResourceId = "/subscriptions/$SubscriptionId/resourcegroups/$ResourceGroup/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/savedSearches/$SavedSearchId/schedules/$ScheduleId/"
$scheduleProperties = [PSCustomObject]@{
Interval = 10
QueryTimeSpan = 10
Active = "true"
}
# Using the API directly for now since nested resources is not supposed to work with this command. This does work though so we re-enable at a later date
New-AzureRmResource -ResourceId $ResourceId -Properties $scheduleProperties -ApiVersion $Apiversion -Force
#>
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Error "Error occurred while creating Schedule: $ErrorMessage"
Exit 1
}
}
# Create a new action for a schedule, completing the alert configuration
function New-AzureAlert
{
param
(
[Parameter(Mandatory=$true)]
[string]$SubscriptionID,
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,
[Parameter(Mandatory=$true)]
[string]$ActionResourceGroup,
[Parameter(Mandatory=$true)]
[string]$WorkspaceName,
[Parameter(Mandatory=$true)]
[string]$Apiversion,
[Parameter(Mandatory=$true)]
[string]$SavedSearchId,
[Parameter(Mandatory=$true)]
[string]$ScheduleId,
[Parameter(Mandatory=$true)]
[string]$AlertId,
[Parameter(Mandatory=$true)]
[string]$ActionGroupName,
[Parameter(Mandatory=$true)]
$BearerToken,
[Parameter(Mandatory=$true)]
[PSCustomObject]$Properties
)
Write-Verbose "Creating new alert"
# Build the header for the API call
$header = @{
'Content-Type'='application\json'
'Authorization'= $BearerToken
}
# Build the URI for the API call
$uri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups/$ResourceGroup/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/savedSearches/$SavedSearchId/schedules/$ScheduleId/actions/$($AlertId)?api-version=$($Apiversion)"
# Depth parameter must be large enough so that arrays deeper into the JSON aren't converted to a single line of text.
$alertsJson = [PSCustomObject]@{properties = $Properties} | ConvertTo-Json -Depth 5
# Replace with actual action group, subscription and resource group names.
$alertsJson = $alertsJson.Replace("samplecoreactiongroup", $ActionGroupName)
$alertsJson = $alertsJson.Replace("subscrname", $SubscriptionId)
$alertsJson = $alertsJson.Replace("resourcegrp", $ActionResourceGroup)
Write-Verbose "URI: $uri"
Write-Verbose "Json payload: $alertsJson"
# Create the alert
Invoke-RestMethod -Uri $uri -Headers $header -Method Put -Body $alertsJson -ContentType "application/json"
}
function Update-WorkspaceEventCollection
{
param
(
[Parameter(Mandatory=$true)]
[string]$ResourceGroup,
[Parameter(Mandatory=$true)]
[string]$WorkspaceName,
[Parameter(Mandatory=$true)]
[PSCustomObject]$EventLogConfig
)
# Configure log analytics workspace with specified event log collections
Write-Verbose "Entering function: 'Update-WorkspaceEventCollection'"
Write-Verbose "Resource Group Name: '$ResourceGroup'"
Write-Verbose "Getting current windows event collection configuration from workspace"
$CurrentWindowsEventConfig = Get-AzureRmOperationalInsightsDataSource -WorkspaceName $WorkspaceName -ResourceGroupName $ResourceGroup -Kind WindowsEvent | Select-Object `
Name, `
@{n='EventLogName'; e={ $_.Properties.EventLogName }}, `
@{n='CollectErrors'; e={$_.Properties.EventTypes.EventType -contains 'Error' }}, `
@{n='CollectWarnings'; e={$_.Properties.EventTypes.EventType -contains 'Warning' }}, `
@{n='CollectInformation'; e={$_.Properties.EventTypes.EventType -contains 'Information' }}
#
Write-Verbose "Looping through events from even log configuration"
foreach ( $EventLogItem in $EventLogConfig )
{
Write-Verbose "Processing event '$($EventLogItem.EventLogName)'"
# Create a hashtable to track whether Error, Warning or Information event types should be collected for this event log
$EventArgs = @{}
$EventArgs.Add('EventLogName', $EventLogItem.EventLogName)
if ( $EventLogItem.Error )
{
$EventArgs.Add('CollectErrors', $null)
}
if ( $EventLogItem.Warning )
{
$EventArgs.Add('CollectWarnings', $null)
}
if ( $EventLogItem.Information )
{
$EventArgs.Add('CollectInformation', $null)
}
# Get configuration if this event log is already configured in the log analytics workspace
$ThisEvent = $CurrentWindowsEventConfig | Where-Object { $_.EventLogName -eq $EventLogItem.EventLogName }
# Enable the event log collection if it is not already configured.
if ( -not $ThisEvent )
{
Write-Verbose "Event log not configured";
# Build the name in the format log analytics expects
$NewDataSourceName = "DataSource_WindowsEvent_$( (New-Guid).ToString() )"
Write-Verbose $NewDataSourceName
# Configure the event in the specified workspace
New-AzureRmOperationalInsightsWindowsEventDataSource -WorkspaceName $WorkspaceName -ResourceGroupName $ResourceGroup -Name $NewDataSourceName @EventArgs | Out-Null
}
else
{
Write-Verbose "Event log collection already configured"
}
}
Write-Verbose "Exiting function: 'Update-WorkspaceEventCollection'"
}
function Update-WorkspacePerfCollection
{
param
(
[Parameter(Mandatory=$true)]
$Workspace,
[Parameter(Mandatory=$true)]
[PSCustomObject]$PerfCollectionConfig
)
# Configure log analytics workspace with specified performance counter collections
Write-Verbose "Entering function: 'Update-WorkspacePerfCollection'"
Write-Verbose "Getting current windows event collection configuration from workspace"
$CurrentWindowsPerfConfig = Get-AzureRmOperationalInsightsDataSource -Workspace $Workspace -Kind WindowsPerformanceCounter | Select-Object `
Name, `
@{n='ObjectName'; e={ $_.Properties.ObjectName }}, `
@{n='InstanceName'; e={$_.Properties.InstanceName }}, `
@{n='IntervalSeconds'; e={$_.Properties.IntervalSeconds }}, `
@{n='CounterName'; e={$_.Properties.CounterName }}, `
@{n='CollectorType'; e={$_.Properties.CollectorType }}
Write-Verbose "Looping through events from even log configuration"
foreach ( $PerfCollectionItem in $PerfCollectionConfig )
{
Write-Verbose "Processing performance collector '$($PerfCollectionItem.ObjectName)($($PerfCollectionItem.InstanceName))\$($PerfCollectionItem.CounterName)'"
# Create a hashtable to track the ObjectName, InstanceName, IntervalSeconds and CounterName values
$EventArgs = @{}
$EventArgs.Add('ObjectName', $PerfCollectionItem.ObjectName)
$EventArgs.Add('InstanceName', $PerfCollectionItem.InstanceName)
$EventArgs.Add('IntervalSeconds', $PerfCollectionItem.IntervalSeconds)
$EventArgs.Add('CounterName', $PerfCollectionItem.CounterName)
# Get configuration if this performance counter is already configured in the log analytics workspace
$ThisPerfCollector = $CurrentWindowsPerfConfig | Where-Object { ($_.ObjectName -eq $PerfCollectionItem.ObjectName ) -and ($_.CounterName -eq $PerfCollectionItem.CounterName ) -and ($_.CounterName -eq $PerfCollectionItem.CounterName ) }
# Enable the performance counter collection if it is not already configured.
if ( -not $ThisPerfCollector )
{
Write-Verbose "Perf collector not configured";
# Build the name in the format log analytics expects
$NewDataSourceName = "DataSource_PerfCounter_$( (New-Guid).ToString() )"
Write-Verbose $NewDataSourceName
# Configure the event in the specified workspace
New-AzureRmOperationalInsightsWindowsPerformanceCounterDataSource -Workspace $Workspace -Name $NewDataSourceName @EventArgs | Out-Null
}
else
{
Write-Verbose "Perf counter collection already configured"
}
}
Write-Verbose "Exiting function: 'Update-WorkspacePerfCollection'"
}
function Login
{
# Attempt to login to Azure
$needLogin = $true
Try
{
$content = Get-AzureRmContext
if ($content)
{
# Verify there is an active session
$needLogin = ([string]::IsNullOrEmpty($content.Account))
}
}
Catch
{
if ($_ -like "*Login-AzureRmAccount to login*")
{
$needLogin = $true
}
else
{
throw
}
}
if ($needLogin)
{
# Perform the login if needed
Login-AzureRmAccount
}
}
function Get-AzureRmCachedAccessToken
{
# Function found here undet MIT license
# https://gallery.technet.microsoft.com/scriptcenter/Easily-obtain-AccessToken-3ba6e593
$ErrorActionPreference = 'Stop'
if (-not (Get-Module AzureRm.Profile))
{
Import-Module AzureRm.Profile
}
$azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version
# refactoring performed in AzureRm.Profile v3.0 or later
if ($azureRmProfileModuleVersion.Major -ge 3)
{
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
if (-not $azureRmProfile.Accounts.Count)
{
Write-Error "Ensure you have logged in before calling this function."
}
}
else
{
# AzureRm.Profile < v3.0
$azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile
if (-not $azureRmProfile.Context.Account.Count)
{
Write-Error "Ensure you have logged in before calling this function."
}
}
$currentAzureContext = Get-AzureRmContext
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
Write-Debug ("Getting access token for tenant" + $currentAzureContext.Subscription.TenantId)
$token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId)
return $token.AccessToken
}
function Get-BearerToken
{
# Format the bearer token for use in header for API call.
$context = Get-AzureRmContext
$tokenCache = $context.TokenCache
$tenantId = $context.Tenant
$cachedTokens = $tokenCache.ReadItems() `
| Where-Object { $_.TenantId -eq $tenantId } `
| Sort-Object -Property ExpiresOn -Descending
$accessToken = $cachedTokens[0]
$bearerToken = "Bearer " + $accessToken.AccessToken
$bearerToken = ('Bearer {0}' -f (Get-AzureRmCachedAccessToken))
return $bearerToken
}
Write-Host
# Attempt to obtain auth token for Azure API calls
try
{
Login
$token = Get-BearerToken
}
catch
{
Write-Error "There was an error logging into Azure and creating an authentication token. $($_.Exception.Message)"
Exit 1
}
# Verify the ConfigPath parameter contains the path to an actual file.
if (Test-Path $ConfigPath)
{
Write-Verbose "ConfigPath path, '$ConfigPath' is valid"
}
else
{
Write-Error "ConfigPath path, '$ConfigPath' does not exist. Please verify the ConfigPath path and run the command again."
Exit 1
}
# Make sure there are no spaces in action group short name. Need to figure out how to pass spaces in API call.
# The call fails with spaces, but GUI will allow creation with spaces.
if ($ActionGroupShortName.Contains(" "))
{
Write-Error "Parameter ActionGroupShortName cannot contain spaces"
}
# Select subscription
try
{
Select-AzureRmSubscription -SubscriptionId $SubscriptionId -ErrorAction Stop | Out-Null
}
catch
{
Write-Error "Failed to select subscription with error $($_.Exception.Message)"
Exit 1
}
Write-Host "Verifying parameters..."
# Verify Subscription exists. Probably a moot point since we would have failed to login if this was not valid.
try
{
Get-AzureRmSubscription -SubscriptionId $SubscriptionId -ErrorAction Stop | Out-Null
}
catch
{
Write-Error $_.Exception.Message
Exit 1
}
# Verify Resource Group exists. Potential to use ARM templates later to give the option to create as part of toolkit.
try
{
Get-AzureRmResourceGroup -Name $ResourceGroup -ErrorAction Stop | Out-Null
}
catch
{
Write-Error "Failed to find resource group. Please verify resource group exists and try again.`r`n Error: $($_.Exception.Message)"
Exit 1
}
# Verify Workspace. Potential to use ARM templates later to give the option to create as part of toolkit.
try
{
Get-AzureRmOperationalInsightsIntelligencePacks -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -ErrorAction Stop | Out-Null
$workspace = Get-AzureRmOperationalInsightsWorkspace | Where-Object { $_.Name -eq $WorkspaceName; }
}
catch
{
Write-Error "Failed to find workspace. Please verify workspace exists and try again.`r`n Error: $($_.Exception.Message)"
Exit 1
}
# Prompt user if no alert email address was provided.
if (!$AlertEmailAddress -and !$ExistingActionGroupName)
{
$AlertEmailAddress = Read-Host -Prompt "`nEnter the email address to be subscribed for alerts"
}
# Retrieve core monitoring config data from configuration file and convert from JSON to PowerShell object
$alertConfig = (Get-Content $ConfigPath) | ConvertFrom-Json
# API Versions ** under review **
$apiversion = $alertConfig.ApiVersion
if (!$apiversion)
{
Write-Error "API Version not found in the configuration file. Exiting script."
Exit 1
}
# Derive an action group name from the workspace name if none is provided
if (!$NewActionGroupName)
{
$NewActionGroupName = "$($WorkspaceName)-email-ag1"
Write-Verbose "No action group name defined by user. Action group name will be '$NewActionGroupName'"
}
# Verify Action Group provided by user exists. Potential to use ARM templates later to give the option to create as part of toolkit.
Write-Verbose "Verifying action group if provided and set ActionResourceGroup"
if ($ExistingActionGroupName)
{
Write-Verbose "User provided existing action group"
$type = "Microsoft.Insights/ActionGroups"
$actiongroupFindResult = Get-AzureRmResource -ResourceType $type -Name $ExistingActionGroupName
if ($actiongroupFindResult)
{
Write-Verbose "User provided action group found"
$ActionResourceGroup = $actiongroupFindResult.ResourceGroupName
$ActionGroupName = $ExistingActionGroupName
}
else
{
Write-Error "Action group with name '$ExistingActionGroupName' not found in subscription '$SubscriptionId'"
Exit 1
}
}
else
{
Write-Verbose "User did not provide existing action group using NewActionGroupName"
$ActionResourceGroup = $ResourceGroup
$ActionGroupName = $NewActionGroupName
# Creates action group to be used for core monitoring alerts
#TODO: Add error checking
Write-Host "Creating action group..."
$actionGroupCreateResult = New-ActionGroup `
-SubscriptionID $SubscriptionID `
-ResourceGroup $ResourceGroup `
-AlertEmailAddress $AlertEmailAddress `
-ActionGroupName $NewActionGroupName `
-ActionGroupShortName $ActionGroupShortName
Write-Host "Action group with name, '$NewActionGroupName' created successfully"
}
##### Update event and perf collections
Write-Host "Configuring event log collections..."
Update-WorkspaceEventCollection -ResourceGroup $ResourceGroup `
-WorkspaceName $WorkspaceName `
-EventLogConfig $alertConfig.Events
Write-Host "Configuring performance counter collections..."
Update-WorkspacePerfCollection `
-Workspace $workspace `
-PerfCollectionConfig $alertConfig.PerformanceCounters
##### Begin creating alerts
# Loop through alerts in config file and create all necessary components, including saved search, schedule and the alert.
$alertProgressCount = 1
$numAlerts = $alertConfig.Alerts.Count
Write-Host "Beginning creation of $numAlerts alerts..."
foreach ($alert in $alertConfig.Alerts){
# If the alert from the config file has a GUID, use that. Otherwise generate one.
$alertGuid = $alert.AlertGuid
if (!$alertGuid)
{
$alertGuid = [string]"$(New-Guid)"
}
Write-Verbose "AlertGuid: $alertGuid"
$alertDisplayName = $alert.AlertName
Write-Host " -Creating alert $alertProgressCount of $($numAlerts): '$alertDisplayName'"
# Create Saved Searches to be used in Alert configurations
Write-Verbose "Creating Saved Searches..."
$savedSearchResult = New-AlertSavedSearch `
-SubscriptionId $SubscriptionID `
-ResourceGroup $ResourceGroup `
-WorkspaceName $WorkspaceName `
-SavedSearchId $alertGuid `
-ApiVersion $apiversion `
-Properties $alert.SavedSearch
Write-Verbose "Saved Searches created successfully"
# Create Schedules.
Write-Verbose "Creating Schedules..."
$scheduleResult = New-AlertSchedule `
-SubscriptionId $SubscriptionID `
-ResourceGroup $ResourceGroup `
-WorkspaceName $WorkspaceName `
-SavedSearchId $alertGuid `
-ScheduleId $alertGuid `
-BearerToken $token `
-ApiVersion $apiversion `
-Properties $alert.Schedule
Write-Verbose "Schedules created successfully"
# Create alert action
Write-Verbose "Creating alerts..."
$actionResult = New-AzureAlert `
-SubscriptionId $SubscriptionId `
-ResourceGroup $ResourceGroup `
-ActionResourceGroup $ActionResourceGroup `
-WorkspaceName $WorkspaceName `
-SavedSearchId $alertGuid `
-ScheduleId $alertGuid `
-AlertId $alertGuid `
-ActionGroupName $ActionGroupName `
-ApiVersion $apiversion `
-BearerToken $token `
-Properties $alert.AlertDefinition
Write-Verbose "Alerts created successfully.."
$alertProgressCount++
}
Write-Host "Alert creation complete..."
Write-Host "Script exiting..."
Write-Host

167
README.md
Просмотреть файл

@ -1,14 +1,161 @@
#Core Monitoring Tool Kit
1. [Overview](#overview)
1. [Prerequisites](#prerequisites)
1. [Deployment Steps](#deployment-steps)
1. [Alert Components](#alert-components)
1. [Alert Configuration File](#alert-configuration-file)
1. [Script Help](#script-help)
1. [References](#references)
1. [Contributing](#contributing)
# Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
##Overview
The Core Monitoring Toolkit automates the deployment of an example set of log alerts to Azure Monitor Log Analytics. The toolkit consists of configuration file containing log alert definitions and a script that deploys the alerts.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
##Prerequisites
- [AzureRm PowerShell Module installed](https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps?view=azurermps-5.7.0)
- Log Analytics workspace created
- User running the toolkit will need Contributor role on the resource group and workspace
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
##Deployment Steps
1. Download the core monitoring toolkit contents to your local system
1. Navigate to the script directory
1. Run the PowerShell script, **New-CoreAlerts.ps1**, with desired parameters. Minimum suggested parameters shown in the example below.
``` powershell
# Run core monitoring toolkit with email specified.
.\New-CoreAlerts.ps1 `
-SubscriptionID "<subscriptionId>" `
-WorkspaceName "<Log Analytics Workspace Name>" `
-ResourceGroup "<Log Analytics Workspace resource group name>" `
-Location '<Location of workspace and resource group>' `
-AlertEmailAddress "<email address>"
```
**Sample Output:**
![Sample Output With Parameters](/docs/images/sampleOutputWithParams.png)
4. Alternatively you can run the script with no parameters and you will be prompted for the required parameters.
``` powershell
# Run core monitoring toolkit with no parameters
.\New-CoreAlerts.ps1
```
**Sample Output:**
![Sample output with no parameters](/docs/images/sampleOutputNoParams.png)
5. Lastly, the toolkit can use an existing action group.
``` powershell
# Run core monitoring toolkit with an existing action group specified.
.\New-CoreAlerts.ps1 `
-SubscriptionID "<subscriptionId>" `
-WorkspaceName "<Log Analytics Workspace Name>" `
-ResourceGroup "<Log Analytics Workspace resource group name>" `
-Location '<Location of workspace and resource group>' `
-ExistingActionGroupName '<Name of existing action group>'
```
**Sample Output:**
![Sample output with existing action group](/docs/images/sampleOutputExistingActionGroup.png)
6. Once the script completes you will see the alerts in the Azure Portal -> Log Analytics-> Alerts
![Alerts in Azure Portal](/docs/images/portalExample.png)
## Alert Components
The toolkit automates the creation of alerts by creating several different resources and associating them to one another.
**Action Group:**
The action group contains any number of actions that should happen once the alert fires. This could include sending an email or calling a webhook. The Core Monitoring toolkit currently supports just a single email. Additional actions can be added later.
**Saved Search**
The saved search is where the alert query is defined. When the query returns results over a given time period, the alert is fired.
**Schedule**
A saved search can have one or more schedules. The schedule defines how often the search is run and the time interval over which the criteria is identified.
**Alert Action**
Finally, the toolkit creates an alert action. This is associated with the **Saved Search**, **Schedule** and **Action Group** to create the final alert.
More information on how to configure alerts using the REST API can be found here:
https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-api-alerts
## Alert Configuration File
The alert configuration file, **Configure.xml**, contains the alert definitions for Alerts included in the Core Monitoring Toolkit. Alerts can be added or removed from the configuration file before running the script.
Each **Alert** element in the configuration file contains a **Search** and **Email** element.
The **Search** element contains the JSON payload required to create saved search. This is the basis of a log analytics alert. This includes such information as the category and display name, but most importantly the query that will be used to define the criteria for an Alert.
The **Email** element contains the JSON payload required to create the alert and tie it to an action group.
##Script Help
The New-CoreAlerts script supports PowerShell's Get-Help command. To get the most up-to-date information please run the following from within the script directory.
``` powershell
PS C:\Demo> Get-Help .\New-CoreAlerts.ps1 -Full
```
</br>
At the time of this writing:
```
.SYNOPSIS
The Core Monitoring Toolkit automates the deployment of an example set of log alerts to Azure Monitor Log Analytics.
.DESCRIPTION
The Core Monitoring Toolkit automates the deployment of an example set of log alerts to Azure Monitor Log Analytics.
The toolkit consists of configuration file containing log alert definitions and a script that deploys the alerts.
.Parameter SubscriptionID
Specifies the Azure Subscription ID for the workspace where the alerts will be created.
.Parameter WorkspaceName
Specifies the name for the workspace where the alerts will be created.
.Parameter ResourceGroup
Specifies the resource group of the workspace where the alerts will be created.
.Parameter Location
Specifies the location of the workspace where the alerts will be created.
.Parameter NewActionGroupName
Specifies the name of the action group to be added to all alerts created by this toolkit. Default is '<workspacename>-email-ag1', where workspacename is the name of the workspace.
.Parameter ActionGroupShortName
Specifies the short name (12 char max, no spaces) of the action group to be added to all alerts created by this toolkit. Default is 'CoreAlert'.
.Parameter AlertEmailAddress
Specifies the email address that will be configured for the action group to be added to all alerts created by this toolkit.
.Parameter ExistingActionGroupName
Specifies the name of an existing action group to be added to all alerts created by this toolkit.
.Parameter ConfigPath
Specifies the path to the JSON file containing the alert configurations. Default is '.\DefaultAlertConfig.json'.
.EXAMPLE
.\New-CoreAlerts.ps1 -SubscriptionId 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' -WorkspaceName 'alertsWorkspace' -ResourceGroup 'alertsRG' -Location 'East US'
This command will run the Core Monitoring Toolkit script with the provided parameters.
.EXAMPLE
.\New-CoreAlerts.ps1
This command will run the Core Monitoring Toolkit script and prompt the user for required parameters.
.EXAMPLE
.\New-CoreAlerts.ps1 -SubscriptionId 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' -ExistingActionGroupName 'useractiongroupname' -WorkspaceName 'alertsWorkspace' -ResourceGroup 'alertsRG' -Location 'East US'
This command will run the Core Monitoring Toolkit script with the provided parameters, adding the existing action group named 'useractiongroupname' to all alerts created by the toolkit.
.LINK
https://github.com/Microsoft/manageability-toolkits
.Notes
NAME: New-CoreAlerts
AUTHOR(s): Arun Kumar Rajendra <arunkra@microsoft.com>, Matt Carlson <macarlso@microsoft.com>
LASTEDIT: 10/31/2018
KEYWORDS: OMS, Log Analytics, Alerts, Core Alerts, Log Alerts, Azure Monitor
```
##References
**Create and manage alert rules in Log Analytics with REST API**
https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-api-alerts
##Contributing
[Contribution guidelines for this project](docs/CONTRIBUTING.md)

14
docs/CONTRIBUTING.md Normal file
Просмотреть файл

@ -0,0 +1,14 @@
# Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

Двоичные данные
docs/portalExample.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 157 KiB

Двоичные данные
docs/sampleOutputExistingActionGroup.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 106 KiB

Двоичные данные
docs/sampleOutputNoParams.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 106 KiB

Двоичные данные
docs/sampleOutputWithParams.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 109 KiB