Zum Inhalt springen

Azure Create LogAnalytics Alert Rule

Azure log analytics workspaces can be queried for entries and if a specified entry is found, an alarm can be fired.

I’ve written a small script to create an alert rule with everything that is needed.

# 2020/04/19
# Guido Jeuken
# this script creates an AzureMonitor alert rule for a Log Analytics workspaces
# if any log entry with the defined query is found, an Email will be sent.

## define Parameter here
$AlertRuleName = "CRM Fehler"
$AlertRuleDescription = "Sends Email if any log entry with the defined query is found"
# the resourcegroup wherte the log analytics workspace resists
$resgroupname = "gj_loganalyse"
# the log analytics workspace name

# EmailReseiver to send Alert to, this may be a Email Address, or -Group
$EmailReceiver="crmfehler@jeuken.de" ##Email or GroupEmail
# the name of the Action Group
$ActionGroupName = "CRM Error"
# the Query to search for in the LogSpace
$LogAnalyticsQuery= "AzureActivity | where TimeGenerated > ago(1h)"
# some parameter are defined later, scheduling and trigger condition "greater then =0"

# check if connected -> Connect if necessary
if($azureConnection -eq $null){
    $azureConnection = Connect-AzAccount 
    Write-Host "you are allready connected as"

# get resouregroup, logspace objects for further actions
$resgroup = Get-AzResourceGroup -Name $resgroupname
$logspace= get-AzOperationalInsightsWorkspace -Name $logspaceName -ResourceGroupName $resgroupname

# define and create the Action Group
$ActionGroupEmailReceiver = New-AzActionGroupReceiver -Name $ActionGroupName -EmailAddress $EmailReceiver
New-AzActionGroup -ActionGroupId $logspace.ResourceId.ToString() + $actionGroupname
Set-AzActionGroup -Name $ActionGroupName -Receiver $ActionGroupEmailReceiver -ResourceGroupName $resgroupname -ShortName $ActionGroupName
$ActionGroup = Get-AzActionGroup -Name $ActionGroupName -ResourceGroupName $resgroupname

# define and create the Action Rule
$AlertQueryRuleSouce = New-AzScheduledQueryRuleSource -Query $LogAnalyticsQuery -DataSourceId $logspace.ResourceId

$AlertQueryRuleSchedule = New-AzScheduledQueryRuleSchedule -FrequencyInMinutes 15 -TimeWindowInMinutes 15

$triggerCondition = New-AzScheduledQueryRuleTriggerCondition -ThresholdOperator "GreaterThan" -Threshold 0 

$aznsActionGroup = New-AzScheduledQueryRuleAznsActionGroup -ActionGroup $ActionGroup.id

$AlertingAction = New-AzScheduledQueryRuleAlertingAction -AznsAction $aznsActionGroup -Severity "4" -Trigger $triggerCondition

New-AzScheduledQueryRule -ResourceGroupName $resgroup.ResourceGroupName -Location $resgroup.location -Action $AlertingAction -Enabled $true -Description $AlertRuleDescription -Schedule $AlertQueryRuleSchedule -Source $AlertQueryRuleSouce -Name $AlertRuleName

Schreibe einen Kommentar