Search code examples
azurepowershellalertazure-automationazure-monitoring

Disable/Enable Azure monitor alert rules by azure automation powershell


I have a azure monitoring alert rule where it will check the heartbeat of my virtual machine for every 5 minutes. But, the virtual machine itself will go offline everyday at 11 PM and will be started again on 9 AM on next day.

so I'm trying to use azure automation to disable/enable my alert rule at the same time. this is the code I've tried to use:

Write-Output "start job"
$vmResourceGroupName = <<resource_group>>
$vmName = <<vm_name>>

try
{
    # Connection
    Write-Output "connect to the VM"
    $Conn = Get-AutomationConnection -Name AzureRunAsConnection
    $rcConn = Connect-AzAccount -ServicePrincipal -TenantId $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint

    # Stop the VM
    Write-Output "Stop the VM"
    stop-AzVM -ResourceGroupName $vmResourceGroupName -Name $vmName -Force
    #first method that I use to disable my alert rules
    Get-AzAlertRule -ResourceGroupName $vmResourceGroupName -TargetResourceId <<my_resource_id>> -DisableRule
    #second method that I use to disable my alert rules
    Disable-AzureRmActivityLogAlert -Name <<my_alert_name>> -ResourceGroupName <<my_resource_group>>
}
catch
{
    if($_.Exception.Message)
   {
        Write-Error -Message "$($_.Exception.Message)" -ErrorAction Continue
    }
    else
    {
        Write-Error -Message "$($_.Exception)" -ErrorAction Continue
    }
    throw "$($_.Exception)"
}
finally
{
    Write-Output "end job"
}

both of the method which I use returning an error that said my alert rules are not found.


Solution

  • answers from Joy and Khrisna helped me solve this problem. there's one thing on my end, because my Log Analytics Workspace was made last year, it didn't support Get-AzScheduledQuery API. to solve this problem you can either: 1. migrating your workspace to new workspace 2. update your workspace settings so it support Get-AzScheduledQuery. you can follow this tutorial to update the settings :

    Tutorial

    hope it helps!