Quick Code – Install AMA and Assign a DCR with PowerShell

Happy Holidays! Here’s a quick post to share some code that will inventory Azure VMs, install the AMA if necessary, and then assign a DCR to the VM.

# Ensure you're logged in to Azure

# Define the Data Collection Rule (DCR) resource ID
$dcrResourceId = "<Your-DCR-Resource-ID>"

# Get all VMs in the subscription
$vms = Get-AzVM

# Use ForEach-Object with -Parallel to process VMs concurrently
$vms | ForEach-Object -Parallel {
    $vm = $_
    $osType = $vm.StorageProfile.OsDisk.OsType
    $extensionName = if ($osType -eq "Windows") { "AzureMonitorWindowsAgent" } else { "AzureMonitorLinuxAgent" }
    $extensionPublisher = "Microsoft.Azure.Monitor"
    $vmResourceId = "/subscriptions/$using:vm.SubscriptionId/resourceGroups/$using:vm.ResourceGroupName/providers/Microsoft.Compute/virtualMachines/$using:vm.Name"

    try {
        # Check if the Azure Monitor Agent extension is installed
        $amaExtension = Get-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -ErrorAction SilentlyContinue

        if (-not $amaExtension) {
            try {
                # Install the Azure Monitor Agent extension
                Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -Publisher $extensionPublisher -ExtensionType $extensionName -TypeHandlerVersion "1.0" -Location $using:vm.Location
                Write-Host "Installed Azure Monitor Agent on $($using:vm.Name)"
            } catch {
                Write-Host "Failed to install Azure Monitor Agent on $($using:vm.Name): $_"
        } else {
            Write-Host "Azure Monitor Agent is already installed on $($using:vm.Name)"
    } catch {
        Write-Host "Error checking Azure Monitor Agent on $($using:vm.Name): $_"

    try {
        # Assign the DCR to the VM
        $settings = @{ "dataCollectionRuleResourceIds" = @($using:dcrResourceId) }
        Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name "AzureMonitorVmExtension" -Publisher $extensionPublisher -ExtensionType $extensionName -Settings $settings -Location $using:vm.Location
        Write-Host "Assigned DCR to $($using:vm.Name)"
    } catch {
        Write-Host "Failed to assign DCR to $($using:vm.Name): $_"
} -ThrottleLimit 5 # Adjust the ThrottleLimit as necessary

Creating Alert Rules in Azure with AZ PowerShell – Some Samples

Let go over a simple one – how to create various types of alert rules in Azure using the AZ PowerShell Module.

Each example targets a different aspect of Azure monitoring, but doesn’t cover them all. Remember to tweak the parameters to match your environment.

Metric Alerts for Performance Monitoring

To keep an eye on Azure service metrics:

$criteria = New-AzMetricAlertRuleV2Criteria -MetricName 'Percentage CPU' -TimeAggregation Average -Operator GreaterThan -Threshold 80

Add-AzMetricAlertRuleV2 -Name 'HighCPUAlert' -ResourceGroupName 'YourResourceGroupName' -WindowSize 00:05:00 -Frequency 00:01:00 -TargetResourceId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/Microsoft.Compute/virtualMachines/yourVMName' -Condition $criteria -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -Severity 3 -Description 'Alert on high CPU usage.'

Log Alerts for Custom Log Queries

For alerts based on log analytics:

$query = "AzureActivity | where OperationName == 'Create or Update Virtual Machine' and ActivityStatus == 'Succeeded'"

Set-AzScheduledQueryRule -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -ActionGroup '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName' -ConditionQuery $query -Description "VM creation alert" -Enabled $true -EvaluationFrequency 'PT5M' -Severity 0 -WindowSize 'PT5M' -Name 'VMCreationAlert'

Activity Log Alerts for Azure Resource Events

To monitor specific Azure service events:

$condition = New-AzActivityLogAlertCondition -Field 'category' -Equal 'Administrative'
$actionGroupId = "/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/actionGroups/yourActionGroupName"

Set-AzActivityLogAlert -Location 'Global' -Name 'AdminActivityAlert' -ResourceGroupName 'YourResourceGroupName' -Scopes "/subscriptions/yourSubscriptionId" -Condition $condition -ActionGroupId $actionGroupId -Description "Alert on administrative activities"

Application Insights Alerts for Application Performance

Track application performance with a simple AppInsights web test

$rule = New-AzApplicationInsightsWebTestAlertRule -Name 'AppPerfAlert' -ResourceGroupName 'YourResourceGroupName' -Location 'East US' -WebTestId '/subscriptions/yourSubscriptionId/resourceGroups/yourResourceGroupName/providers/microsoft.insights/webtests/yourWebTestId' -FailedLocationCount 3 -WindowSize 'PT5M' -Frequency 'PT1M' -Criteria $criteria

Set-AzApplicationInsightsWebTestAlertRule -InputObject $rule