question

sathishravi-9591 avatar image
0 Votes"
sathishravi-9591 asked AnuragSingh-MSFT commented

Replace a action group from existing azure alert and update with another action group using powershell

I'm looking for a powershell command/script which can help me to update all my alert rules with another action group.

Remove existing action group for alert rule and add another action group

Thanks

azure-monitor
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@sathishravi-9591, Apologies for the delayed response. I am looking into it and will update this thread soon.

0 Votes 0 ·

1 Answer

AnuragSingh-MSFT avatar image
0 Votes"
AnuragSingh-MSFT answered AnuragSingh-MSFT commented

Hi @sathishravi-9591,

Welcome to Microsoft Q&A! Thanks for posting the question.

To be able to update the "Action Group" for Alert rules in Azure Monitor, there are multiple ways. The easiest one would be to use the Azure portal itself to manage them. However, if you would like to achieve it using PowerShell, below information should help you. There are 3 main types of Signals on which the alert rules are based: Metric, Log and Activity Log alerts (refer: Overview of alerting and notification monitoring in Azure - Azure Monitor).


1. Metric Alert: There isn't a direct PS cmdlet to update the metric alert rule, but you may use the REST API for Updating the Metric Alert rule to achieve it in PowerShell using Invoke-Webrequest cmdlet as shown below. The script contains reference articles for help, where required. The first section is to supply the parameters which needs to be updated before running the script. (The script is provided "AS IS", without warranty of any kind, express or implied. This is provided as a reference and must be tested before using in production)

 ###################Get All the Parameters####################
 #ref: https://jiasli.github.io/azure-notes/aad/Service-Principal-portal.html
 $ApplicationId = "<>"
 $TenantId = "<>"
 $ClientSecret = "<>"
 $SUBSCRIPTION_ID = "<>"
    
 #Assign this service Principal a "Monitoring Contributor" role at subscription level. 
    
 # Name of New action group (the one that needs to be updated)
 $NEW_ACTION_GROUP_NAME = "<new action group name>"
    
 # Resource Group name, where the New action group is stored, 
 # to avoid conflict wither other action groups of the same name
 $NEW_ACTION_GROUP_RG_NAME = "<new action group's resource ID>"
 ############################################################
    
    
 ###########Login to Azure and Set Subscription Context######
 #login to Azure
 Add-AzAccount
    
 Set-AzContext -Subscription $SUBSCRIPTION_ID
 ############################################################
    
    
 ##################Get Breaer token###########################
 $Auth_Uri = "https://login.microsoftonline.com/"+$TenantId+"/oauth2/token"
 $Auth_Body = @{
 grant_type="client_credentials"
 client_id=$ApplicationId
 client_secret=$ClientSecret
 resource="https://management.core.windows.net"
 }
    
 $Auth_Response = Invoke-WebRequest -Method Post -Uri $auth_uri -Body $Auth_Body | select -ExpandProperty Content | ConvertFrom-Json
 $Bearer_Token = $Auth_Response.access_token
    
 $headers = @{Authorization = "Bearer $Bearer_Token"}
 ############################################################
    
 #get the new action group
 $newActionGroup = Get-AzActionGroup -ResourceGroupName $NEW_ACTION_GROUP_RG_NAME -Name $NEW_ACTION_GROUP_NAME
    
 # Get all the metric rules (non-classic)
 $MetricAlertRules = Get-AzMetricAlertRuleV2
    
 #update the action group for MetricAlertRule
 foreach($ma in $MetricAlertRules)
 {
     $URL = "https://management.azure.com/subscriptions/"+$SUBSCRIPTION_ID+"/resourceGroups/"+$ma.ResourceGroup+"/providers/Microsoft.Insights/metricAlerts/"+ `
         $ma.Name+"?api-version=2018-03-01"
    
     $Body = '{
       "properties": {
         "actions": [
           {
             "actionGroupId": "' + $newActionGroup.Id + '"' + `
           '}
         ]
       }
     }'
    
     $response = Invoke-WebRequest -Method Patch -Uri $URL -Body $Body -Headers $headers -ContentType 'application/json'
 }

2. Log Alert: Like the example above, you may use same script with some modification for Log Alert rule to update the action group. Please note log based alerts rules are also known as Scheduled query rules. The API for update of Log/Scheduled Query alert rules is available here: Scheduled Query Rules - Update

3. Activity Alert: This will have to be done manually as the REST API or PowerShell cmdlet are not yet available.

Please note that this will not work for Smart detection in Application Insights alert rules as of now, and they will have to be updated manually from portal.

Feel free to reach out to me in case you have any questions.


Please 'Accept as answer' and ‘Upvote’ if it helped so that it can help others in the community looking for help on similar topics.

· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@sathishravi-9591, I wanted to check if you had a chance to review my answer above. Please let me know if you have any queries or concerns.

Please 'Accept as answer' if it helped so that it can help others in the community looking for help on similar topics.

0 Votes 0 ·

Hi AnuragSingh,

PowerShell output for Log search has no parameter like "actiongroup.id". Also, below are the response for Get-AzScheduledQueryRule and the output not showing actual action groups under "action".

Could you please confirm the parameter to add actiongroup?

################PowerShell Ouput

CreatedWithApiVersion :
IsLegacyLogAnalyticsRule :
Description : This alert is triggered when keys are about to expire
DisplayName :
AutoMitigate :
Enabled : true
LastUpdatedTime : 3/23/2022 3:54:23 PM
ProvisioningState : Succeeded
Source : Microsoft.Azure.Management.Monitor.Models.Source
Schedule : Microsoft.Azure.Management.Monitor.Models.Schedule
Action : Microsoft.Azure.Management.Monitor.Models.AlertingAction
Id : /subscriptions/xxxxxxxxxxx/resourceGroups/iptiqadata-prod-monitoring/pr
oviders/microsoft.insights/scheduledqueryrules/Keys_and_Certs_Expiry_Notification
Name : Keys_and_Certs_Expiry_Notification
Type : microsoft.insights/scheduledqueryrules
Location : eastus
Tags : {[APMID, IPTIQADATA], [CostCenter, SAGE], [CreatedOnDate, 03/18/2022 13:37:49], [Creator,
Alexandr Gaponenko (external)]...}
Kind :
Etag :



Thanks

0 Votes 0 ·

@sathishravi-9591, Apologies for the delayed response.

Please find my answers below to your follow-up queries.

1. actiongroup.id is obtained using the Get-AzActionGroup commandlet, as available in Line 43 of the script above. This actiongroup id is of the new Action Group which will be added to the alert rule.

2. The output from Get-AzScheduledQueryRule mostly contain model class objects which cannot be directly used to update the action group id. The best way to update them is by using the REST Api as shown in above script from line 46-65. The script above uses the REST API for metric alert (`/providers/Microsoft.Insights/metricAlerts`). To update it for Log based alert, you will have to use the Log based alert Rest API - Scheduled Query Rules - Update


Please Accept as answer and Upvote if it helped so that it can help others in the community looking for help on similar topics.

0 Votes 0 ·