I need to create multiple azure monitor alarms. I'm trying to do this following this website: https://www.azureblue.io/how-to-create-an-alert-rule-using-powershell-and-azure-cli/
This solution works for me if I have action group and target resources in the same subscription but generally I don't. I have one actiongroup and hundreds targets in almost 100 subscriptions.
I have:
#jump to subscription with actiongroup
$context = Get-AzSubscription -SubscriptionId xxx
Set-AzContext $context
$actionGroup = Get-AzActionGroup -name "xxx" -ResourceGroupName "xxx"
$actionGroupId = New-AzActionGroup -ActionGroupId $actionGroup.Id
#jump to subscription with target without this I can't ask for target.id
$context = Get-AzSubscription -SubscriptionId xx
Set-AzContext $context
# Creates a local criteria object that can be used to create a new metric alert
$condition = New-AzMetricAlertRuleV2Criteria `
-MetricName "Data space used percent (Platform)" `
-TimeAggregation Maximum `
-Operator GreaterThan `
-Threshold 0.8
$windowSize = New-TimeSpan -Minutes 30
$frequency = New-TimeSpan -Minutes 5
$targetResourceId = (Get-AzResource -Name xxx).Id
#I was thinking that this jump to subscription will solve my issue but doesn't
$context = Get-AzSubscription -SubscriptionId cf653672-c304-49a2-b01b-171f6236bad6
Set-AzContext $context
# Adds or updates a V2 (non-classic) metric-based alert rule.
Add-AzMetricAlertRuleV2 `
-Name "test" `
-ResourceGroupName "xxx" `
-WindowSize $windowSize `
-Frequency $frequency `
-TargetResourceId $targetResourceId `
-Condition $condition `
-ActionGroup $actionGroupId `
-Severity 3
I got this error:
Add-AzMetricAlertRuleV2 : Exception type: ErrorResponseException, Message: Null/Empty, Code: Null, Status code:NotFound, Reason phrase: Not Found
At line:26 char:1
+ Add-AzMetricAlertRuleV2 `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Add-AzMetricAlertRuleV2], PSInvalidOperationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Insights.Alerts.AddAzureRmMetricAlertRuleV2Command
From GUI there is no a problem to chose actiongroup from different subscription but you can't chose targets from multiple subscription.
If I will find solution for this one example I will try to read all my resources and run the code in a loop.