Azure Monitor Baseline Alerts
Download AlertsGlossaryGitHubGitHub IssuesToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeBack to homepage

machines

NameTypeDescription
Hybrid Machine Available Memory PercentageLogLog Alert for Hybrid Machine Available Memory Percentage
Hybrid Machine Data Disk Free Space Percentage AlertLogLog Alert for Hybrid Machine Data Disk Free Space Percentage
Hybrid Machine Data Disk Read Latency AlertLogLog Alert for Hybrid Machine Data Disk Read Latency
Hybrid Machine Data Disk Write Latency AlertLogLog Alert for Hybrid Machine Data Disk Write Latency (ms)
Hybrid Machine Heartbeat AlertLogLog Alert for Hybrid Machine Heartbeat
Hybrid Machine Network Read AlertLogLog Alert for Hybrid Machine Network Read (bytes/sec)
Hybrid Machine Network Write AlertLogLog Alert for Hybrid Machine Network Write (bytes/sec)
Hybrid Machine OS Disk Free Space PercentageLogLog Alert for Hybrid Machine OS Disk Free Space Percentage
Hybrid Machine OS Disk Read Latency AlertLogLog Alert for Hybrid Machine Data OS Read Latency (ms)
Hybrid Machine OS Disk Write Latency (ms)LogLog Alert for Hybrid Machine OS Disk Write Latency (ms)
Hybrid Machine Processor Utilization PercentageLogLog Alert for Hybrid Machine Processor Utilization Percentage

Dashboards:

Click a tab to view the dashboard template

{
  "__inputs": [],
  "__elements": {},
  "__requires": [
    {
      "type": "panel",
      "id": "bargauge",
      "name": "Bar gauge",
      "version": ""
    },
    {
      "type": "grafana",
      "id": "grafana",
      "name": "Grafana",
      "version": "9.5.12"
    },
    {
      "type": "datasource",
      "id": "grafana-azure-monitor-datasource",
      "name": "Azure Monitor",
      "version": "1.0.0"
    }
  ],
  "title": "Machines",
  "editable": true,
  "links": [],
  "liveNow": false,
  "panels": [
    {
      "title": "Hybrid Machine Available Memory Percentage",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {

                "color": "dark-red",                
                "value": 0
              },
              {

                "color": "dark-green",                
                "value": 10
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 0
      },
      "id": 1,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"Memory\" and Name == \"AvailableMB\" | extend TotalMemory = toreal(todynamic(Tags)[\"vm.azm.ms/memorySizeMB\"]) | extend AvailableMemoryPercentage = (toreal(Val) / TotalMemory) * 100.0 | summarize AggregatedValue = avg(AvailableMemoryPercentage) by bin(TimeGenerated,15m), Computer, _ResourceId",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Data Disk Free Space Percentage Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {

                "color": "dark-red",                
                "value": 0
              },
              {

                "color": "dark-green",                
                "value": 10
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 0
      },
      "id": 2,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\"and Name == \"FreeSpacePercentage\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer,_ResourceId, Disk",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Data Disk Read Latency Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 25
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 8
      },
      "id": 3,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"ReadLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\", \"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Data Disk Write Latency Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 25
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 8
      },
      "id": 4,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"WriteLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer, _ResourceId, Disk",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Heartbeat Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 10
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 16
      },
      "id": 5,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "Heartbeat | where _ResourceId has \"Microsoft.HybridCompute/machines\" | summarize TimeGenerated=max(TimeGenerated) by Computer, _ResourceId | extend Duration = datetime_diff(\"minute\",now(),TimeGenerated) | summarize AggregatedValue = min(Duration) by Computer, bin(TimeGenerated,5m), _ResourceId",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Network Read Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 10000000
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 16
      },
      "id": 6,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"Network\" and Name == \"ReadBytesPerSecond\" | extend NetworkInterface=tostring(todynamic(Tags)[\"vm.azm.ms/networkDeviceId\"]) | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, NetworkInterface",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Network Write Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 10000000
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 24
      },
      "id": 7,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"Network\" and Name == \"WriteBytesPerSecond\" | extend NetworkInterface=tostring(todynamic(Tags)[\"vm.azm.ms/networkDeviceId\"]) | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, NetworkInterface",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine OS Disk Free Space Percentage",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {

                "color": "dark-red",                
                "value": 0
              },
              {

                "color": "dark-green",                
                "value": 10
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 24
      },
      "id": 8,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"FreeSpacePercentage\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine OS Disk Read Latency Alert",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 25
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 32
      },
      "id": 9,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"ReadLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine OS Disk Write Latency (ms)",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 25
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 12,
        "y": 32
      },
      "id": 10,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"WriteLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    },
    {
      "title": "Hybrid Machine Processor Utilization Percentage",
      "datasource": {
        "type": "grafana-azure-monitor-datasource",
        "uid": "${ds}"
      },
      "fieldConfig": {
        "defaults": {
          "color": {
            "mode": "thresholds"
          },
          "mappings": [],
          "thresholds": {
            "mode": "absolute",
            "steps": [
              {
                "color": "#808080",
                "value": null
              },
              {
                
                "color": "dark-green",                
                "value": 0
              },
              {
                
                "color": "dark-red",                
                "value": 85
              }
            ]
          }
        },
        "overrides": []
      },
      "gridPos": {
        "h": 8,
        "w": 12,
        "x": 0,
        "y": 40
      },
      "id": 11,
      "options": {
        "displayMode": "basic",
        "minVizHeight": 10,
        "minVizWidth": 0,
        "orientation": "horizontal",
        "reduceOptions": {
          "calcs": [
            "lastNotNull"
          ],
          "fields": "",
          "values": true
        },
        "showUnfilled": true,
        "valueMode": "color"
      },
      "pluginVersion": "9.5.12",
      "targets": [
        {
          "azureLogAnalytics": {

            "query": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"Processor\" and Name == \"UtilizationPercentage\" | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId",
            "resources": [
              "/subscriptions/$sub"
            ]
          },
          "azureMonitor": {
            "allowedTimeGrainsMs": [],
            "timeGrain": "auto"
          },
          "datasource": {
            "type": "grafana-azure-monitor-datasource",
            "uid": "${ds}"
          },
          "queryType": "Azure Log Analytics",
          "refId": "A"
        }
      ],
      "transformations": [
        {
          "id": "organize",
          "options": {
            "excludeByName": {
              "_ResourceId": true
            },
            "indexByName": {},
            "renameByName": {}
          }
        }
      ],
      "type": "bargauge"
    }
  ],
  "refresh": "",
  "schemaVersion": 38,
  "style": "dark",
  "tags": [],
  "templating": {
    "list": [
      {
        "current": {},
        "hide": 0,
        "includeAll": false,
        "label": "Datasource",
        "multi": false,
        "name": "ds",
        "options": [],
        "query": "grafana-azure-monitor-datasource",
        "queryValue": "",
        "refresh": 1,
        "regex": "",
        "skipUrlSync": false,
        "type": "datasource"
      },
      {
        "current": {},
        "datasource": {
          "type": "grafana-azure-monitor-datasource",
          "uid": "${ds}"
        },
        "definition": "",
        "hide": 0,
        "includeAll": false,
        "label": "Subscription",
        "multi": false,
        "name": "sub",
        "options": [],
        "query": {
          "azureLogAnalytics": {
            "query": "",
            "resources": []
          },
          "queryType": "Azure Subscriptions",
          "refId": "A"
        },
        "refresh": 1,
        "regex": "",
        "skipUrlSync": false,
        "sort": 0,
        "type": "query"
      }
    ]
  },
  "time": {
    "from": "now-6h",
    "to": "now"
  },
  "timepicker": {},
  "timezone": "",
  "version": null
}



Hybrid Machine Available Memory Percentage - Log Alert

Log Alert for Hybrid Machine Available Memory Percentage

Properties:

autoMitigatetrue
autoResolvetrue
autoResolveTime0:10:00
dimensions
[
  {
    "name": "Computer",
    "operator": "Include",
    "values": [
      "*"
    ]
  }
]
evaluationFrequencyPT5M
failingPeriods
{
  "minFailingPeriodsToAlert": 1,
  "numberOfEvaluationPeriods": 1
}
metricMeasureColumnAggregatedValue
operatorLessThan
query
InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "Memory" and Name == "AvailableMB" | extend TotalMemory = toreal(todynamic(Tags)["vm.azm.ms/memorySizeMB"]) | extend AvailableMemoryPercentage = (toreal(Val) / TotalMemory) * 100.0 | summarize AggregatedValue = avg(AvailableMemoryPercentage) by bin(TimeGenerated,15m), Computer, _ResourceId
resouceIdColumn_ResourceId
severity2
threshold10
timeAggregationAverage
windowSizePT15M

References:

Templates:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Name of the alert"
      }
    },
    "alertDescription": {
      "type": "string",
      "defaultValue": "Log Alert for Hybrid Machine Available Memory Percentage",
      "metadata": {
        "description": "Description of alert"
      }
    },
    "isEnabled": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert is enabled"
      }
    },
    "checkWorkspaceAlertsStorageConfigured": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies whether to check linked storage and fail creation if the storage was not found"
      }
    },
    "resourceId": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
      }
    },
    "muteActionsDuration": {
      "type": "string",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H"
      ],
      "metadata": {
        "description": "Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired."
      }
    },
    "alertSeverity": {
      "type": "int",
      "defaultValue": 2,
      "allowedValues": [
        0,
        1,
        2,
        3,
        4
      ],
      "metadata": {
        "description": "Severity of alert {0,1,2,3,4}"
      }
    },
    "autoMitigate": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert will automatically resolve"
      }
    },
    "query": {
      "type": "string",
      "minLength": 1,
      "defaultValue": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"Memory\" and Name == \"AvailableMB\" | extend TotalMemory = toreal(todynamic(Tags)[\"vm.azm.ms/memorySizeMB\"]) | extend AvailableMemoryPercentage = (toreal(Val) / TotalMemory) * 100.0 | summarize AggregatedValue = avg(AvailableMemoryPercentage) by bin(TimeGenerated,15m), Computer, _ResourceId",
      "metadata": {
        "description": "Name of the metric used in the comparison to activate the alert."
      }
    },
    "metricMeasureColumn": {
      "type": "string",
      "defaultValue": "AggregatedValue",
      "metadata": {
        "description": "Name of the measure column used in the alert evaluation."
      }
    },
    "resourceIdColumn": {
      "type": "string",
      "defaultValue": "_ResourceId",
      "metadata": {
        "description": "Name of the resource ID column used in the alert targeting the alerts."
      }
    },
    "operator": {
      "type": "string",
      "defaultValue": "LessThan",
      "allowedValues": [
        "Equals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      }
    },
    "threshold": {
      "type": "string",
      "defaultValue": "10",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      }
    },
    "numberOfEvaluationPeriods": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of periods to check in the alert evaluation."
      }
    },
    "minFailingPeriodsToAlert": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods)."
      }
    },
    "timeAggregation": {
      "type": "string",
      "defaultValue": "Average",
      "allowedValues": [
        "Average",
        "Minimum",
        "Maximum",
        "Total",
        "Count"
      ],
      "metadata": {
        "description": "How the data that is collected should be combined over time."
      }
    },
    "windowSize": {
      "type": "string",
      "defaultValue": "PT15M",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H",
        "PT1D"
      ],
      "metadata": {
        "description": "Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format."
      }
    },
    "evaluationFrequency": {
      "type": "string",
      "defaultValue": "PT5M",
      "allowedValues": [
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H"
      ],
      "metadata": {
        "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
      }
    },
    "currentDateTimeUtcNow": {
      "type": "string",
      "defaultValue": "[utcNow()]",
      "metadata": {
          "description": "The current date and time using the utcNow function. Used for deployment name uniqueness"
      }
    },
    "telemetryOptOut": {
      "type": "string",
      "defaultValue": "No",
      "allowedValues": [
          "Yes",
          "No"
      ],
      "metadata": {
          "description": "The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry."
      }
    }
  },
  "variables": {
    "pidDeploymentName": "[take(concat('pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-', uniqueString(resourceGroup().id, parameters('alertName'), parameters('currentDateTimeUtcNow'))), 64)]"
  },
  "resources": [
    {
      "type": "Microsoft.Insights/scheduledQueryRules",
      "apiVersion": "2021-08-01",
      "name": "[parameters('alertName')]",
      "location": "[resourceGroup().location]",
      "tags": {
        "_deployed_by_amba": true
      },
      "properties": {
        "description": "[parameters('alertDescription')]",
        "severity": "[parameters('alertSeverity')]",
        "enabled": "[parameters('isEnabled')]",
        "scopes": [
          "[parameters('resourceId')]"
        ],
        "evaluationFrequency": "[parameters('evaluationFrequency')]",
        "windowSize": "[parameters('windowSize')]",
        "criteria": {
          "allOf": [
            {
              "query": "[parameters('query')]",
              "metricMeasureColumn": "[parameters('metricMeasureColumn')]",
              "resourceIdColumn": "[parameters('resourceIdColumn')]",
              "dimensions": [{"name": "Computer", "operator": "Include", "values": ["*"]}],
              "operator": "[parameters('operator')]",
              "threshold": "[parameters('threshold')]",
              "timeAggregation": "[parameters('timeAggregation')]",
              "failingPeriods": {
                "numberOfEvaluationPeriods": "[parameters('numberOfEvaluationPeriods')]",
                "minFailingPeriodsToAlert": "[parameters('minFailingPeriodsToAlert')]"
              }
            }
          ]
        },
        "muteActionsDuration": "[parameters('muteActionsDuration')]",
        "autoMitigate": "[parameters('autoMitigate')]",
        "checkWorkspaceAlertsStorageConfigured": "[parameters('checkWorkspaceAlertsStorageConfigured')]"
      }
    },
    {
      "condition": "[equals(parameters('telemetryOptOut'), 'No')]",
      "apiVersion": "2023-07-01",
      "name": "[variables('pidDeploymentName')]",
      "type": "Microsoft.Resources/deployments",
      "properties": {
          "mode": "Incremental",
          "template": {
              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
              "contentVersion": "1.0.0.0",
              "resources": []
          }
      }
    }
  ]
}
@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'Log Alert for Hybrid Machine Available Memory Percentage'

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

@description('Specifies whether to check linked storage and fail creation if the storage was not found')
param checkWorkspaceAlertsStorageConfigured bool = false

@description('Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz')
@minLength(1)
param resourceId string

@description('Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param muteActionsDuration string

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

@description('Specifies whether the alert will automatically resolve')
param autoMitigate bool = true

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param query string = 'InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "Memory" and Name == "AvailableMB" | extend TotalMemory = toreal(todynamic(Tags)["vm.azm.ms/memorySizeMB"]) | extend AvailableMemoryPercentage = (toreal(Val) / TotalMemory) * 100.0 | summarize AggregatedValue = avg(AvailableMemoryPercentage) by bin(TimeGenerated,15m), Computer, _ResourceId'

@description('Name of the measure column used in the alert evaluation.')
param metricMeasureColumn string = 'AggregatedValue'

@description('Name of the resource ID column used in the alert targeting the alerts.')
param resourceIdColumn string = '_ResourceId'

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

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

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

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

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

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

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

@description('"The current date and time using the utcNow function. Used for deployment name uniqueness')
param currentDateTimeUtcNow string = utcNow()

@description('The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry.')
@allowed([
  'Yes'
  'No'
])
param telemetryOptOut string = 'No'

resource alert 'Microsoft.Insights/scheduledQueryRules@2021-08-01' = {
  name: alertName
  location: resourceGroup().location
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      allOf: [
        {
          query: query
          metricMeasureColumn: metricMeasureColumn
          resourceIdColumn: resourceIdColumn
          dimensions: [
            {
              name: 'Computer'
              operator: 'Include'
              values: ['*']
            }]
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
        }
      ]
    }
    muteActionsDuration: muteActionsDuration
    autoMitigate: autoMitigate
    checkWorkspaceAlertsStorageConfigured: checkWorkspaceAlertsStorageConfigured
  }
}

