0

I have the following code

# Variables
$task3storageAccountName = "testRG" 
$actionGroupName = "Storage Admins"
$actionGroupShortName = "SA Admins"
$notificationName = "Email storage admins"
$emailAddress = "[email protected]"  # Replace with your actual email

# Get the Storage Account and its resource ID (this will be used in the alert rule)
$storageAccount = Get-AzStorageAccount -Name $task3storageAccountName -ResourceGroupName $resourceGroupName
Write-Host "For task 3 the storage account '$task3storageAccountName' will be used.`nResource ID: $($storageAccount.Id)"
$storageAccount | Format-List

# Create receiver object
$email1 = New-AzActionGroupEmailReceiverObject -EmailAddress $emailAddress -Name "Name"
$sms1 = New-AzActionGroupSmsReceiverObject -CountryCode '61' -Name user2 -PhoneNumber '00000000'

# Create action group
# https://learn.microsoft.com/en-us/powershell/module/az.monitor/new-azactiongroup?view=azps-14.0.0&viewFallbackFrom=azps-13.3.0
$actionGroup=New-AzActionGroup `
    -Name $actionGroupName `
    -ResourceGroupName $resourceGroupName `
    -Location "global" `
    -GroupShortName $actionGroupShortName `
    -EmailReceiver $email1 `
    -SmsReceiver $sms1


$alertRuleName = "Storage account key generation failed"
$location = "global"

$categoryCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject `
    -Field "category" `
    -Equal "Administrative"

# Operation name filter
$operationCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject `
    -Field "operationName" `
    -Equal "Microsoft.Storage/storageAccounts/regenerateKey/action"

# Status filter
$statusCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject `
    -Field "status" `
    -Equal "Failed"

# Create the alert
# There's a bug in the Az module that prevents the use of the -Action parameter.
$alert=New-AzActivityLogAlert `
    -Name $alertRuleName `
    -ResourceGroupName $resourceGroupName `
    -Action $actionGroup `
    -Condition @($categoryCondition, $operationCondition, $statusCondition) `
    -Location $location `
    -Scope $storageAccount.Id `
    -Enabled:$true

The issue is with the cmdlet New-AzActivityLogAlert and the parameter Action. There seems to be a bug that prevents the Activity Log Alert to have the designated Action Group.

A temporary fix for this issue is to run az monitor activity-log alert action-group add -n test2 -g $resourceGroupName --action $actionGroup.Id But this requires login both via CLI and PowerShell.

1
  • I hope this helps to resolve your issue. Please feel free to ask any questions if the solution provided isn't helpful. Commented May 26 at 8:49

2 Answers 2

0

The issue you encountered is due to passing an incorrect Action Group resource object to the -Action parameter.

The -Action parameter expects a wrapped object, not the raw output from New-AzActionGroup.

To resolve the issue, create a wrapped object using the following cmdlet.

$actionGroupObj = New-AzActivityLogAlertActionGroupObject -Id $actionGroup.Id -WebhookProperty @{}

enter image description here

Then use this object in your alert rule.

New-AzActivityLogAlert -Action $actionGroupObj

Here is the updated code to create an alert and action group and link to the alert.

$task3storageAccountName = "venkatstoragedemo" 
$actionGroupName = "StorageEmailGroup"
$actionGroupShortName = "SEGrp"
$emailAddress = "[email protected]" 
$resourceGroupName = "venkat-RG"
$alertRuleName = "Test-Storage account key generation failed"
$location = "global"

$storageAccount = Get-AzStorageAccount -Name $task3storageAccountName -ResourceGroupName $resourceGroupName
Write-Host "For task 3 the storage account '$task3storageAccountName' will be used.`nResource ID: $($storageAccount.Id)"

$emailReceiver = New-AzActionGroupEmailReceiverObject -EmailAddress $emailAddress -Name "EmailReceiver"

$actionGroup = New-AzActionGroup -Name $actionGroupName -ResourceGroupName $resourceGroupName -Location $location -GroupShortName $actionGroupShortName -EmailReceiver $emailReceiver

$actionGroupObj = New-AzActivityLogAlertActionGroupObject -Id $actionGroup.Id -WebhookProperty @{}

$categoryCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject -Field "category" -Equal "Administrative"
$operationCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject -Field "operationName" -Equal "Microsoft.Storage/storageAccounts/regenerateKey/action"
$statusCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject -Field "status" -Equal "Failed"

$alert = New-AzActivityLogAlert -Name $alertRuleName -ResourceGroupName $resourceGroupName -Action $actionGroupObj -Condition @($categoryCondition, $operationCondition, $statusCondition) -Location $location -Scope $storageAccount.Id -Enabled $true

Output:

enter image description here

enter image description here

Reference: Create activity log alert

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, Venkat. Indeed, using New-AzActivityLogAlertActionGroupObjectsolved the issue. I can see that when the alert rule is created now it includes the Action Group, which before didn't happen
Venkat, something that is also required for new accounts is this: Register-AzResourceProvider -ProviderNamespace Microsoft.Insights
@Álvaro Good to accept any of the solution if it has solved the problem. This is for the benefit of the SO Community, refer SO Link
0