var ambaTelemetryPidName = 'pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-${uniqueString(resourceGroup().id, alertName, currentDateTimeUtcNow)}'
resource ambaTelemetryPid 'Microsoft.Resources/deployments@2023-07-01' =  if (telemetryOptOut == 'No') {
  name: ambaTelemetryPidName
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    mode: 'Incremental'
    template: {
      '$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#'
      contentVersion: '1.0.0.0'
      resources: []
    }
  }
}
{
    "mode": "All",
    "parameters": {
      "alertResourceGroupName": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Name",
          "description": "Resource group the alert is placed in"
        },
        "defaultValue": "rg-amba-monitoring-001"
      },
      "alertResourceGroupTags": {
        "type": "Object",
        "metadata": {
          "displayName": "Resource Group Tags",
          "description": "Tags on the Resource group the alert is placed in"
        },
        "defaultValue": {
          "Project": "amba-monitoring"
        }
      },
      "alertResourceGroupLocation": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Location",
          "description": "Location of the Resource group the alert is placed in"
        },
        "defaultValue": "centralus"
      },
      "UAMIResourceId": {
        "type": "string",
        "defaultValue": "",
        "metadata": {
          "description": "The resource Id of the user assigned managed identity.",
          "displayName": "User Assigned managed Identity resource Id."
        }
      },
      "severity": {
        "type": "String",
        "metadata": {
          "displayName": "Severity",
          "description": "Severity of the Alert"
        },
        "allowedValues": [
          "0",
          "1",
          "2",
          "3",
          "4"
        ],
        "defaultValue": "2"
      },
      "operator": {
        "type": "String",
        "metadata": {
          "displayName": "Operator"
        },
        "allowedValues": [
          "GreaterThan"
        ],
        "defaultValue": "GreaterThan"
      },
      "timeAggregation": {
        "type": "String",
        "metadata": {
          "displayName": "TimeAggregation"
        },
        "allowedValues": [
          "Count"
        ],
        "defaultValue": "Count"
      },
      "windowSize": {
        "type": "String",
        "metadata": {
          "displayName": "Window Size",
          "description": "Window size for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H",
          "PT6H",
          "PT12H",
          "PT24H"
        ],
        "defaultValue": "PT15M"
      },
      "evaluationFrequency": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Frequency",
          "description": "Evaluation frequency for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H"
        ],
        "defaultValue": "PT5M"
      },
      "autoMitigate": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Mitigate",
          "description": "Auto Mitigate for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolve": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolveTime": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve time for the alert in ISO 8601 format"
        },
        "defaultValue": "true"
      },
      "enabled": {
        "type": "String",
        "metadata": {
          "displayName": "Alert State",
          "description": "Alert state for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "threshold": {
        "type": "String",
        "metadata": {
          "displayName": "Threshold",
          "description": "Threshold for the alert"
        },
        "defaultValue": "10"
      },
      "failingPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Failing Periods",
          "description": "Number of failing periods before alert is fired"
        },
        "defaultValue": "1"
      },
      "evaluationPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Periods",
          "description": "The number of aggregated lookback points."
        },
        "defaultValue": "1"
      },
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Effect of the policy"
        },
        "allowedValues": [
          "deployIfNotExists",
          "disabled"
        ],
        "defaultValue": "deployIfNotExists"
      },
      "MonitorDisableTagName": {
        "type": "String",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag name",
          "description": "Tag name to disable monitoring. Set to true if monitoring should be disabled"
        },
        "defaultValue": "MonitorDisable"
      },
      "MonitorDisableTagValues": {
        "type": "Array",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag values(s)",
          "description": "Tag value(s) used to disable monitoring at the resource level. Set to true if monitoring should be disabled."
        },
        "defaultValue": [
          "true",
          "Test",
          "Dev",
          "Sandbox"
        ]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.HybridCompute/machines"
          },
          {
            "field": "[concat('tags[', parameters('MonitorDisableTagName'), ']')]",
            "notIn": "[parameters('MonitorDisableTagValues')]"
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ],
          "type": "Microsoft.Insights/scheduledQueryRules",
          "existenceScope": "resourceGroup",
          "resourceGroupName": "[parameters('alertResourceGroupName')]",
          "deploymentScope": "subscription",
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Insights/scheduledQueryRules/displayName",
                "equals": "[concat(subscription().displayName, '-HybridVMLowMemoryAlert')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/scopes[*]",
                "equals": "[subscription().id]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/enabled",
                "equals": "[parameters('enabled')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/evaluationFrequency",
                "equals": "[parameters('evaluationFrequency')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/windowSize",
                "equals": "[parameters('windowSize')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/severity",
                "equals": "[parameters('severity')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/autoMitigate",
                "equals": "[parameters('autoMitigate')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].operator",
                "equals": "[parameters('operator')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].timeAggregation",
                "equals": "[parameters('timeAggregation')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.numberOfEvaluationPeriods",
                "equals": "[parameters('evaluationPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.minFailingPeriodsToAlert",
                "equals": "[parameters('failingPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].query",
                "equals": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-AvailableMemoryPercentage-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"Memory\" and Name == \"AvailableMB\" | extend TotalMemory = toreal(todynamic(Tags)[\"vm.azm.ms/memorySizeMB\"]) | extend AvailableMemoryPercentage = (toreal(Val) / TotalMemory) * 100.0 | summarize AggregatedValue = avg(AvailableMemoryPercentage) by bin(TimeGenerated, 15m), Computer, _ResourceId | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-AvailableMemoryPercentage-threshold-Override_\", tostring(tags.[\"_amba-AvailableMemoryPercentage-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue < appliedThreshold | project TimeGenerated, Computer, _ResourceId, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]"
              },
              {
                "field": "identity.userAssignedIdentities",
                "containsKey": "[parameters('UAMIResourceId')]"
              }
            ]
          },
          "deployment": {
            "location": "northeurope",
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "alertResourceGroupName": {
                    "type": "string"
                  },
                  "alertResourceGroupTags": {
                    "type": "object"
                  },
                  "alertResourceGroupLocation": {
                    "type": "string"
                  },
                  "UAMIResourceId": {
                    "type": "string"
                  },
                  "severity": {
                    "type": "String"
                  },
                  "windowSize": {
                    "type": "String"
                  },
                  "evaluationFrequency": {
                    "type": "String"
                  },
                  "autoMitigate": {
                    "type": "String"
                  },
                  "autoResolve": {
                    "type": "String"
                  },
                  "autoResolveTime": {
                    "type": "String"
                  },
                  "enabled": {
                    "type": "String"
                  },
                  "threshold": {
                    "type": "String"
                  },
                  "operator": {
                    "type": "String"
                  },
                  "timeAggregation": {
                    "type": "String"
                  },
                  "failingPeriods": {
                    "type": "String"
                  },
                  "evaluationPeriods": {
                    "type": "String"
                  },
                  "MonitorDisableTagName": {
                    "type": "String"
                  },
                  "MonitorDisableTagValues": {
                    "type": "Array"
                  }
                },
                "variables": {},
                "resources": [
                  {
                    "type": "Microsoft.Resources/resourceGroups",
                    "apiVersion": "2021-04-01",
                    "name": "[parameters('alertResourceGroupName')]",
                    "location": "[parameters('alertResourceGroupLocation')]",
                    "tags": "[parameters('alertResourceGroupTags')]"
                  },
                  {
                    "type": "Microsoft.Resources/deployments",
                    "apiVersion": "2019-10-01",
                    "name": "HybridVMMemoryAlert",
                    "resourceGroup": "[parameters('alertResourceGroupName')]",
                    "dependsOn": [
                      "[concat('Microsoft.Resources/resourceGroups/', parameters('alertResourceGroupName'))]"
                    ],
                    "properties": {
                      "mode": "Incremental",
                      "template": {
                        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                        "contentVersion": "1.0.0.0",
                        "parameters": {
                          "enabled": {
                            "type": "string"
                          },
                          "alertResourceGroupName": {
                            "type": "string"
                          },
                          "alertResourceGroupLocation": {
                            "type": "string"
                          },
                          "UAMIResourceId": {
                            "type": "string"
                          }
                        },
                        "variables": {},
                        "resources": [
                          {
                            "type": "Microsoft.Insights/scheduledQueryRules",
                            "apiVersion": "2022-08-01-preview",
                            "name": "[concat(subscription().displayName, '-HybridVMLowMemoryAlert')]",
                            "location": "[parameters('alertResourceGroupLocation')]",
                            "identity": {
                              "type": "UserAssigned",
                              "userAssignedIdentities": {
                                "[parameters('UAMIResourceId')]": {}
                              }
                            },
                            "tags": {
                              "_deployed_by_amba": true
                            },
                            "properties": {
                              "displayName": "[concat(subscription().displayName, '-HybridVMLowMemoryAlert')]",
                              "description": "Log Alert for Virtual Machine Memory",
                              "severity": "[parameters('severity')]",
                              "enabled": "[parameters('enabled')]",
                              "scopes": [
                                "[subscription().Id]"
                              ],
                              "targetResourceTypes": [
                                "Microsoft.HybridCompute/machines"
                              ],
                              "evaluationFrequency": "[parameters('evaluationFrequency')]",
                              "windowSize": "[parameters('windowSize')]",
                              "criteria": {
                                "allOf": [
                                  {
                                    "query": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-AvailableMemoryPercentage-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"Memory\" and Name == \"AvailableMB\" | extend TotalMemory = toreal(todynamic(Tags)[\"vm.azm.ms/memorySizeMB\"]) | extend AvailableMemoryPercentage = (toreal(Val) / TotalMemory) * 100.0 | summarize AggregatedValue = avg(AvailableMemoryPercentage) by bin(TimeGenerated, 15m), Computer, _ResourceId | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-AvailableMemoryPercentage-threshold-Override_\", tostring(tags.[\"_amba-AvailableMemoryPercentage-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue < appliedThreshold | project TimeGenerated, Computer, _ResourceId, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]",
                                    "threshold": 0,
                                    "operator": "[parameters('operator')]",
                                    "resourceIdColumn": "_ResourceId",
                                    "timeAggregation": "[parameters('timeAggregation')]",
                                    "dimensions": [
                                      {
                                        "name": "Computer",
                                        "operator": "Include",
                                        "values": [
                                          "*"
                                        ]
                                      }
                                    ],
                                    "failingPeriods": {
                                      "numberOfEvaluationPeriods": "[parameters('evaluationPeriods')]",
                                      "minFailingPeriodsToAlert": "[parameters('failingPeriods')]"
                                    }
                                  }
                                ]
                              },
                              "autoMitigate": "[parameters('autoMitigate')]",
                              "ruleResolveConfiguration": {
                                "autoResolved": "[parameters('autoResolve')]",
                                "timeToResolve": "[parameters('autoResolveTime')]"
                              },
                              "parameters": {
                                "alertResourceGroupName": {
                                  "value": "[parameters('alertResourceGroupName')]"
                                },
                                "alertResourceGroupLocation": {
                                  "value": "[parameters('alertResourceGroupLocation')]"
                                },
                                "UAMIResourceId": {
                                  "value": "[parameters('UAMIResourceId')]"
                                },
                                "severity": {
                                  "value": "[parameters('severity')]"
                                },
                                "windowSize": {
                                  "value": "[parameters('windowSize')]"
                                },
                                "evaluationFrequency": {
                                  "value": "[parameters('evaluationFrequency')]"
                                },
                                "autoMitigate": {
                                  "value": "[parameters('autoMitigate')]"
                                },
                                "autoResolve": {
                                  "value": "[parameters('autoResolve')]"
                                },
                                "autoResolveTime": {
                                  "value": "[parameters('autoResolveTime')]"
                                },
                                "enabled": {
                                  "value": "[parameters('enabled')]"
                                },
                                "threshold": {
                                  "value": "[parameters('threshold')]"
                                },
                                "failingPeriods": {
                                  "value": "[parameters('failingPeriods')]"
                                },
                                "evaluationPeriods": {
                                  "value": "[parameters('evaluationPeriods')]"
                                },
                                "MonitorDisableTagName": {
                                  "value": "[parameters('MonitorDisableTagName')]"
                                },
                                "MonitorDisableTagValues": {
                                  "value": "[parameters('MonitorDisableTagValues')]"
                                }
                              }
                            }
                          }
                        ]
                      },
                      "parameters": {
                        "enabled": {
                          "value": "[parameters('enabled')]"
                        },
                        "alertResourceGroupName": {
                          "value": "[parameters('alertResourceGroupName')]"
                        },
                        "alertResourceGroupLocation": {
                          "value": "[parameters('alertResourceGroupLocation')]"
                        },
                        "UAMIResourceId": {
                          "value": "[parameters('UAMIResourceId')]"
                        }
                      }
                    }
                  }
                ]
              },
              "parameters": {
                "alertResourceGroupName": {
                  "value": "[parameters('alertResourceGroupName')]"
                },
                "alertResourceGroupTags": {
                  "value": "[parameters('alertResourceGroupTags')]"
                },
                "alertResourceGroupLocation": {
                  "value": "[parameters('alertResourceGroupLocation')]"
                },
                "UAMIResourceId": {
                  "value": "[parameters('UAMIResourceId')]"
                },
                "severity": {
                  "value": "[parameters('severity')]"
                },
                "windowSize": {
                  "value": "[parameters('windowSize')]"
                },
                "evaluationFrequency": {
                  "value": "[parameters('evaluationFrequency')]"
                },
                "autoMitigate": {
                  "value": "[parameters('autoMitigate')]"
                },
                "autoResolve": {
                  "value": "[parameters('autoResolve')]"
                },
                "autoResolveTime": {
                  "value": "[parameters('autoResolveTime')]"
                },
                "enabled": {
                  "value": "[parameters('enabled')]"
                },
                "threshold": {
                  "value": "[parameters('threshold')]"
                },
                "operator": {
                  "value": "[parameters('operator')]"
                },
                "timeAggregation": {
                  "value": "[parameters('timeAggregation')]"
                },
                "failingPeriods": {
                  "value": "[parameters('failingPeriods')]"
                },
                "evaluationPeriods": {
                  "value": "[parameters('evaluationPeriods')]"
                },
                "MonitorDisableTagName": {
                  "value": "[parameters('MonitorDisableTagName')]"
                },
                "MonitorDisableTagValues": {
                  "value": "[parameters('MonitorDisableTagValues')]"
                }
              }
            }
          }
        }
      }
    }
  }



Hybrid Machine Data Disk Free Space Percentage Alert - Log Alert

Log Alert for Hybrid Machine Data Disk Free Space Percentage

Properties:

autoMitigatetrue
autoResolvetrue
autoResolveTime0:10:00
dimensions
[
  {
    "name": "Computer",
    "operator": "Include",
    "values": [
      "*"
    ]
  },
  {
    "name": "Disk",
    "operator": "Include",
    "values": [
      "*"
    ]
  }
]
evaluationFrequencyPT5M
failingPeriods
{
  "minFailingPeriodsToAlert": 1,
  "numberOfEvaluationPeriods": 1
}
metricMeasureColumnAggregatedValue
operatorLessThan
query
InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "LogicalDisk"and Name == "FreeSpacePercentage" | extend Disk=tostring(todynamic(Tags)["vm.azm.ms/mountId"]) | where Disk !in ("C:","/") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer,_ResourceId, Disk
resouceIdColumn_ResourceId
severity2
threshold10
timeAggregationAverage
windowSizePT15M

References:

Templates:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Name of the alert"
      }
    },
    "alertDescription": {
      "type": "string",
      "defaultValue": "Log Alert for Hybrid Machine Data Disk Free Space Percentage",
      "metadata": {
        "description": "Description of alert"
      }
    },
    "isEnabled": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert is enabled"
      }
    },
    "checkWorkspaceAlertsStorageConfigured": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies whether to check linked storage and fail creation if the storage was not found"
      }
    },
    "resourceId": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
      }
    },
    "muteActionsDuration": {
      "type": "string",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H"
      ],
      "metadata": {
        "description": "Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired."
      }
    },
    "alertSeverity": {
      "type": "int",
      "defaultValue": 2,
      "allowedValues": [
        0,
        1,
        2,
        3,
        4
      ],
      "metadata": {
        "description": "Severity of alert {0,1,2,3,4}"
      }
    },
    "autoMitigate": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert will automatically resolve"
      }
    },
    "query": {
      "type": "string",
      "minLength": 1,
      "defaultValue": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\"and Name == \"FreeSpacePercentage\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer,_ResourceId, Disk",
      "metadata": {
        "description": "Name of the metric used in the comparison to activate the alert."
      }
    },
    "metricMeasureColumn": {
      "type": "string",
      "defaultValue": "AggregatedValue",
      "metadata": {
        "description": "Name of the measure column used in the alert evaluation."
      }
    },
    "resourceIdColumn": {
      "type": "string",
      "defaultValue": "_ResourceId",
      "metadata": {
        "description": "Name of the resource ID column used in the alert targeting the alerts."
      }
    },
    "operator": {
      "type": "string",
      "defaultValue": "LessThan",
      "allowedValues": [
        "Equals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      }
    },
    "threshold": {
      "type": "string",
      "defaultValue": "10",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      }
    },
    "numberOfEvaluationPeriods": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of periods to check in the alert evaluation."
      }
    },
    "minFailingPeriodsToAlert": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods)."
      }
    },
    "timeAggregation": {
      "type": "string",
      "defaultValue": "Average",
      "allowedValues": [
        "Average",
        "Minimum",
        "Maximum",
        "Total",
        "Count"
      ],
      "metadata": {
        "description": "How the data that is collected should be combined over time."
      }
    },
    "windowSize": {
      "type": "string",
      "defaultValue": "PT15M",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H",
        "PT1D"
      ],
      "metadata": {
        "description": "Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format."
      }
    },
    "evaluationFrequency": {
      "type": "string",
      "defaultValue": "PT5M",
      "allowedValues": [
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H"
      ],
      "metadata": {
        "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
      }
    },
    "currentDateTimeUtcNow": {
      "type": "string",
      "defaultValue": "[utcNow()]",
      "metadata": {
          "description": "The current date and time using the utcNow function. Used for deployment name uniqueness"
      }
    },
    "telemetryOptOut": {
      "type": "string",
      "defaultValue": "No",
      "allowedValues": [
          "Yes",
          "No"
      ],
      "metadata": {
          "description": "The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry."
      }
    }
  },
  "variables": {
    "pidDeploymentName": "[take(concat('pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-', uniqueString(resourceGroup().id, parameters('alertName'), parameters('currentDateTimeUtcNow'))), 64)]"
  },
  "resources": [
    {
      "type": "Microsoft.Insights/scheduledQueryRules",
      "apiVersion": "2021-08-01",
      "name": "[parameters('alertName')]",
      "location": "[resourceGroup().location]",
      "tags": {
        "_deployed_by_amba": true
      },
      "properties": {
        "description": "[parameters('alertDescription')]",
        "severity": "[parameters('alertSeverity')]",
        "enabled": "[parameters('isEnabled')]",
        "scopes": [
          "[parameters('resourceId')]"
        ],
        "evaluationFrequency": "[parameters('evaluationFrequency')]",
        "windowSize": "[parameters('windowSize')]",
        "criteria": {
          "allOf": [
            {
              "query": "[parameters('query')]",
              "metricMeasureColumn": "[parameters('metricMeasureColumn')]",
              "resourceIdColumn": "[parameters('resourceIdColumn')]",
              "dimensions": [{"name": "Computer", "operator": "Include", "values": ["*"]}, {"name": "Disk", "operator": "Include", "values": ["*"]}],
              "operator": "[parameters('operator')]",
              "threshold": "[parameters('threshold')]",
              "timeAggregation": "[parameters('timeAggregation')]",
              "failingPeriods": {
                "numberOfEvaluationPeriods": "[parameters('numberOfEvaluationPeriods')]",
                "minFailingPeriodsToAlert": "[parameters('minFailingPeriodsToAlert')]"
              }
            }
          ]
        },
        "muteActionsDuration": "[parameters('muteActionsDuration')]",
        "autoMitigate": "[parameters('autoMitigate')]",
        "checkWorkspaceAlertsStorageConfigured": "[parameters('checkWorkspaceAlertsStorageConfigured')]"
      }
    },
    {
      "condition": "[equals(parameters('telemetryOptOut'), 'No')]",
      "apiVersion": "2023-07-01",
      "name": "[variables('pidDeploymentName')]",
      "type": "Microsoft.Resources/deployments",
      "properties": {
          "mode": "Incremental",
          "template": {
              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
              "contentVersion": "1.0.0.0",
              "resources": []
          }
      }
    }
  ]
}
@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'Log Alert for Hybrid Machine Data Disk Free Space Percentage'

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

@description('Specifies whether to check linked storage and fail creation if the storage was not found')
param checkWorkspaceAlertsStorageConfigured bool = false

@description('Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz')
@minLength(1)
param resourceId string

@description('Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param muteActionsDuration string

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

@description('Specifies whether the alert will automatically resolve')
param autoMitigate bool = true

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param query string = 'InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "LogicalDisk"and Name == "FreeSpacePercentage" | extend Disk=tostring(todynamic(Tags)["vm.azm.ms/mountId"]) | where Disk !in ("C:","/") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer,_ResourceId, Disk'

@description('Name of the measure column used in the alert evaluation.')
param metricMeasureColumn string = 'AggregatedValue'

@description('Name of the resource ID column used in the alert targeting the alerts.')
param resourceIdColumn string = '_ResourceId'

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

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

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

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

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

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

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

@description('"The current date and time using the utcNow function. Used for deployment name uniqueness')
param currentDateTimeUtcNow string = utcNow()

@description('The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry.')
@allowed([
  'Yes'
  'No'
])
param telemetryOptOut string = 'No'

resource alert 'Microsoft.Insights/scheduledQueryRules@2021-08-01' = {
  name: alertName
  location: resourceGroup().location
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      allOf: [
        {
          query: query
          metricMeasureColumn: metricMeasureColumn
          resourceIdColumn: resourceIdColumn
          dimensions: [
            {
              name: 'Computer'
              operator: 'Include'
              values: ['*']
            }
            {
              name: 'Disk'
              operator: 'Include'
              values: ['*']
            }]
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
        }
      ]
    }
    muteActionsDuration: muteActionsDuration
    autoMitigate: autoMitigate
    checkWorkspaceAlertsStorageConfigured: checkWorkspaceAlertsStorageConfigured
  }
}