Based on Venkat code this would be the final code:

```

Write-Host "Task 3: Configure monitoring for a storage account" -ForegroundColor Green
Write-Host "---------------------------------------------------------------------" -ForegroundColor Green
# Variables
$task3storageAccountName = "sab$rgId" 
$actionGroupName = "Storage Admins"
$actionGroupShortName = "SA Admins"
$notificationName = "Email storage admins"
$emailAddress = "[email protected]"  # Replace with your actual email


# This is required to create action groups
Register-AzResourceProvider -ProviderNamespace Microsoft.Insights

$maxAttempts = 20
$delaySeconds = 15
$attempt = 0
$registered = $false

while ($attempt -lt $maxAttempts -and -not $registered) {
    $attempt++
    Write-Host "Attempt $attempt of ${maxAttempts}: Checking registration state..." # I used {} to avoid the variable conflicting with the :

    $insightsProvider = Get-AzResourceProvider -ProviderNamespace "microsoft.insights" |
    Where-Object {
        $_.ResourceTypes.ResourceTypeName -eq "actiongroups"
    } 

    if ($insightsProvider.RegistrationState -eq "Registered") {
        Write-Host "`n✅ Microsoft.Insights provider  for Action Groups is registered."
        $registered = $true
    } else {
        Write-Host "❌ Not yet registered. Waiting $delaySeconds seconds..."
        Start-Sleep -Seconds $delaySeconds
    }
}

if (-not $registered) {
    # We can't continue with the task
    throw "`n❌ microsoft.insights provider did not register after $maxAttempts attempts."
}

# Get the Storage Account and its resource ID (this will be used in the alert rule)
$storageAccount = Get-AzStorageAccount -Name $task3storageAccountName -ResourceGroupName $resourceGroupName
Write-Host "For task 3 the storage account '$task3storageAccountName' will be used.`nResource ID: $($storageAccount.Id)"
$storageAccount | Format-List

# Create receiver object
$emailReceiver = New-AzActionGroupEmailReceiverObject -EmailAddress $emailAddress -Name "Name Surnames"
$smsReceiver = New-AzActionGroupSmsReceiverObject -CountryCode '61' -Name user2 -PhoneNumber '400000000'

# Create action group
# https://learn.microsoft.com/en-us/powershell/module/az.monitor/new-azactiongroup?view=azps-14.0.0&viewFallbackFrom=azps-13.3.0
$actionGroup=New-AzActionGroup `
    -Name $actionGroupName `
    -ResourceGroupName $resourceGroupName `
    -Location "global" `
    -GroupShortName $actionGroupShortName `
    -EmailReceiver $emailReceiver `
    -SmsReceiver $smsReceiver

# Throw exception if creation failed. This will avoid the script to continue if the action group was not created successfully.
if (-not $actionGroup) {
    throw "❌ Failed to create Action Group '$actionGroupName'. The returned object is null."
}

# Create a wrapped object that will be used in the alert rule. 
$actionGroupObj = New-AzActivityLogAlertActionGroupObject -Id $actionGroup.Id -WebhookProperty @{}


# Send test notification (this command is optional, but useful to verify that the action group is set up correctly). 
# Be aware that it will take a while to receive the email and SMS. If executed in a chain of commands, it will take a while to execute.
# https://learn.microsoft.com/en-us/powershell/module/az.monitor/test-azactiongroup?view=azps-14.0.0&viewFallbackFrom=azps-13.2.0
Test-AzActionGroup `
    -ResourceGroupName $resourceGroupName `
    -ActionGroupName $actionGroupName `
    -AlertType servicehealth `
    -Receiver $emailReceiver,$smsReceiver


$alertRuleName = "Storage account key generation failed"
$location = "global"


# Required: Category must be specified and exactly one
$categoryCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject `
    -Field "category" `
    -Equal "Administrative"

# Operation name filter
$operationCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject `
    -Field "operationName" `
    -Equal "Microsoft.Storage/storageAccounts/regenerateKey/action"

# Status filter
$statusCondition = New-AzActivityLogAlertAlertRuleAnyOfOrLeafConditionObject `
    -Field "status" `
    -Equal "Failed"

# Create the alert
# Note: the -Action parameter can't receive an action group object directly, it needs to be wrapped in a specific object type.
# https://stackoverflow.com/questions/79634835/bug-with-azure-powershell-command-new-azactivitylogalert/79635400#79635400
$alert=New-AzActivityLogAlert `
    -Name $alertRuleName `
    -ResourceGroupName $resourceGroupName `
    -Action $actionGroupObj `
    -Condition @($categoryCondition, $operationCondition, $statusCondition) `
    -Location $location `
    -Scope $storageAccount.Id `
    -Enabled:$true

```

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.