var ambaTelemetryPidName = 'pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-${uniqueString(resourceGroup().id, alertName, currentDateTimeUtcNow)}'
resource ambaTelemetryPid 'Microsoft.Resources/deployments@2023-07-01' =  if (telemetryOptOut == 'No') {
  name: ambaTelemetryPidName
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    mode: 'Incremental'
    template: {
      '$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#'
      contentVersion: '1.0.0.0'
      resources: []
    }
  }
}
{
    "mode": "All",
    "parameters": {
      "alertResourceGroupName": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Name",
          "description": "Resource group the alert is placed in"
        },
        "defaultValue": "rg-amba-monitoring-001"
      },
      "alertResourceGroupTags": {
        "type": "Object",
        "metadata": {
          "displayName": "Resource Group Tags",
          "description": "Tags on the Resource group the alert is placed in"
        },
        "defaultValue": {
          "Project": "amba-monitoring"
        }
      },
      "alertResourceGroupLocation": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Location",
          "description": "Location of the Resource group the alert is placed in"
        },
        "defaultValue": "centralus"
      },
      "UAMIResourceId": {
        "type": "string",
        "defaultValue": "",
        "metadata": {
          "description": "The resource Id of the user assigned managed identity.",
          "displayName": "User Assigned managed Identity resource Id."
        }
      },
      "severity": {
        "type": "String",
        "metadata": {
          "displayName": "Severity",
          "description": "Severity of the Alert"
        },
        "allowedValues": [
          "0",
          "1",
          "2",
          "3",
          "4"
        ],
        "defaultValue": "2"
      },
      "operator": {
        "type": "String",
        "metadata": {
          "displayName": "Operator"
        },
        "allowedValues": [
          "GreaterThan"
        ],
        "defaultValue": "GreaterThan"
      },
      "timeAggregation": {
        "type": "String",
        "metadata": {
          "displayName": "TimeAggregation"
        },
        "allowedValues": [
          "Count"
        ],
        "defaultValue": "Count"
      },
      "windowSize": {
        "type": "String",
        "metadata": {
          "displayName": "Window Size",
          "description": "Window size for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H",
          "PT6H",
          "PT12H",
          "PT24H"
        ],
        "defaultValue": "PT15M"
      },
      "evaluationFrequency": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Frequency",
          "description": "Evaluation frequency for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H"
        ],
        "defaultValue": "PT5M"
      },
      "autoMitigate": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Mitigate",
          "description": "Auto Mitigate for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolve": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolveTime": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve time for the alert in ISO 8601 format"
        },
        "defaultValue": "true"
      },
      "enabled": {
        "type": "String",
        "metadata": {
          "displayName": "Alert State",
          "description": "Alert state for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "threshold": {
        "type": "String",
        "metadata": {
          "displayName": "Threshold",
          "description": "Threshold for the alert"
        },
        "defaultValue": "10"
      },
      "failingPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Failing Periods",
          "description": "Number of failing periods before alert is fired"
        },
        "defaultValue": "1"
      },
      "evaluationPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Periods",
          "description": "The number of aggregated lookback points."
        },
        "defaultValue": "1"
      },
      "computersToInclude": {
        "type": "array",
        "metadata": {
          "displayName": "Computers to be included to be monitored",
          "description": "Array of Computer to be monitored"
        },
        "defaultValue": [
          "*"
        ]
      },
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Effect of the policy"
        },
        "allowedValues": [
          "deployIfNotExists",
          "disabled"
        ],
        "defaultValue": "deployIfNotExists"
      },
      "MonitorDisableTagName": {
        "type": "String",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag name",
          "description": "Tag name to disable monitoring. Set to true if monitoring should be disabled"
        },
        "defaultValue": "MonitorDisable"
      },
      "MonitorDisableTagValues": {
        "type": "Array",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag values(s)",
          "description": "Tag value(s) used to disable monitoring at the resource level. Set to true if monitoring should be disabled."
        },
        "defaultValue": [
          "true",
          "Test",
          "Dev",
          "Sandbox"
        ]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.HybridCompute/machines"
          },
          {
            "field": "[concat('tags[', parameters('MonitorDisableTagName'), ']')]",
            "notIn": "[parameters('MonitorDisableTagValues')]"
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ],
          "type": "Microsoft.Insights/scheduledQueryRules",
          "existenceScope": "resourceGroup",
          "resourceGroupName": "[parameters('alertResourceGroupName')]",
          "deploymentScope": "subscription",
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Insights/scheduledQueryRules/displayName",
                "equals": "[concat(subscription().displayName, '-HybridVMLowDataDiskSpaceAlert')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/scopes[*]",
                "equals": "[subscription().id]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/enabled",
                "equals": "[parameters('enabled')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/evaluationFrequency",
                "equals": "[parameters('evaluationFrequency')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/windowSize",
                "equals": "[parameters('windowSize')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/severity",
                "equals": "[parameters('severity')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/autoMitigate",
                "equals": "[parameters('autoMitigate')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].operator",
                "equals": "[parameters('operator')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].timeAggregation",
                "equals": "[parameters('timeAggregation')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.numberOfEvaluationPeriods",
                "equals": "[parameters('evaluationPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.minFailingPeriodsToAlert",
                "equals": "[parameters('failingPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].query",
                "equals": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-FreeSpacePercentage-Data-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"FreeSpacePercentage\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-FreeSpacePercentage-Data-threshold-Override_\", tostring(tags.[\"_amba-FreeSpacePercentage-Data-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue < appliedThreshold | project TimeGenerated, Computer, _ResourceId, Disk, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]"
              },
              {
                "field": "identity.userAssignedIdentities",
                "containsKey": "[parameters('UAMIResourceId')]"
              }
            ]
          },
          "deployment": {
            "location": "northeurope",
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "alertResourceGroupName": {
                    "type": "string"
                  },
                  "alertResourceGroupTags": {
                    "type": "object"
                  },
                  "alertResourceGroupLocation": {
                    "type": "string"
                  },
                  "UAMIResourceId": {
                    "type": "string"
                  },
                  "severity": {
                    "type": "String"
                  },
                  "windowSize": {
                    "type": "String"
                  },
                  "evaluationFrequency": {
                    "type": "String"
                  },
                  "autoMitigate": {
                    "type": "String"
                  },
                  "autoResolve": {
                    "type": "String"
                  },
                  "autoResolveTime": {
                    "type": "String"
                  },
                  "enabled": {
                    "type": "String"
                  },
                  "threshold": {
                    "type": "String"
                  },
                  "operator": {
                    "type": "String"
                  },
                  "timeAggregation": {
                    "type": "String"
                  },
                  "failingPeriods": {
                    "type": "String"
                  },
                  "evaluationPeriods": {
                    "type": "String"
                  },
                  "computersToInclude": {
                    "type": "array"
                  },
                  "MonitorDisableTagName": {
                    "type": "String"
                  },
                  "MonitorDisableTagValues": {
                    "type": "Array"
                  }
                },
                "variables": {},
                "resources": [
                  {
                    "type": "Microsoft.Resources/resourceGroups",
                    "apiVersion": "2021-04-01",
                    "name": "[parameters('alertResourceGroupName')]",
                    "location": "[parameters('alertResourceGroupLocation')]",
                    "tags": "[parameters('alertResourceGroupTags')]"
                  },
                  {
                    "type": "Microsoft.Resources/deployments",
                    "apiVersion": "2019-10-01",
                    "name": "HybridVMdataDiskSpaceAlert",
                    "resourceGroup": "[parameters('alertResourceGroupName')]",
                    "dependsOn": [
                      "[concat('Microsoft.Resources/resourceGroups/', parameters('alertResourceGroupName'))]"
                    ],
                    "properties": {
                      "mode": "Incremental",
                      "template": {
                        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                        "contentVersion": "1.0.0.0",
                        "parameters": {
                          "enabled": {
                            "type": "string"
                          },
                          "alertResourceGroupName": {
                            "type": "string"
                          },
                          "alertResourceGroupLocation": {
                            "type": "string"
                          },
                          "UAMIResourceId": {
                            "type": "string"
                          }
                        },
                        "variables": {},
                        "resources": [
                          {
                            "type": "Microsoft.Insights/scheduledQueryRules",
                            "apiVersion": "2022-08-01-preview",
                            "name": "[concat(subscription().displayName, '-HybridVMLowDataDiskSpaceAlert')]",
                            "location": "[parameters('alertResourceGroupLocation')]",
                            "identity": {
                              "type": "UserAssigned",
                              "userAssignedIdentities": {
                                "[parameters('UAMIResourceId')]": {}
                              }
                            },
                            "tags": {
                              "_deployed_by_amba": true
                            },
                            "properties": {
                              "displayName": "[concat(subscription().displayName, '-HybridVMLowDataDiskSpaceAlert')]",
                              "description": "Log Alert for Virtual Machine dataDiskSpace",
                              "severity": "[parameters('severity')]",
                              "enabled": "[parameters('enabled')]",
                              "scopes": [
                                "[subscription().Id]"
                              ],
                              "targetResourceTypes": [
                                "Microsoft.HybridCompute/machines"
                              ],
                              "evaluationFrequency": "[parameters('evaluationFrequency')]",
                              "windowSize": "[parameters('windowSize')]",
                              "criteria": {
                                "allOf": [
                                  {
                                    "query": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-FreeSpacePercentage-Data-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"FreeSpacePercentage\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-FreeSpacePercentage-Data-threshold-Override_\", tostring(tags.[\"_amba-FreeSpacePercentage-Data-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue < appliedThreshold | project TimeGenerated, Computer, _ResourceId, Disk, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]",
                                    "threshold": 0,
                                    "operator": "[parameters('operator')]",
                                    "resourceIdColumn": "_ResourceId",
                                    "timeAggregation": "[parameters('timeAggregation')]",
                                    "dimensions": [
                                      {
                                        "name": "Computer",
                                        "operator": "Include",
                                        "values": "[parameters('computersToInclude')]"
                                      },
                                      {
                                        "name": "Disk",
                                        "operator": "Include",
                                        "values": [
                                          "*"
                                        ]
                                      }
                                    ],
                                    "failingPeriods": {
                                      "numberOfEvaluationPeriods": "[parameters('evaluationPeriods')]",
                                      "minFailingPeriodsToAlert": "[parameters('failingPeriods')]"
                                    }
                                  }
                                ]
                              },
                              "autoMitigate": "[parameters('autoMitigate')]",
                              "ruleResolveConfiguration": {
                                "autoResolved": "[parameters('autoResolve')]",
                                "timeToResolve": "[parameters('autoResolveTime')]"
                              },
                              "parameters": {
                                "alertResourceGroupName": {
                                  "value": "[parameters('alertResourceGroupName')]"
                                },
                                "alertResourceGroupLocation": {
                                  "value": "[parameters('alertResourceGroupLocation')]"
                                },
                                "UAMIResourceId": {
                                  "value": "[parameters('UAMIResourceId')]"
                                },
                                "severity": {
                                  "value": "[parameters('severity')]"
                                },
                                "windowSize": {
                                  "value": "[parameters('windowSize')]"
                                },
                                "evaluationFrequency": {
                                  "value": "[parameters('evaluationFrequency')]"
                                },
                                "autoMitigate": {
                                  "value": "[parameters('autoMitigate')]"
                                },
                                "autoResolve": {
                                  "value": "[parameters('autoResolve')]"
                                },
                                "autoResolveTime": {
                                  "value": "[parameters('autoResolveTime')]"
                                },
                                "enabled": {
                                  "value": "[parameters('enabled')]"
                                },
                                "threshold": {
                                  "value": "[parameters('threshold')]"
                                },
                                "failingPeriods": {
                                  "value": "[parameters('failingPeriods')]"
                                },
                                "evaluationPeriods": {
                                  "value": "[parameters('evaluationPeriods')]"
                                },
                                "computersToInclude": {
                                  "value": "[parameters('computersToInclude')]"
                                },
                                "MonitorDisableTagName": {
                                  "value": "[parameters('MonitorDisableTagName')]"
                                },
                                "MonitorDisableTagValues": {
                                  "value": "[parameters('MonitorDisableTagValues')]"
                                }
                              }
                            }
                          }
                        ]
                      },
                      "parameters": {
                        "enabled": {
                          "value": "[parameters('enabled')]"
                        },
                        "alertResourceGroupName": {
                          "value": "[parameters('alertResourceGroupName')]"
                        },
                        "alertResourceGroupLocation": {
                          "value": "[parameters('alertResourceGroupLocation')]"
                        },
                        "UAMIResourceId": {
                          "value": "[parameters('UAMIResourceId')]"
                        }
                      }
                    }
                  }
                ]
              },
              "parameters": {
                "alertResourceGroupName": {
                  "value": "[parameters('alertResourceGroupName')]"
                },
                "alertResourceGroupTags": {
                  "value": "[parameters('alertResourceGroupTags')]"
                },
                "alertResourceGroupLocation": {
                  "value": "[parameters('alertResourceGroupLocation')]"
                },
                "UAMIResourceId": {
                  "value": "[parameters('UAMIResourceId')]"
                },
                "severity": {
                  "value": "[parameters('severity')]"
                },
                "windowSize": {
                  "value": "[parameters('windowSize')]"
                },
                "evaluationFrequency": {
                  "value": "[parameters('evaluationFrequency')]"
                },
                "autoMitigate": {
                  "value": "[parameters('autoMitigate')]"
                },
                "autoResolve": {
                  "value": "[parameters('autoResolve')]"
                },
                "autoResolveTime": {
                  "value": "[parameters('autoResolveTime')]"
                },
                "enabled": {
                  "value": "[parameters('enabled')]"
                },
                "threshold": {
                  "value": "[parameters('threshold')]"
                },
                "operator": {
                  "value": "[parameters('operator')]"
                },
                "timeAggregation": {
                  "value": "[parameters('timeAggregation')]"
                },
                "failingPeriods": {
                  "value": "[parameters('failingPeriods')]"
                },
                "evaluationPeriods": {
                  "value": "[parameters('evaluationPeriods')]"
                },
                "computersToInclude": {
                  "value": "[parameters('computersToInclude')]"
                },
                "MonitorDisableTagName": {
                  "value": "[parameters('MonitorDisableTagName')]"
                },
                "MonitorDisableTagValues": {
                  "value": "[parameters('MonitorDisableTagValues')]"
                }
              }
            }
          }
        }
      }
    }
  }



Hybrid Machine Data Disk Read Latency Alert - Log Alert

Log Alert for Hybrid Machine Data Disk Read Latency

Properties:

autoMitigatetrue
autoResolvetrue
autoResolveTime0:10:00
dimensions
[
  {
    "name": "Computer",
    "operator": "Include",
    "values": [
      "*"
    ]
  },
  {
    "name": "Disk",
    "operator": "Include",
    "values": [
      "*"
    ]
  }
]
evaluationFrequencyPT5M
failingPeriods
{
  "minFailingPeriodsToAlert": 1,
  "numberOfEvaluationPeriods": 1
}
metricMeasureColumnAggregatedValue
operatorGreaterThan
query
InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "LogicalDisk" and Name == "ReadLatencyMs" | extend Disk=tostring(todynamic(Tags)["vm.azm.ms/mountId"]) | where Disk !in ("C:", "/") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk
resouceIdColumn_ResourceId
severity2
threshold25
timeAggregationAverage
windowSizePT15M

References:

Templates:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Name of the alert"
      }
    },
    "alertDescription": {
      "type": "string",
      "defaultValue": "Log Alert for Hybrid Machine Data Disk Read Latency",
      "metadata": {
        "description": "Description of alert"
      }
    },
    "isEnabled": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert is enabled"
      }
    },
    "checkWorkspaceAlertsStorageConfigured": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies whether to check linked storage and fail creation if the storage was not found"
      }
    },
    "resourceId": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
      }
    },
    "muteActionsDuration": {
      "type": "string",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H"
      ],
      "metadata": {
        "description": "Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired."
      }
    },
    "alertSeverity": {
      "type": "int",
      "defaultValue": 2,
      "allowedValues": [
        0,
        1,
        2,
        3,
        4
      ],
      "metadata": {
        "description": "Severity of alert {0,1,2,3,4}"
      }
    },
    "autoMitigate": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert will automatically resolve"
      }
    },
    "query": {
      "type": "string",
      "minLength": 1,
      "defaultValue": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"ReadLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\", \"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk",
      "metadata": {
        "description": "Name of the metric used in the comparison to activate the alert."
      }
    },
    "metricMeasureColumn": {
      "type": "string",
      "defaultValue": "AggregatedValue",
      "metadata": {
        "description": "Name of the measure column used in the alert evaluation."
      }
    },
    "resourceIdColumn": {
      "type": "string",
      "defaultValue": "_ResourceId",
      "metadata": {
        "description": "Name of the resource ID column used in the alert targeting the alerts."
      }
    },
    "operator": {
      "type": "string",
      "defaultValue": "GreaterThan",
      "allowedValues": [
        "Equals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      }
    },
    "threshold": {
      "type": "string",
      "defaultValue": "25",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      }
    },
    "numberOfEvaluationPeriods": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of periods to check in the alert evaluation."
      }
    },
    "minFailingPeriodsToAlert": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods)."
      }
    },
    "timeAggregation": {
      "type": "string",
      "defaultValue": "Average",
      "allowedValues": [
        "Average",
        "Minimum",
        "Maximum",
        "Total",
        "Count"
      ],
      "metadata": {
        "description": "How the data that is collected should be combined over time."
      }
    },
    "windowSize": {
      "type": "string",
      "defaultValue": "PT15M",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H",
        "PT1D"
      ],
      "metadata": {
        "description": "Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format."
      }
    },
    "evaluationFrequency": {
      "type": "string",
      "defaultValue": "PT5M",
      "allowedValues": [
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H"
      ],
      "metadata": {
        "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
      }
    },
    "currentDateTimeUtcNow": {
      "type": "string",
      "defaultValue": "[utcNow()]",
      "metadata": {
          "description": "The current date and time using the utcNow function. Used for deployment name uniqueness"
      }
    },
    "telemetryOptOut": {
      "type": "string",
      "defaultValue": "No",
      "allowedValues": [
          "Yes",
          "No"
      ],
      "metadata": {
          "description": "The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry."
      }
    }
  },
  "variables": {
    "pidDeploymentName": "[take(concat('pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-', uniqueString(resourceGroup().id, parameters('alertName'), parameters('currentDateTimeUtcNow'))), 64)]"
  },
  "resources": [
    {
      "type": "Microsoft.Insights/scheduledQueryRules",
      "apiVersion": "2021-08-01",
      "name": "[parameters('alertName')]",
      "location": "[resourceGroup().location]",
      "tags": {
        "_deployed_by_amba": true
      },
      "properties": {
        "description": "[parameters('alertDescription')]",
        "severity": "[parameters('alertSeverity')]",
        "enabled": "[parameters('isEnabled')]",
        "scopes": [
          "[parameters('resourceId')]"
        ],
        "evaluationFrequency": "[parameters('evaluationFrequency')]",
        "windowSize": "[parameters('windowSize')]",
        "criteria": {
          "allOf": [
            {
              "query": "[parameters('query')]",
              "metricMeasureColumn": "[parameters('metricMeasureColumn')]",
              "resourceIdColumn": "[parameters('resourceIdColumn')]",
              "dimensions": [{"name": "Computer", "operator": "Include", "values": ["*"]}, {"name": "Disk", "operator": "Include", "values": ["*"]}],
              "operator": "[parameters('operator')]",
              "threshold": "[parameters('threshold')]",
              "timeAggregation": "[parameters('timeAggregation')]",
              "failingPeriods": {
                "numberOfEvaluationPeriods": "[parameters('numberOfEvaluationPeriods')]",
                "minFailingPeriodsToAlert": "[parameters('minFailingPeriodsToAlert')]"
              }
            }
          ]
        },
        "muteActionsDuration": "[parameters('muteActionsDuration')]",
        "autoMitigate": "[parameters('autoMitigate')]",
        "checkWorkspaceAlertsStorageConfigured": "[parameters('checkWorkspaceAlertsStorageConfigured')]"
      }
    },
    {
      "condition": "[equals(parameters('telemetryOptOut'), 'No')]",
      "apiVersion": "2023-07-01",
      "name": "[variables('pidDeploymentName')]",
      "type": "Microsoft.Resources/deployments",
      "properties": {
          "mode": "Incremental",
          "template": {
              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
              "contentVersion": "1.0.0.0",
              "resources": []
          }
      }
    }
  ]
}
@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'Log Alert for Hybrid Machine Data Disk Read Latency'

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

@description('Specifies whether to check linked storage and fail creation if the storage was not found')
param checkWorkspaceAlertsStorageConfigured bool = false

@description('Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz')
@minLength(1)
param resourceId string

@description('Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param muteActionsDuration string

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

@description('Specifies whether the alert will automatically resolve')
param autoMitigate bool = true

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param query string = 'InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "LogicalDisk" and Name == "ReadLatencyMs" | extend Disk=tostring(todynamic(Tags)["vm.azm.ms/mountId"]) | where Disk !in ("C:", "/") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk'

@description('Name of the measure column used in the alert evaluation.')
param metricMeasureColumn string = 'AggregatedValue'

@description('Name of the resource ID column used in the alert targeting the alerts.')
param resourceIdColumn string = '_ResourceId'

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

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

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

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

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

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

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

@description('"The current date and time using the utcNow function. Used for deployment name uniqueness')
param currentDateTimeUtcNow string = utcNow()

@description('The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry.')
@allowed([
  'Yes'
  'No'
])
param telemetryOptOut string = 'No'

resource alert 'Microsoft.Insights/scheduledQueryRules@2021-08-01' = {
  name: alertName
  location: resourceGroup().location
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      allOf: [
        {
          query: query
          metricMeasureColumn: metricMeasureColumn
          resourceIdColumn: resourceIdColumn
          dimensions: [
            {
              name: 'Computer'
              operator: 'Include'
              values: ['*']
            }
            {
              name: 'Disk'
              operator: 'Include'
              values: ['*']
            }]
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
        }
      ]
    }
    muteActionsDuration: muteActionsDuration
    autoMitigate: autoMitigate
    checkWorkspaceAlertsStorageConfigured: checkWorkspaceAlertsStorageConfigured
  }
}

var ambaTelemetryPidName = 'pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-${uniqueString(resourceGroup().id, alertName, currentDateTimeUtcNow)}'
resource ambaTelemetryPid 'Microsoft.Resources/deployments@2023-07-01' =  if (telemetryOptOut == 'No') {
  name: ambaTelemetryPidName
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    mode: 'Incremental'
    template: {
      '$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#'
      contentVersion: '1.0.0.0'
      resources: []
    }
  }
}
{
    "mode": "All",
    "parameters": {
      "alertResourceGroupName": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Name",
          "description": "Resource group the alert is placed in"
        },
        "defaultValue": "rg-amba-monitoring-001"
      },
      "alertResourceGroupTags": {
        "type": "Object",
        "metadata": {
          "displayName": "Resource Group Tags",
          "description": "Tags on the Resource group the alert is placed in"
        },
        "defaultValue": {
          "Project": "amba-monitoring"
        }
      },
      "alertResourceGroupLocation": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Location",
          "description": "Location of the Resource group the alert is placed in"
        },
        "defaultValue": "centralus"
      },
      "UAMIResourceId": {
        "type": "string",
        "defaultValue": "",
        "metadata": {
          "description": "The resource Id of the user assigned managed identity.",
          "displayName": "User Assigned managed Identity resource Id."
        }
      },
      "severity": {
        "type": "String",
        "metadata": {
          "displayName": "Severity",
          "description": "Severity of the Alert"
        },
        "allowedValues": [
          "0",
          "1",
          "2",
          "3",
          "4"
        ],
        "defaultValue": "2"
      },
      "operator": {
        "type": "String",
        "metadata": {
          "displayName": "Operator"
        },
        "allowedValues": [
          "GreaterThan"
        ],
        "defaultValue": "GreaterThan"
      },
      "timeAggregation": {
        "type": "String",
        "metadata": {
          "displayName": "TimeAggregation"
        },
        "allowedValues": [
          "Count"
        ],
        "defaultValue": "Count"
      },
      "windowSize": {
        "type": "String",
        "metadata": {
          "displayName": "Window Size",
          "description": "Window size for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H",
          "PT6H",
          "PT12H",
          "PT24H"
        ],
        "defaultValue": "PT15M"
      },
      "evaluationFrequency": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Frequency",
          "description": "Evaluation frequency for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H"
        ],
        "defaultValue": "PT5M"
      },
      "autoMitigate": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Mitigate",
          "description": "Auto Mitigate for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolve": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolveTime": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve time for the alert in ISO 8601 format"
        },
        "defaultValue": "true"
      },
      "enabled": {
        "type": "String",
        "metadata": {
          "displayName": "Alert State",
          "description": "Alert state for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "threshold": {
        "type": "String",
        "metadata": {
          "displayName": "Threshold",
          "description": "Threshold for the alert"
        },
        "defaultValue": "30"
      },
      "failingPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Failing Periods",
          "description": "Number of failing periods before alert is fired"
        },
        "defaultValue": "1"
      },
      "evaluationPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Periods",
          "description": "The number of aggregated lookback points."
        },
        "defaultValue": "1"
      },
      "computersToInclude": {
        "type": "array",
        "metadata": {
          "displayName": "Computers to be included to be monitored",
          "description": "Array of Computer to be monitored"
        },
        "defaultValue": [
          "*"
        ]
      },
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Effect of the policy"
        },
        "allowedValues": [
          "deployIfNotExists",
          "disabled"
        ],
        "defaultValue": "deployIfNotExists"
      },
      "MonitorDisableTagName": {
        "type": "String",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag name",
          "description": "Tag name to disable monitoring. Set to true if monitoring should be disabled"
        },
        "defaultValue": "MonitorDisable"
      },
      "MonitorDisableTagValues": {
        "type": "Array",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag values(s)",
          "description": "Tag value(s) used to disable monitoring at the resource level. Set to true if monitoring should be disabled."
        },
        "defaultValue": [
          "true",
          "Test",
          "Dev",
          "Sandbox"
        ]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.HybridCompute/machines"
          },
          {
            "field": "[concat('tags[', parameters('MonitorDisableTagName'), ']')]",
            "notIn": "[parameters('MonitorDisableTagValues')]"
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ],
          "type": "Microsoft.Insights/scheduledQueryRules",
          "existenceScope": "resourceGroup",
          "resourceGroupName": "[parameters('alertResourceGroupName')]",
          "deploymentScope": "subscription",
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Insights/scheduledQueryRules/displayName",
                "equals": "[concat(subscription().displayName, '-HybridVMHighDataDiskReadLatencyAlert')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/scopes[*]",
                "equals": "[subscription().id]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/enabled",
                "equals": "[parameters('enabled')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/evaluationFrequency",
                "equals": "[parameters('evaluationFrequency')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/windowSize",
                "equals": "[parameters('windowSize')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/severity",
                "equals": "[parameters('severity')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/autoMitigate",
                "equals": "[parameters('autoMitigate')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].operator",
                "equals": "[parameters('operator')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].timeAggregation",
                "equals": "[parameters('timeAggregation')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.numberOfEvaluationPeriods",
                "equals": "[parameters('evaluationPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.minFailingPeriodsToAlert",
                "equals": "[parameters('failingPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].query",
                "equals": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-ReadLatencyMs-Data-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"ReadLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\", \"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-ReadLatencyMs-Data-threshold-Override_\", tostring(tags.[\"_amba-ReadLatencyMs-Data-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue > appliedThreshold | project TimeGenerated, Computer, _ResourceId, Disk, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]"
              },
              {
                "field": "identity.userAssignedIdentities",
                "containsKey": "[parameters('UAMIResourceId')]"
              }
            ]
          },
          "deployment": {
            "location": "northeurope",
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "alertResourceGroupName": {
                    "type": "string"
                  },
                  "alertResourceGroupTags": {
                    "type": "object"
                  },
                  "alertResourceGroupLocation": {
                    "type": "string"
                  },
                  "UAMIResourceId": {
                    "type": "string"
                  },
                  "severity": {
                    "type": "String"
                  },
                  "windowSize": {
                    "type": "String"
                  },
                  "evaluationFrequency": {
                    "type": "String"
                  },
                  "autoMitigate": {
                    "type": "String"
                  },
                  "autoResolve": {
                    "type": "String"
                  },
                  "autoResolveTime": {
                    "type": "String"
                  },
                  "enabled": {
                    "type": "String"
                  },
                  "threshold": {
                    "type": "String"
                  },
                  "operator": {
                    "type": "String"
                  },
                  "timeAggregation": {
                    "type": "String"
                  },
                  "failingPeriods": {
                    "type": "String"
                  },
                  "evaluationPeriods": {
                    "type": "String"
                  },
                  "computersToInclude": {
                    "type": "array"
                  },
                  "MonitorDisableTagName": {
                    "type": "String"
                  },
                  "MonitorDisableTagValues": {
                    "type": "Array"
                  }
                },
                "variables": {},
                "resources": [
                  {
                    "type": "Microsoft.Resources/resourceGroups",
                    "apiVersion": "2021-04-01",
                    "name": "[parameters('alertResourceGroupName')]",
                    "location": "[parameters('alertResourceGroupLocation')]",
                    "tags": "[parameters('alertResourceGroupTags')]"
                  },
                  {
                    "type": "Microsoft.Resources/deployments",
                    "apiVersion": "2019-10-01",
                    "name": "HybridVMdataDiskReadLatencyAlert",
                    "resourceGroup": "[parameters('alertResourceGroupName')]",
                    "dependsOn": [
                      "[concat('Microsoft.Resources/resourceGroups/', parameters('alertResourceGroupName'))]"
                    ],
                    "properties": {
                      "mode": "Incremental",
                      "template": {
                        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                        "contentVersion": "1.0.0.0",
                        "parameters": {
                          "enabled": {
                            "type": "string"
                          },
                          "alertResourceGroupName": {
                            "type": "string"
                          },
                          "alertResourceGroupLocation": {
                            "type": "string"
                          },
                          "UAMIResourceId": {
                            "type": "string"
                          }
                        },
                        "variables": {},
                        "resources": [
                          {
                            "type": "Microsoft.Insights/scheduledQueryRules",
                            "apiVersion": "2022-08-01-preview",
                            "name": "[concat(subscription().displayName, '-HybridVMHighDataDiskReadLatencyAlert')]",
                            "location": "[parameters('alertResourceGroupLocation')]",
                            "identity": {
                              "type": "UserAssigned",
                              "userAssignedIdentities": {
                                "[parameters('UAMIResourceId')]": {}
                              }
                            },
                            "tags": {
                              "_deployed_by_amba": true
                            },
                            "properties": {
                              "displayName": "[concat(subscription().displayName, '-HybridVMHighDataDiskReadLatencyAlert')]",
                              "description": "Log Alert for Virtual Machine dataDiskReadLatency",
                              "severity": "[parameters('severity')]",
                              "enabled": "[parameters('enabled')]",
                              "scopes": [
                                "[subscription().Id]"
                              ],
                              "targetResourceTypes": [
                                "Microsoft.HybridCompute/machines"
                              ],
                              "evaluationFrequency": "[parameters('evaluationFrequency')]",
                              "windowSize": "[parameters('windowSize')]",
                              "criteria": {
                                "allOf": [
                                  {
                                    "query": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-ReadLatencyMs-Data-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"ReadLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\", \"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-ReadLatencyMs-Data-threshold-Override_\", tostring(tags.[\"_amba-ReadLatencyMs-Data-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue > appliedThreshold | project TimeGenerated, Computer, _ResourceId, Disk, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]",
                                    "threshold": 0,
                                    "operator": "[parameters('operator')]",
                                    "resourceIdColumn": "_ResourceId",
                                    "timeAggregation": "[parameters('timeAggregation')]",
                                    "dimensions": [
                                      {
                                        "name": "Computer",
                                        "operator": "Include",
                                        "values": "[parameters('computersToInclude')]"
                                      },
                                      {
                                        "name": "Disk",
                                        "operator": "Include",
                                        "values": [
                                          "*"
                                        ]
                                      }
                                    ],
                                    "failingPeriods": {
                                      "numberOfEvaluationPeriods": "[parameters('evaluationPeriods')]",
                                      "minFailingPeriodsToAlert": "[parameters('failingPeriods')]"
                                    }
                                  }
                                ]
                              },
                              "autoMitigate": "[parameters('autoMitigate')]",
                              "ruleResolveConfiguration": {
                                "autoResolved": "[parameters('autoResolve')]",
                                "timeToResolve": "[parameters('autoResolveTime')]"
                              },
                              "parameters": {
                                "alertResourceGroupName": {
                                  "value": "[parameters('alertResourceGroupName')]"
                                },
                                "alertResourceGroupLocation": {
                                  "value": "[parameters('alertResourceGroupLocation')]"
                                },
                                "UAMIResourceId": {
                                  "value": "[parameters('UAMIResourceId')]"
                                },
                                "severity": {
                                  "value": "[parameters('severity')]"
                                },
                                "windowSize": {
                                  "value": "[parameters('windowSize')]"
                                },
                                "evaluationFrequency": {
                                  "value": "[parameters('evaluationFrequency')]"
                                },
                                "autoMitigate": {
                                  "value": "[parameters('autoMitigate')]"
                                },
                                "autoResolve": {
                                  "value": "[parameters('autoResolve')]"
                                },
                                "autoResolveTime": {
                                  "value": "[parameters('autoResolveTime')]"
                                },
                                "enabled": {
                                  "value": "[parameters('enabled')]"
                                },
                                "threshold": {
                                  "value": "[parameters('threshold')]"
                                },
                                "failingPeriods": {
                                  "value": "[parameters('failingPeriods')]"
                                },
                                "evaluationPeriods": {
                                  "value": "[parameters('evaluationPeriods')]"
                                },
                                "computersToInclude": {
                                  "value": "[parameters('computersToInclude')]"
                                },
                                "MonitorDisableTagName": {
                                  "value": "[parameters('MonitorDisableTagName')]"
                                },
                                "MonitorDisableTagValues": {
                                  "value": "[parameters('MonitorDisableTagValues')]"
                                }
                              }
                            }
                          }
                        ]
                      },
                      "parameters": {
                        "enabled": {
                          "value": "[parameters('enabled')]"
                        },
                        "alertResourceGroupName": {
                          "value": "[parameters('alertResourceGroupName')]"
                        },
                        "alertResourceGroupLocation": {
                          "value": "[parameters('alertResourceGroupLocation')]"
                        },
                        "UAMIResourceId": {
                          "value": "[parameters('UAMIResourceId')]"
                        }
                      }
                    }
                  }
                ]
              },
              "parameters": {
                "alertResourceGroupName": {
                  "value": "[parameters('alertResourceGroupName')]"
                },
                "alertResourceGroupTags": {
                  "value": "[parameters('alertResourceGroupTags')]"
                },
                "alertResourceGroupLocation": {
                  "value": "[parameters('alertResourceGroupLocation')]"
                },
                "UAMIResourceId": {
                  "value": "[parameters('UAMIResourceId')]"
                },
                "severity": {
                  "value": "[parameters('severity')]"
                },
                "windowSize": {
                  "value": "[parameters('windowSize')]"
                },
                "evaluationFrequency": {
                  "value": "[parameters('evaluationFrequency')]"
                },
                "autoMitigate": {
                  "value": "[parameters('autoMitigate')]"
                },
                "autoResolve": {
                  "value": "[parameters('autoResolve')]"
                },
                "autoResolveTime": {
                  "value": "[parameters('autoResolveTime')]"
                },
                "enabled": {
                  "value": "[parameters('enabled')]"
                },
                "threshold": {
                  "value": "[parameters('threshold')]"
                },
                "operator": {
                  "value": "[parameters('operator')]"
                },
                "timeAggregation": {
                  "value": "[parameters('timeAggregation')]"
                },
                "failingPeriods": {
                  "value": "[parameters('failingPeriods')]"
                },
                "evaluationPeriods": {
                  "value": "[parameters('evaluationPeriods')]"
                },
                "computersToInclude": {
                  "value": "[parameters('computersToInclude')]"
                },
                "MonitorDisableTagName": {
                  "value": "[parameters('MonitorDisableTagName')]"
                },
                "MonitorDisableTagValues": {
                  "value": "[parameters('MonitorDisableTagValues')]"
                }
              }
            }
          }
        }
      }
    }
  }



Hybrid Machine Data Disk Write Latency Alert - Log Alert

Log Alert for Hybrid Machine Data Disk Write Latency (ms)

Properties:

autoMitigatetrue
autoResolvetrue
autoResolveTime0:10:00
dimensions
[
  {
    "name": "Computer",
    "operator": "Include",
    "values": [
      "*"
    ]
  },
  {
    "name": "Disk",
    "operator": "Include",
    "values": [
      "*"
    ]
  }
]
evaluationFrequencyPT5M
failingPeriods
{
  "minFailingPeriodsToAlert": 1,
  "numberOfEvaluationPeriods": 1
}
metricMeasureColumnAggregatedValue
operatorGreaterThan
query
InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "LogicalDisk" and Name == "WriteLatencyMs" | extend Disk=tostring(todynamic(Tags)["vm.azm.ms/mountId"]) | where Disk !in ("C:","/") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer, _ResourceId, Disk
resouceIdColumn_ResourceId
severity2
threshold25
timeAggregationAverage
windowSizePT15M

References:

Templates:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Name of the alert"
      }
    },
    "alertDescription": {
      "type": "string",
      "defaultValue": "Log Alert for Hybrid Machine Data Disk Write Latency (ms)",
      "metadata": {
        "description": "Description of alert"
      }
    },
    "isEnabled": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert is enabled"
      }
    },
    "checkWorkspaceAlertsStorageConfigured": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies whether to check linked storage and fail creation if the storage was not found"
      }
    },
    "resourceId": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
      }
    },
    "muteActionsDuration": {
      "type": "string",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H"
      ],
      "metadata": {
        "description": "Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired."
      }
    },
    "alertSeverity": {
      "type": "int",
      "defaultValue": 2,
      "allowedValues": [
        0,
        1,
        2,
        3,
        4
      ],
      "metadata": {
        "description": "Severity of alert {0,1,2,3,4}"
      }
    },
    "autoMitigate": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert will automatically resolve"
      }
    },
    "query": {
      "type": "string",
      "minLength": 1,
      "defaultValue": "InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"WriteLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer, _ResourceId, Disk",
      "metadata": {
        "description": "Name of the metric used in the comparison to activate the alert."
      }
    },
    "metricMeasureColumn": {
      "type": "string",
      "defaultValue": "AggregatedValue",
      "metadata": {
        "description": "Name of the measure column used in the alert evaluation."
      }
    },
    "resourceIdColumn": {
      "type": "string",
      "defaultValue": "_ResourceId",
      "metadata": {
        "description": "Name of the resource ID column used in the alert targeting the alerts."
      }
    },
    "operator": {
      "type": "string",
      "defaultValue": "GreaterThan",
      "allowedValues": [
        "Equals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      }
    },
    "threshold": {
      "type": "string",
      "defaultValue": "25",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      }
    },
    "numberOfEvaluationPeriods": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of periods to check in the alert evaluation."
      }
    },
    "minFailingPeriodsToAlert": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods)."
      }
    },
    "timeAggregation": {
      "type": "string",
      "defaultValue": "Average",
      "allowedValues": [
        "Average",
        "Minimum",
        "Maximum",
        "Total",
        "Count"
      ],
      "metadata": {
        "description": "How the data that is collected should be combined over time."
      }
    },
    "windowSize": {
      "type": "string",
      "defaultValue": "PT15M",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H",
        "PT1D"
      ],
      "metadata": {
        "description": "Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format."
      }
    },
    "evaluationFrequency": {
      "type": "string",
      "defaultValue": "PT5M",
      "allowedValues": [
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H"
      ],
      "metadata": {
        "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
      }
    },
    "currentDateTimeUtcNow": {
      "type": "string",
      "defaultValue": "[utcNow()]",
      "metadata": {
          "description": "The current date and time using the utcNow function. Used for deployment name uniqueness"
      }
    },
    "telemetryOptOut": {
      "type": "string",
      "defaultValue": "No",
      "allowedValues": [
          "Yes",
          "No"
      ],
      "metadata": {
          "description": "The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry."
      }
    }
  },
  "variables": {
    "pidDeploymentName": "[take(concat('pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-', uniqueString(resourceGroup().id, parameters('alertName'), parameters('currentDateTimeUtcNow'))), 64)]"
  },
  "resources": [
    {
      "type": "Microsoft.Insights/scheduledQueryRules",
      "apiVersion": "2021-08-01",
      "name": "[parameters('alertName')]",
      "location": "[resourceGroup().location]",
      "tags": {
        "_deployed_by_amba": true
      },
      "properties": {
        "description": "[parameters('alertDescription')]",
        "severity": "[parameters('alertSeverity')]",
        "enabled": "[parameters('isEnabled')]",
        "scopes": [
          "[parameters('resourceId')]"
        ],
        "evaluationFrequency": "[parameters('evaluationFrequency')]",
        "windowSize": "[parameters('windowSize')]",
        "criteria": {
          "allOf": [
            {
              "query": "[parameters('query')]",
              "metricMeasureColumn": "[parameters('metricMeasureColumn')]",
              "resourceIdColumn": "[parameters('resourceIdColumn')]",
              "dimensions": [{"name": "Computer", "operator": "Include", "values": ["*"]}, {"name": "Disk", "operator": "Include", "values": ["*"]}],
              "operator": "[parameters('operator')]",
              "threshold": "[parameters('threshold')]",
              "timeAggregation": "[parameters('timeAggregation')]",
              "failingPeriods": {
                "numberOfEvaluationPeriods": "[parameters('numberOfEvaluationPeriods')]",
                "minFailingPeriodsToAlert": "[parameters('minFailingPeriodsToAlert')]"
              }
            }
          ]
        },
        "muteActionsDuration": "[parameters('muteActionsDuration')]",
        "autoMitigate": "[parameters('autoMitigate')]",
        "checkWorkspaceAlertsStorageConfigured": "[parameters('checkWorkspaceAlertsStorageConfigured')]"
      }
    },
    {
      "condition": "[equals(parameters('telemetryOptOut'), 'No')]",
      "apiVersion": "2023-07-01",
      "name": "[variables('pidDeploymentName')]",
      "type": "Microsoft.Resources/deployments",
      "properties": {
          "mode": "Incremental",
          "template": {
              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
              "contentVersion": "1.0.0.0",
              "resources": []
          }
      }
    }
  ]
}
@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'Log Alert for Hybrid Machine Data Disk Write Latency (ms)'

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

@description('Specifies whether to check linked storage and fail creation if the storage was not found')
param checkWorkspaceAlertsStorageConfigured bool = false

@description('Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz')
@minLength(1)
param resourceId string

@description('Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param muteActionsDuration string

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

@description('Specifies whether the alert will automatically resolve')
param autoMitigate bool = true

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param query string = 'InsightsMetrics | where _ResourceId has "Microsoft.HybridCompute/machines" | where Origin == "vm.azm.ms" | where Namespace == "LogicalDisk" and Name == "WriteLatencyMs" | extend Disk=tostring(todynamic(Tags)["vm.azm.ms/mountId"]) | where Disk !in ("C:","/") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated,15m), Computer, _ResourceId, Disk'

@description('Name of the measure column used in the alert evaluation.')
param metricMeasureColumn string = 'AggregatedValue'

@description('Name of the resource ID column used in the alert targeting the alerts.')
param resourceIdColumn string = '_ResourceId'

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

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

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

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

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

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

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

@description('"The current date and time using the utcNow function. Used for deployment name uniqueness')
param currentDateTimeUtcNow string = utcNow()

@description('The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry.')
@allowed([
  'Yes'
  'No'
])
param telemetryOptOut string = 'No'

resource alert 'Microsoft.Insights/scheduledQueryRules@2021-08-01' = {
  name: alertName
  location: resourceGroup().location
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      allOf: [
        {
          query: query
          metricMeasureColumn: metricMeasureColumn
          resourceIdColumn: resourceIdColumn
          dimensions: [
            {
              name: 'Computer'
              operator: 'Include'
              values: ['*']
            }
            {
              name: 'Disk'
              operator: 'Include'
              values: ['*']
            }]
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
        }
      ]
    }
    muteActionsDuration: muteActionsDuration
    autoMitigate: autoMitigate
    checkWorkspaceAlertsStorageConfigured: checkWorkspaceAlertsStorageConfigured
  }
}

var ambaTelemetryPidName = 'pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-${uniqueString(resourceGroup().id, alertName, currentDateTimeUtcNow)}'
resource ambaTelemetryPid 'Microsoft.Resources/deployments@2023-07-01' =  if (telemetryOptOut == 'No') {
  name: ambaTelemetryPidName
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    mode: 'Incremental'
    template: {
      '$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#'
      contentVersion: '1.0.0.0'
      resources: []
    }
  }
}
{
    "mode": "All",
    "parameters": {
      "alertResourceGroupName": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Name",
          "description": "Resource group the alert is placed in"
        },
        "defaultValue": "rg-amba-monitoring-001"
      },
      "alertResourceGroupTags": {
        "type": "Object",
        "metadata": {
          "displayName": "Resource Group Tags",
          "description": "Tags on the Resource group the alert is placed in"
        },
        "defaultValue": {
          "Project": "amba-monitoring"
        }
      },
      "alertResourceGroupLocation": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Location",
          "description": "Location of the Resource group the alert is placed in"
        },
        "defaultValue": "centralus"
      },
      "UAMIResourceId": {
        "type": "string",
        "defaultValue": "",
        "metadata": {
          "description": "The resource Id of the user assigned managed identity.",
          "displayName": "User Assigned managed Identity resource Id."
        }
      },
      "severity": {
        "type": "String",
        "metadata": {
          "displayName": "Severity",
          "description": "Severity of the Alert"
        },
        "allowedValues": [
          "0",
          "1",
          "2",
          "3",
          "4"
        ],
        "defaultValue": "2"
      },
      "operator": {
        "type": "String",
        "metadata": {
          "displayName": "Operator"
        },
        "allowedValues": [
          "GreaterThan"
        ],
        "defaultValue": "GreaterThan"
      },
      "timeAggregation": {
        "type": "String",
        "metadata": {
          "displayName": "TimeAggregation"
        },
        "allowedValues": [
          "Count"
        ],
        "defaultValue": "Count"
      },
      "windowSize": {
        "type": "String",
        "metadata": {
          "displayName": "Window Size",
          "description": "Window size for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H",
          "PT6H",
          "PT12H",
          "PT24H"
        ],
        "defaultValue": "PT15M"
      },
      "evaluationFrequency": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Frequency",
          "description": "Evaluation frequency for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H"
        ],
        "defaultValue": "PT5M"
      },
      "autoMitigate": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Mitigate",
          "description": "Auto Mitigate for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolve": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolveTime": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve time for the alert in ISO 8601 format"
        },
        "defaultValue": "true"
      },
      "enabled": {
        "type": "String",
        "metadata": {
          "displayName": "Alert State",
          "description": "Alert state for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "threshold": {
        "type": "String",
        "metadata": {
          "displayName": "Threshold",
          "description": "Threshold for the alert"
        },
        "defaultValue": "30"
      },
      "failingPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Failing Periods",
          "description": "Number of failing periods before alert is fired"
        },
        "defaultValue": "1"
      },
      "evaluationPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Periods",
          "description": "The number of aggregated lookback points."
        },
        "defaultValue": "1"
      },
      "computersToInclude": {
        "type": "array",
        "metadata": {
          "displayName": "Computers to be included to be monitored",
          "description": "Array of Computer to be monitored"
        },
        "defaultValue": [
          "*"
        ]
      },
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Effect of the policy"
        },
        "allowedValues": [
          "deployIfNotExists",
          "disabled"
        ],
        "defaultValue": "deployIfNotExists"
      },
      "MonitorDisableTagName": {
        "type": "String",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag name",
          "description": "Tag name to disable monitoring. Set to true if monitoring should be disabled"
        },
        "defaultValue": "MonitorDisable"
      },
      "MonitorDisableTagValues": {
        "type": "Array",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag values(s)",
          "description": "Tag value(s) used to disable monitoring at the resource level. Set to true if monitoring should be disabled."
        },
        "defaultValue": [
          "true",
          "Test",
          "Dev",
          "Sandbox"
        ]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.HybridCompute/machines"
          },
          {
            "field": "[concat('tags[', parameters('MonitorDisableTagName'), ']')]",
            "notIn": "[parameters('MonitorDisableTagValues')]"
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ],
          "type": "Microsoft.Insights/scheduledQueryRules",
          "existenceScope": "resourceGroup",
          "resourceGroupName": "[parameters('alertResourceGroupName')]",
          "deploymentScope": "subscription",
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Insights/scheduledQueryRules/displayName",
                "equals": "[concat(subscription().displayName, '-HybridVMHighDataDiskWriteLatencyAlert')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/scopes[*]",
                "equals": "[subscription().id]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/enabled",
                "equals": "[parameters('enabled')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/evaluationFrequency",
                "equals": "[parameters('evaluationFrequency')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/windowSize",
                "equals": "[parameters('windowSize')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/severity",
                "equals": "[parameters('severity')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/autoMitigate",
                "equals": "[parameters('autoMitigate')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].operator",
                "equals": "[parameters('operator')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].timeAggregation",
                "equals": "[parameters('timeAggregation')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.numberOfEvaluationPeriods",
                "equals": "[parameters('evaluationPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.minFailingPeriodsToAlert",
                "equals": "[parameters('failingPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].query",
                "equals": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-WriteLatencyMs-Data-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"WriteLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-WriteLatencyMs-Data-threshold-Override_\", tostring(tags.[\"_amba-WriteLatencyMs-Data-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue > appliedThreshold | project TimeGenerated, Computer, _ResourceId, Disk, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]"
              },
              {
                "field": "identity.userAssignedIdentities",
                "containsKey": "[parameters('UAMIResourceId')]"
              }
            ]
          },
          "deployment": {
            "location": "northeurope",
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "alertResourceGroupName": {
                    "type": "string"
                  },
                  "alertResourceGroupTags": {
                    "type": "object"
                  },
                  "alertResourceGroupLocation": {
                    "type": "string"
                  },
                  "UAMIResourceId": {
                    "type": "string"
                  },
                  "severity": {
                    "type": "String"
                  },
                  "windowSize": {
                    "type": "String"
                  },
                  "evaluationFrequency": {
                    "type": "String"
                  },
                  "autoMitigate": {
                    "type": "String"
                  },
                  "autoResolve": {
                    "type": "String"
                  },
                  "autoResolveTime": {
                    "type": "String"
                  },
                  "enabled": {
                    "type": "String"
                  },
                  "threshold": {
                    "type": "String"
                  },
                  "operator": {
                    "type": "String"
                  },
                  "timeAggregation": {
                    "type": "String"
                  },
                  "failingPeriods": {
                    "type": "String"
                  },
                  "evaluationPeriods": {
                    "type": "String"
                  },
                  "computersToInclude": {
                    "type": "array"
                  },
                  "MonitorDisableTagName": {
                    "type": "String"
                  },
                  "MonitorDisableTagValues": {
                    "type": "Array"
                  }
                },
                "variables": {},
                "resources": [
                  {
                    "type": "Microsoft.Resources/resourceGroups",
                    "apiVersion": "2021-04-01",
                    "name": "[parameters('alertResourceGroupName')]",
                    "location": "[parameters('alertResourceGroupLocation')]",
                    "tags": "[parameters('alertResourceGroupTags')]"
                  },
                  {
                    "type": "Microsoft.Resources/deployments",
                    "apiVersion": "2019-10-01",
                    "name": "HybridVMdataDiskWriteLatencyAlert",
                    "resourceGroup": "[parameters('alertResourceGroupName')]",
                    "dependsOn": [
                      "[concat('Microsoft.Resources/resourceGroups/', parameters('alertResourceGroupName'))]"
                    ],
                    "properties": {
                      "mode": "Incremental",
                      "template": {
                        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                        "contentVersion": "1.0.0.0",
                        "parameters": {
                          "enabled": {
                            "type": "string"
                          },
                          "alertResourceGroupName": {
                            "type": "string"
                          },
                          "alertResourceGroupLocation": {
                            "type": "string"
                          },
                          "UAMIResourceId": {
                            "type": "string"
                          }
                        },
                        "variables": {},
                        "resources": [
                          {
                            "type": "Microsoft.Insights/scheduledQueryRules",
                            "apiVersion": "2022-08-01-preview",
                            "name": "[concat(subscription().displayName, '-HybridVMHighDataDiskWriteLatencyAlert')]",
                            "location": "[parameters('alertResourceGroupLocation')]",
                            "identity": {
                              "type": "UserAssigned",
                              "userAssignedIdentities": {
                                "[parameters('UAMIResourceId')]": {}
                              }
                            },
                            "tags": {
                              "_deployed_by_amba": true
                            },
                            "properties": {
                              "displayName": "[concat(subscription().displayName, '-HybridVMHighDataDiskWriteLatencyAlert')]",
                              "description": "Log Alert for Virtual Machine dataDiskWriteLatency",
                              "severity": "[parameters('severity')]",
                              "enabled": "[parameters('enabled')]",
                              "scopes": [
                                "[subscription().Id]"
                              ],
                              "targetResourceTypes": [
                                "Microsoft.HybridCompute/machines"
                              ],
                              "evaluationFrequency": "[parameters('evaluationFrequency')]",
                              "windowSize": "[parameters('windowSize')]",
                              "criteria": {
                                "allOf": [
                                  {
                                    "query": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-WriteLatencyMs-Data-threshold-Override_\"); InsightsMetrics | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | where Origin == \"vm.azm.ms\" | where Namespace == \"LogicalDisk\" and Name == \"WriteLatencyMs\" | extend Disk=tostring(todynamic(Tags)[\"vm.azm.ms/mountId\"]) | where Disk !in (\"C:\",\"/\") | summarize AggregatedValue = avg(Val) by bin(TimeGenerated, 15m), Computer, _ResourceId, Disk | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-WriteLatencyMs-Data-threshold-Override_\", tostring(tags.[\"_amba-WriteLatencyMs-Data-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where AggregatedValue > appliedThreshold | project TimeGenerated, Computer, _ResourceId, Disk, AggregatedValue', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]",
                                    "threshold": 0,
                                    "operator": "[parameters('operator')]",
                                    "resourceIdColumn": "_ResourceId",
                                    "timeAggregation": "[parameters('timeAggregation')]",
                                    "dimensions": [
                                      {
                                        "name": "Computer",
                                        "operator": "Include",
                                        "values": "[parameters('computersToInclude')]"
                                      },
                                      {
                                        "name": "Disk",
                                        "operator": "Include",
                                        "values": [
                                          "*"
                                        ]
                                      }
                                    ],
                                    "failingPeriods": {
                                      "numberOfEvaluationPeriods": "[parameters('evaluationPeriods')]",
                                      "minFailingPeriodsToAlert": "[parameters('failingPeriods')]"
                                    }
                                  }
                                ]
                              },
                              "autoMitigate": "[parameters('autoMitigate')]",
                              "ruleResolveConfiguration": {
                                "autoResolved": "[parameters('autoResolve')]",
                                "timeToResolve": "[parameters('autoResolveTime')]"
                              },
                              "parameters": {
                                "alertResourceGroupName": {
                                  "value": "[parameters('alertResourceGroupName')]"
                                },
                                "alertResourceGroupLocation": {
                                  "value": "[parameters('alertResourceGroupLocation')]"
                                },
                                "UAMIResourceId": {
                                  "value": "[parameters('UAMIResourceId')]"
                                },
                                "severity": {
                                  "value": "[parameters('severity')]"
                                },
                                "windowSize": {
                                  "value": "[parameters('windowSize')]"
                                },
                                "evaluationFrequency": {
                                  "value": "[parameters('evaluationFrequency')]"
                                },
                                "autoMitigate": {
                                  "value": "[parameters('autoMitigate')]"
                                },
                                "autoResolve": {
                                  "value": "[parameters('autoResolve')]"
                                },
                                "autoResolveTime": {
                                  "value": "[parameters('autoResolveTime')]"
                                },
                                "enabled": {
                                  "value": "[parameters('enabled')]"
                                },
                                "threshold": {
                                  "value": "[parameters('threshold')]"
                                },
                                "failingPeriods": {
                                  "value": "[parameters('failingPeriods')]"
                                },
                                "evaluationPeriods": {
                                  "value": "[parameters('evaluationPeriods')]"
                                },
                                "computersToInclude": {
                                  "value": "[parameters('computersToInclude')]"
                                },
                                "MonitorDisableTagName": {
                                  "value": "[parameters('MonitorDisableTagName')]"
                                },
                                "MonitorDisableTagValues": {
                                  "value": "[parameters('MonitorDisableTagValues')]"
                                }
                              }
                            }
                          }
                        ]
                      },
                      "parameters": {
                        "enabled": {
                          "value": "[parameters('enabled')]"
                        },
                        "alertResourceGroupName": {
                          "value": "[parameters('alertResourceGroupName')]"
                        },
                        "alertResourceGroupLocation": {
                          "value": "[parameters('alertResourceGroupLocation')]"
                        },
                        "UAMIResourceId": {
                          "value": "[parameters('UAMIResourceId')]"
                        }
                      }
                    }
                  }
                ]
              },
              "parameters": {
                "alertResourceGroupName": {
                  "value": "[parameters('alertResourceGroupName')]"
                },
                "alertResourceGroupTags": {
                  "value": "[parameters('alertResourceGroupTags')]"
                },
                "alertResourceGroupLocation": {
                  "value": "[parameters('alertResourceGroupLocation')]"
                },
                "UAMIResourceId": {
                  "value": "[parameters('UAMIResourceId')]"
                },
                "severity": {
                  "value": "[parameters('severity')]"
                },
                "windowSize": {
                  "value": "[parameters('windowSize')]"
                },
                "evaluationFrequency": {
                  "value": "[parameters('evaluationFrequency')]"
                },
                "autoMitigate": {
                  "value": "[parameters('autoMitigate')]"
                },
                "autoResolve": {
                  "value": "[parameters('autoResolve')]"
                },
                "autoResolveTime": {
                  "value": "[parameters('autoResolveTime')]"
                },
                "enabled": {
                  "value": "[parameters('enabled')]"
                },
                "threshold": {
                  "value": "[parameters('threshold')]"
                },
                "operator": {
                  "value": "[parameters('operator')]"
                },
                "timeAggregation": {
                  "value": "[parameters('timeAggregation')]"
                },
                "failingPeriods": {
                  "value": "[parameters('failingPeriods')]"
                },
                "evaluationPeriods": {
                  "value": "[parameters('evaluationPeriods')]"
                },
                "computersToInclude": {
                  "value": "[parameters('computersToInclude')]"
                },
                "MonitorDisableTagName": {
                  "value": "[parameters('MonitorDisableTagName')]"
                },
                "MonitorDisableTagValues": {
                  "value": "[parameters('MonitorDisableTagValues')]"
                }
              }
            }
          }
        }
      }
    }
  }



Hybrid Machine Heartbeat Alert - Log Alert

Log Alert for Hybrid Machine Heartbeat

Properties:

autoMitigatetrue
autoResolvetrue
autoResolveTime0:10:00
dimensions
[
  {
    "name": "Computer",
    "operator": "Include",
    "values": [
      "*"
    ]
  },
  {
    "name": "Disk",
    "operator": "Include",
    "values": [
      "*"
    ]
  }
]
evaluationFrequencyPT5M
failingPeriods
{
  "minFailingPeriodsToAlert": 1,
  "numberOfEvaluationPeriods": 1
}
metricMeasureColumnAggregatedValue
operatorGreaterThan
query
Heartbeat | where _ResourceId has "Microsoft.HybridCompute/machines" | summarize TimeGenerated=max(TimeGenerated) by Computer, _ResourceId | extend Duration = datetime_diff("minute",now(),TimeGenerated) | summarize AggregatedValue = min(Duration) by Computer, bin(TimeGenerated,5m), _ResourceId
resouceIdColumn_ResourceId
severity1
threshold10
timeAggregationAverage
windowSizePT15M

References:

Templates:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "alertName": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Name of the alert"
      }
    },
    "alertDescription": {
      "type": "string",
      "defaultValue": "Log Alert for Hybrid Machine Heartbeat",
      "metadata": {
        "description": "Description of alert"
      }
    },
    "isEnabled": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert is enabled"
      }
    },
    "checkWorkspaceAlertsStorageConfigured": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Specifies whether to check linked storage and fail creation if the storage was not found"
      }
    },
    "resourceId": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz"
      }
    },
    "muteActionsDuration": {
      "type": "string",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H"
      ],
      "metadata": {
        "description": "Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired."
      }
    },
    "alertSeverity": {
      "type": "int",
      "defaultValue": 1,
      "allowedValues": [
        0,
        1,
        2,
        3,
        4
      ],
      "metadata": {
        "description": "Severity of alert {0,1,2,3,4}"
      }
    },
    "autoMitigate": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Specifies whether the alert will automatically resolve"
      }
    },
    "query": {
      "type": "string",
      "minLength": 1,
      "defaultValue": "Heartbeat | where _ResourceId has \"Microsoft.HybridCompute/machines\" | summarize TimeGenerated=max(TimeGenerated) by Computer, _ResourceId | extend Duration = datetime_diff(\"minute\",now(),TimeGenerated) | summarize AggregatedValue = min(Duration) by Computer, bin(TimeGenerated,5m), _ResourceId",
      "metadata": {
        "description": "Name of the metric used in the comparison to activate the alert."
      }
    },
    "metricMeasureColumn": {
      "type": "string",
      "defaultValue": "AggregatedValue",
      "metadata": {
        "description": "Name of the measure column used in the alert evaluation."
      }
    },
    "resourceIdColumn": {
      "type": "string",
      "defaultValue": "_ResourceId",
      "metadata": {
        "description": "Name of the resource ID column used in the alert targeting the alerts."
      }
    },
    "operator": {
      "type": "string",
      "defaultValue": "GreaterThan",
      "allowedValues": [
        "Equals",
        "GreaterThan",
        "GreaterThanOrEqual",
        "LessThan",
        "LessThanOrEqual"
      ],
      "metadata": {
        "description": "Operator comparing the current value with the threshold value."
      }
    },
    "threshold": {
      "type": "string",
      "defaultValue": "10",
      "metadata": {
        "description": "The threshold value at which the alert is activated."
      }
    },
    "numberOfEvaluationPeriods": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of periods to check in the alert evaluation."
      }
    },
    "minFailingPeriodsToAlert": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of unhealthy periods to alert on (must be lower or equal to numberOfEvaluationPeriods)."
      }
    },
    "timeAggregation": {
      "type": "string",
      "defaultValue": "Average",
      "allowedValues": [
        "Average",
        "Minimum",
        "Maximum",
        "Total",
        "Count"
      ],
      "metadata": {
        "description": "How the data that is collected should be combined over time."
      }
    },
    "windowSize": {
      "type": "string",
      "defaultValue": "PT15M",
      "allowedValues": [
        "PT1M",
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H",
        "PT6H",
        "PT12H",
        "PT24H",
        "PT1D"
      ],
      "metadata": {
        "description": "Period of time used to monitor alert activity based on the threshold. Must be between one minute and one day. ISO 8601 duration format."
      }
    },
    "evaluationFrequency": {
      "type": "string",
      "defaultValue": "PT5M",
      "allowedValues": [
        "PT5M",
        "PT15M",
        "PT30M",
        "PT1H"
      ],
      "metadata": {
        "description": "how often the metric alert is evaluated represented in ISO 8601 duration format"
      }
    },
    "currentDateTimeUtcNow": {
      "type": "string",
      "defaultValue": "[utcNow()]",
      "metadata": {
          "description": "The current date and time using the utcNow function. Used for deployment name uniqueness"
      }
    },
    "telemetryOptOut": {
      "type": "string",
      "defaultValue": "No",
      "allowedValues": [
          "Yes",
          "No"
      ],
      "metadata": {
          "description": "The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry."
      }
    }
  },
  "variables": {
    "pidDeploymentName": "[take(concat('pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-', uniqueString(resourceGroup().id, parameters('alertName'), parameters('currentDateTimeUtcNow'))), 64)]"
  },
  "resources": [
    {
      "type": "Microsoft.Insights/scheduledQueryRules",
      "apiVersion": "2021-08-01",
      "name": "[parameters('alertName')]",
      "location": "[resourceGroup().location]",
      "tags": {
        "_deployed_by_amba": true
      },
      "properties": {
        "description": "[parameters('alertDescription')]",
        "severity": "[parameters('alertSeverity')]",
        "enabled": "[parameters('isEnabled')]",
        "scopes": [
          "[parameters('resourceId')]"
        ],
        "evaluationFrequency": "[parameters('evaluationFrequency')]",
        "windowSize": "[parameters('windowSize')]",
        "criteria": {
          "allOf": [
            {
              "query": "[parameters('query')]",
              "metricMeasureColumn": "[parameters('metricMeasureColumn')]",
              "resourceIdColumn": "[parameters('resourceIdColumn')]",
              "dimensions": [{"name": "Computer", "operator": "Include", "values": ["*"]}, {"name": "Disk", "operator": "Include", "values": ["*"]}],
              "operator": "[parameters('operator')]",
              "threshold": "[parameters('threshold')]",
              "timeAggregation": "[parameters('timeAggregation')]",
              "failingPeriods": {
                "numberOfEvaluationPeriods": "[parameters('numberOfEvaluationPeriods')]",
                "minFailingPeriodsToAlert": "[parameters('minFailingPeriodsToAlert')]"
              }
            }
          ]
        },
        "muteActionsDuration": "[parameters('muteActionsDuration')]",
        "autoMitigate": "[parameters('autoMitigate')]",
        "checkWorkspaceAlertsStorageConfigured": "[parameters('checkWorkspaceAlertsStorageConfigured')]"
      }
    },
    {
      "condition": "[equals(parameters('telemetryOptOut'), 'No')]",
      "apiVersion": "2023-07-01",
      "name": "[variables('pidDeploymentName')]",
      "type": "Microsoft.Resources/deployments",
      "properties": {
          "mode": "Incremental",
          "template": {
              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
              "contentVersion": "1.0.0.0",
              "resources": []
          }
      }
    }
  ]
}
@description('Name of the alert')
@minLength(1)
param alertName string

@description('Description of alert')
param alertDescription string = 'Log Alert for Hybrid Machine Heartbeat'

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

@description('Specifies whether to check linked storage and fail creation if the storage was not found')
param checkWorkspaceAlertsStorageConfigured bool = false

@description('Full Resource ID of the resource emitting the metric that will be used for the comparison. For example /subscriptions/00000000-0000-0000-0000-0000-00000000/resourceGroups/ResourceGroupName/providers/Microsoft.compute/virtualMachines/VM_xyz')
@minLength(1)
param resourceId string

@description('Mute actions for the chosen period of time (in ISO 8601 duration format) after the alert is fired.')
@allowed([
  'PT1M'
  'PT5M'
  'PT15M'
  'PT30M'
  'PT1H'
  'PT6H'
  'PT12H'
  'PT24H'
])
param muteActionsDuration string

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

@description('Specifies whether the alert will automatically resolve')
param autoMitigate bool = true

@description('Name of the metric used in the comparison to activate the alert.')
@minLength(1)
param query string = 'Heartbeat | where _ResourceId has "Microsoft.HybridCompute/machines" | summarize TimeGenerated=max(TimeGenerated) by Computer, _ResourceId | extend Duration = datetime_diff("minute",now(),TimeGenerated) | summarize AggregatedValue = min(Duration) by Computer, bin(TimeGenerated,5m), _ResourceId'

@description('Name of the measure column used in the alert evaluation.')
param metricMeasureColumn string = 'AggregatedValue'

@description('Name of the resource ID column used in the alert targeting the alerts.')
param resourceIdColumn string = '_ResourceId'

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

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

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

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

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

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

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

@description('"The current date and time using the utcNow function. Used for deployment name uniqueness')
param currentDateTimeUtcNow string = utcNow()

@description('The customer usage identifier used for telemetry purposes. The default value of False enables telemetry. The value of True disables telemetry.')
@allowed([
  'Yes'
  'No'
])
param telemetryOptOut string = 'No'

resource alert 'Microsoft.Insights/scheduledQueryRules@2021-08-01' = {
  name: alertName
  location: resourceGroup().location
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    description: alertDescription
    severity: alertSeverity
    enabled: isEnabled
    scopes: [
      resourceId
    ]
    evaluationFrequency: evaluationFrequency
    windowSize: windowSize
    criteria: {
      allOf: [
        {
          query: query
          metricMeasureColumn: metricMeasureColumn
          resourceIdColumn: resourceIdColumn
          dimensions: [
            {
              name: 'Computer'
              operator: 'Include'
              values: ['*']
            }
            {
              name: 'Disk'
              operator: 'Include'
              values: ['*']
            }]
          operator: operator
          threshold: threshold
          timeAggregation: timeAggregation
          failingPeriods: {
            numberOfEvaluationPeriods: numberOfEvaluationPeriods
            minFailingPeriodsToAlert: minFailingPeriodsToAlert
          }
        }
      ]
    }
    muteActionsDuration: muteActionsDuration
    autoMitigate: autoMitigate
    checkWorkspaceAlertsStorageConfigured: checkWorkspaceAlertsStorageConfigured
  }
}

var ambaTelemetryPidName = 'pid-8bb7cf8a-bcf7-4264-abcb-703ace2fc84d-${uniqueString(resourceGroup().id, alertName, currentDateTimeUtcNow)}'
resource ambaTelemetryPid 'Microsoft.Resources/deployments@2023-07-01' =  if (telemetryOptOut == 'No') {
  name: ambaTelemetryPidName
  tags: {
    _deployed_by_amba: 'true'
  }
  properties: {
    mode: 'Incremental'
    template: {
      '$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#'
      contentVersion: '1.0.0.0'
      resources: []
    }
  }
}
{
    "mode": "All",
    "parameters": {
      "alertResourceGroupName": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Name",
          "description": "Resource group the alert is placed in"
        },
        "defaultValue": "rg-amba-monitoring-001"
      },
      "alertResourceGroupTags": {
        "type": "Object",
        "metadata": {
          "displayName": "Resource Group Tags",
          "description": "Tags on the Resource group the alert is placed in"
        },
        "defaultValue": {
          "Project": "amba-monitoring"
        }
      },
      "alertResourceGroupLocation": {
        "type": "String",
        "metadata": {
          "displayName": "Resource Group Location",
          "description": "Location of the Resource group the alert is placed in"
        },
        "defaultValue": "centralus"
      },
      "UAMIResourceId": {
        "type": "string",
        "defaultValue": "",
        "metadata": {
          "description": "The resource Id of the user assigned managed identity.",
          "displayName": "User Assigned managed Identity resource Id."
        }
      },
      "severity": {
        "type": "String",
        "metadata": {
          "displayName": "Severity",
          "description": "Severity of the Alert"
        },
        "allowedValues": [
          "0",
          "1",
          "2",
          "3",
          "4"
        ],
        "defaultValue": "1"
      },
      "operator": {
        "type": "String",
        "metadata": {
          "displayName": "Operator"
        },
        "allowedValues": [
          "GreaterThan"
        ],
        "defaultValue": "GreaterThan"
      },
      "timeAggregation": {
        "type": "String",
        "metadata": {
          "displayName": "TimeAggregation"
        },
        "allowedValues": [
          "Count"
        ],
        "defaultValue": "Count"
      },
      "windowSize": {
        "type": "String",
        "metadata": {
          "displayName": "Window Size",
          "description": "Window size for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H",
          "PT6H",
          "PT12H",
          "PT24H"
        ],
        "defaultValue": "PT6H"
      },
      "evaluationFrequency": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Frequency",
          "description": "Evaluation frequency for the alert"
        },
        "allowedValues": [
          "PT5M",
          "PT15M",
          "PT30M",
          "PT1H"
        ],
        "defaultValue": "PT5M"
      },
      "autoMitigate": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Mitigate",
          "description": "Auto Mitigate for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolve": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "autoResolveTime": {
        "type": "String",
        "metadata": {
          "displayName": "Auto Resolve",
          "description": "Auto Resolve time for the alert in ISO 8601 format"
        },
        "defaultValue": "true"
      },
      "enabled": {
        "type": "String",
        "metadata": {
          "displayName": "Alert State",
          "description": "Alert state for the alert"
        },
        "allowedValues": [
          "true",
          "false"
        ],
        "defaultValue": "true"
      },
      "threshold": {
        "type": "String",
        "metadata": {
          "displayName": "Threshold",
          "description": "Threshold for the alert"
        },
        "defaultValue": "10"
      },
      "failingPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Failing Periods",
          "description": "Number of failing periods before alert is fired"
        },
        "defaultValue": "1"
      },
      "evaluationPeriods": {
        "type": "String",
        "metadata": {
          "displayName": "Evaluation Periods",
          "description": "The number of aggregated lookback points."
        },
        "defaultValue": "1"
      },
      "computersToInclude": {
        "type": "array",
        "metadata": {
          "displayName": "Computers to be included to be monitored",
          "description": "Array of Computer to be monitored"
        },
        "defaultValue": [
          "*"
        ]
      },
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Effect of the policy"
        },
        "allowedValues": [
          "deployIfNotExists",
          "disabled"
        ],
        "defaultValue": "deployIfNotExists"
      },
      "MonitorDisableTagName": {
        "type": "String",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag name",
          "description": "Tag name to disable monitoring. Set to true if monitoring should be disabled"
        },
        "defaultValue": "MonitorDisable"
      },
      "MonitorDisableTagValues": {
        "type": "Array",
        "metadata": {
          "displayName": "ALZ Monitoring disabled tag values(s)",
          "description": "Tag value(s) used to disable monitoring at the resource level. Set to true if monitoring should be disabled."
        },
        "defaultValue": [
          "true",
          "Test",
          "Dev",
          "Sandbox"
        ]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.HybridCompute/machines"
          },
          {
            "field": "[concat('tags[', parameters('MonitorDisableTagName'), ']')]",
            "notIn": "[parameters('MonitorDisableTagValues')]"
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]",
        "details": {
          "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
          ],
          "type": "Microsoft.Insights/scheduledQueryRules",
          "existenceScope": "resourceGroup",
          "resourceGroupName": "[parameters('alertResourceGroupName')]",
          "deploymentScope": "subscription",
          "existenceCondition": {
            "allOf": [
              {
                "field": "Microsoft.Insights/scheduledQueryRules/displayName",
                "equals": "[concat(subscription().displayName, '-HybridVMHeartBeatAlert')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/scopes[*]",
                "equals": "[subscription().id]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/enabled",
                "equals": "[parameters('enabled')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/evaluationFrequency",
                "equals": "[parameters('evaluationFrequency')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/windowSize",
                "equals": "[parameters('windowSize')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/severity",
                "equals": "[parameters('severity')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/autoMitigate",
                "equals": "[parameters('autoMitigate')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].operator",
                "equals": "[parameters('operator')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].timeAggregation",
                "equals": "[parameters('timeAggregation')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.numberOfEvaluationPeriods",
                "equals": "[parameters('evaluationPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].failingPeriods.minFailingPeriodsToAlert",
                "equals": "[parameters('failingPeriods')]"
              },
              {
                "field": "Microsoft.Insights/scheduledQueryRules/criteria.allOf[*].query",
                "equals": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-Heartbeat-threshold-Override_\"); Heartbeat | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | summarize TimeGenerated=max(TimeGenerated) by Computer, _ResourceId | extend Duration = datetime_diff(\"minute\",now(),TimeGenerated) | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-Heartbeat-threshold-Override_\", tostring(tags.[\"_amba-Heartbeat-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where Duration > appliedThreshold | project TimeGenerated, Computer, _ResourceId, Duration', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]"
              },
              {
                "field": "identity.userAssignedIdentities",
                "containsKey": "[parameters('UAMIResourceId')]"
              }
            ]
          },
          "deployment": {
            "location": "northeurope",
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {
                  "alertResourceGroupName": {
                    "type": "string"
                  },
                  "alertResourceGroupTags": {
                    "type": "object"
                  },
                  "alertResourceGroupLocation": {
                    "type": "string"
                  },
                  "UAMIResourceId": {
                    "type": "string"
                  },
                  "severity": {
                    "type": "String"
                  },
                  "windowSize": {
                    "type": "String"
                  },
                  "evaluationFrequency": {
                    "type": "String"
                  },
                  "autoMitigate": {
                    "type": "String"
                  },
                  "autoResolve": {
                    "type": "String"
                  },
                  "autoResolveTime": {
                    "type": "String"
                  },
                  "enabled": {
                    "type": "String"
                  },
                  "threshold": {
                    "type": "String"
                  },
                  "operator": {
                    "type": "String"
                  },
                  "timeAggregation": {
                    "type": "String"
                  },
                  "failingPeriods": {
                    "type": "String"
                  },
                  "evaluationPeriods": {
                    "type": "String"
                  },
                  "computersToInclude": {
                    "type": "array"
                  },
                  "MonitorDisableTagName": {
                    "type": "String"
                  },
                  "MonitorDisableTagValues": {
                    "type": "Array"
                  }
                },
                "variables": {},
                "resources": [
                  {
                    "type": "Microsoft.Resources/resourceGroups",
                    "apiVersion": "2021-04-01",
                    "name": "[parameters('alertResourceGroupName')]",
                    "location": "[parameters('alertResourceGroupLocation')]",
                    "tags": "[parameters('alertResourceGroupTags')]"
                  },
                  {
                    "type": "Microsoft.Resources/deployments",
                    "apiVersion": "2019-10-01",
                    "name": "HybridVMHeartBeatAlert",
                    "resourceGroup": "[parameters('alertResourceGroupName')]",
                    "dependsOn": [
                      "[concat('Microsoft.Resources/resourceGroups/', parameters('alertResourceGroupName'))]"
                    ],
                    "properties": {
                      "mode": "Incremental",
                      "template": {
                        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                        "contentVersion": "1.0.0.0",
                        "parameters": {
                          "enabled": {
                            "type": "string"
                          },
                          "alertResourceGroupName": {
                            "type": "string"
                          },
                          "alertResourceGroupLocation": {
                            "type": "string"
                          },
                          "UAMIResourceId": {
                            "type": "string"
                          }
                        },
                        "variables": {},
                        "resources": [
                          {
                            "type": "Microsoft.Insights/scheduledQueryRules",
                            "apiVersion": "2022-08-01-preview",
                            "name": "[concat(subscription().displayName, '-HybridVMHeartBeatAlert')]",
                            "location": "[parameters('alertResourceGroupLocation')]",
                            "identity": {
                              "type": "UserAssigned",
                              "userAssignedIdentities": {
                                "[parameters('UAMIResourceId')]": {}
                              }
                            },
                            "tags": {
                              "_deployed_by_amba": true
                            },
                            "properties": {
                              "displayName": "[concat(subscription().displayName, '-HybridVMHeartBeatAlert')]",
                              "description": "Log Alert for Virtual Machine Heartbeat",
                              "severity": "[parameters('severity')]",
                              "enabled": "[parameters('enabled')]",
                              "scopes": [
                                "[subscription().Id]"
                              ],
                              "targetResourceTypes": [
                                "Microsoft.HybridCompute/machines"
                              ],
                              "evaluationFrequency": "[parameters('evaluationFrequency')]",
                              "windowSize": "[parameters('windowSize')]",
                              "criteria": {
                                "allOf": [
                                  {
                                    "query": "[format('let policyThresholdString = \"{2}\"; let excludedResources = (arg(\"\").resources | where type =~ \"Microsoft.HybridCompute/machines\" | project _ResourceId = id, tags | where parse_json(tostring(tags.[\"{0}\"])) in~ (\"{1}\")); let overridenResource = (arg(\"\").resources | where type == \"microsoft.hybridcompute/machines\" | project _ResourceId = tolower(id), tags | where tags contains \"_amba-Heartbeat-threshold-Override_\"); Heartbeat | where _ResourceId has \"Microsoft.HybridCompute/machines\" | where _ResourceId !in~ (excludedResources) | summarize TimeGenerated=max(TimeGenerated) by Computer, _ResourceId | extend Duration = datetime_diff(\"minute\",now(),TimeGenerated) | join hint.remote=left kind=leftouter overridenResource on _ResourceId | project-away _ResourceId1 | extend appliedThresholdString = iif(tags contains \"_amba-Heartbeat-threshold-Override_\", tostring(tags.[\"_amba-Heartbeat-threshold-Override_\"]), policyThresholdString) | extend appliedThreshold = toint(appliedThresholdString) | where Duration > appliedThreshold | project TimeGenerated, Computer, _ResourceId, Duration', parameters('MonitorDisableTagName'), join(parameters('MonitorDisableTagValues'), '\",\"'), parameters('threshold'))]",
                                    "threshold": 0,
                                    "operator": "[parameters('operator')]",
                                    "resourceIdColumn": "_ResourceId",
                                    "timeAggregation": "[parameters('timeAggregation')]",
                                    "dimensions": [
                                      {
                                        "name": "Computer",
                                        "operator": "Include",
                                        "values": "[parameters('computersToInclude')]"
                                      }
                                    ],
                                    "failingPeriods": {
                                      "numberOfEvaluationPeriods": "[parameters('evaluationPeriods')]",
                                      "minFailingPeriodsToAlert": "[parameters('failingPeriods')]"
                                    }
                                  }
                                ]
                              },
                              "autoMitigate": "[parameters('autoMitigate')]",
                              "ruleResolveConfiguration": {
                                "autoResolved": "[parameters('autoResolve')]",
                                "timeToResolve": "[parameters('autoResolveTime')]"
                              },
                              "parameters": {
                                "alertResourceGroupName": {
                                  "value": "[parameters('alertResourceGroupName')]"
                                },
                                "alertResourceGroupLocation": {
                                  "value": "[parameters('alertResourceGroupLocation')]"
                                },
                                "UAMIResourceId": {
                                  "value": "[parameters('UAMIResourceId')]"
                                },
                                "severity": {
                                  "value": "[parameters('severity')]"
                                },
                                "windowSize": {
                                  "value": "[parameters('windowSize')]"