Azure Azure Monitor Azure PowerShell

Create an Azure Monitor action group with Azure PowerShell

[November 26, 2019 – Original post]


Azure Monitor, Microsoft’s built-in monitoring service, allows you to monitor and gain more visibility into the state of your resources from a single place. In this way this service can help you to quickly find and fix problems.

To notify users that an alert has been triggered, Azure Monitor and also other services like Azure Service Health and Azure Advisor, use action groups. Action groups allow an owner of an Azure subscription or an Azure Administrator with the proper role-based access control (RBAC) permissions to group a collection of actions to take when an alert is triggered. They can create an action group with functions such as sending an email, SMS, Logic or Function App, as well as calling a webhook and re-use it across multiple alerts. Various alerts may use the same action group or different action groups depending on the user’s requirements.

If you’re interested, you can always find more information about an action group on this Microsoft Docs page


Action groups can be created through the Azure portal, but to automate the process you can also use Azure PowerShell. In the below script a new action group is created, which will notify the added people (email address or addresses) by email whenever a specific event is triggered. For example, you can then alert on metrics and logs, like Activity Log events, log search queries, or even the health of the underlying Azure platform (service issues). For the moment, you may have up to 1000 email actions in an action group. Also ensure that your email filtering is configured appropriately.

The Azure PowerShell script I wrote to automate the creation of this action group, will do all of the following:

  • Check if the PowerShell window is running as Administrator (when not running from Cloud Shell), otherwise the Azure PowerShell script will be exited.
  • Create a new action group Email receiver in memory.
  • Set and add tags with the specified key/value pairs into the proper data type (dictionary object instead of a hash table).
  • Create a new or update the existing action group.


To use the script copy and save it as Create-Azure-Monitor-Action-Group.ps1 or download it from GitHub.  Then before using the script, adjust all variables to your use (you can find an adjusted example in a screenshot below) and then run the customized script with Administrator privileges from Windows TerminalVisual Studio Code, or Windows PowerShell. Or you can simply run it from Cloud Shell.


Prerequisites

  • An Azure Subscription.
  • An Azure Administrator account with the necessary RBAC roles.


Azure PowerShell script

If you are not running the script from Cloud Shell, don’t forget to sign in with the Connect-AzAccount cmdlet to connect your Azure account. And if you are using multiple Azure subscriptions, select the proper subscription with the Get-AzSubscription cmdlet before running the script.


<#
.SYNOPSIS

A script used to create an Azure Monitor action group.

.DESCRIPTION

A script used to used to create an Azure Monitor action group with the Email action type.
A check is performed to see if the PowerShell window is running as Administrator (which is a requirement), otherwise the Azure PowerShell script will be exited.
And specified tags are set with the specified key/value pairs into the proper data type (dictionary object instead of a hash table) and added to the action group resource.

.NOTES

Filename:       Create-Azure-Monitor-Action-Group.ps1
Created:        26/11/2019
Last modified:  12/01/2022
Author:         Wim Matthyssen
PowerShell:     Azure Cloud Shell or Azure PowerShell
Version:        Install latest Azure PowerShell modules
Action:         Change variables were needed to fit your needs. 
Disclaimer:     This script is provided "As Is" with no warranties.

.EXAMPLE

.\Create-Azure-Monitor-Action-Group.ps1

.LINK

https://wmatthyssen.com/2022/01/12/create-an-azure-monitor-action-group-with-azure-powershell/
#>

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Variables

$rgActionGroup = #<your Action Group rg here> The name of the resource group in which the action group is saved. Example: "rg-hub-myh-management"
$actionGroupName = #<your Action Group name here> The name of the Action Group. Example: "ag-hub-myh-admin"
$actionGroupShortName = #<your Action Group display name here> The name used when notifications are sent using this group, max 12 characters long. Example: "ag-admin"
$emailReceiverName = "emailreceiver"
$emailAddress = #<your email address here> The email address you want to use. Example: "test@demo.com"

$tagSpokeKey = #<your environment tag key here> The environment tag key you want to use. Example:"env"
$tagSpokeValue = #<your environment tag value here> The environment tag value you want to use. Example:"hub"
$tagCostCenterKey  = #<your costCenter tag key here> The costCenter tag key you want to use. Example:"costCenter"
$tagCostCenterValue = #<your costCenter tag value here> The costCenter tag value you want to use. Example: "it"
$tagBusinessCriticalityKey  = #<your businessCriticality tag key here> The businessCriticality tag key you want to use. Example:"costCenter"
$tagBusinessCriticalityValue = #<your businessCriticality tag value here> The businessCriticality tag value you want to use. Example: "critical"
$tagPurposeKey  = #<your purpose tag key here> The purpose tag key you want to use. Example:"purpose"
$tagPurposeValue = #<your purpose tag value here> The purpose tag value you want to use. Example:"monitor"

$global:currenttime= Set-PSBreakpoint -Variable currenttime -Mode Read -Action {$global:currenttime= Get-Date -UFormat "%A %m/%d/%Y %R"}
$foregroundColor1 = "Red"
$foregroundColor2 = "Yellow"
$writeEmptyLine = "`n"
$writeSeperatorSpaces = " - "

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Check if PowerShell runs as Administrator (when not running from Cloud Shell), otherwise exit the script

if ($PSVersionTable.Platform -eq "Unix") {
    Write-Host ($writeEmptyLine + "# Running in Cloud Shell" + $writeSeperatorSpaces + $currentTime)`
    -foregroundcolor $foregroundColor1 $writeEmptyLine
    
    ## Start script execution    
    Write-Host ($writeEmptyLine + "# Script started. Without any errors, it will need around 1 minute to complete" + $writeSeperatorSpaces + $currentTime)`
    -foregroundcolor $foregroundColor1 $writeEmptyLine 
} else {
    $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
    $isAdministrator = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

        ## Check if running as Administrator, otherwise exit the script
        if ($isAdministrator -eq $false) {
        Write-Host ($writeEmptyLine + "# Please run PowerShell as Administrator" + $writeSeperatorSpaces + $currentTime)`
        -foregroundcolor $foregroundColor1 $writeEmptyLine
        Start-Sleep -s 3
        exit
        }
        else {

        ## If running as Administrator, start script execution    
        Write-Host ($writeEmptyLine + "# Script started. Without any errors, it will need around 1 minutes to complete" + $writeSeperatorSpaces + $currentTime)`
        -foregroundcolor $foregroundColor1 $writeEmptyLine 
        }
}

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Suppress breaking change warning messages

Set-Item Env:\SuppressAzurePowerShellBreakingChangeWarnings "true"

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Create a new action group Email receiver in memory 

$emailReceiver = New-AzActionGroupReceiver -Name $emailReceiverName -EmailReceiver -EmailAddress $emailAddress

Write-Host ($writeEmptyLine + "# Action Group Receiver $emailReceiverName saved in memory" + $writeSeperatorSpaces + $currentTime)`
-foregroundcolor $foregroundColor2 $writeEmptyLine 

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Set and add tags with the specified key/value pairs into the proper data type (dictionary object instead of a hash table)

$tag = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$tag.Add($tagSpokeKey,$tagSpokeValue)
$tag.Add($tagCostCenterKey,$tagCostCenterValue)
$tag.Add($tagBusinessCriticalityKey,$tagBusinessCriticalityValue)
$tag.Add($tagPurposeKey,$tagPurposeValue)

Write-Host ($writeEmptyLine + "# Tags set into the proper data type" + $writeSeperatorSpaces + $currentTime)`
-foregroundcolor $foregroundColor2 $writeEmptyLine 

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Create a new or update the existing action group

Set-AzActionGroup -Name $actionGroupName -ResourceGroup $rgActionGroup -ShortName $actionGroupShortName -Receiver $emailReceiver -Tag $tag

Write-Host ($writeEmptyLine + "# Action Group $actionGroupName created" + $writeSeperatorSpaces + $currentTime)`
-foregroundcolor $foregroundColor2 $writeEmptyLine 

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Write script completed

Write-Host ($writeEmptyLine + "# Script completed" + $writeSeperatorSpaces + $currentTime)`
-foregroundcolor $foregroundColor1 $writeEmptyLine 

## ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


You can check all existing action groups in your subscription, by running the below cmdlet. In my example the previously created action group ag-hub-myh-admin is shown.

## View available action groups

Get-AzActionGroup | Select-Object Name


You can also add, validate or manage action groups through the Azure portal by opening Monitor, selecting Alerts and selecting Action groups


I hope this Azure PowerShell script comes in handy whenever you need to create a new action group in your own Azure environment.

If you have any questions or recommendations about it, feel free to contact me through my Twitter handle (@wmatthyssen) or to just leave a comment.


3 comments on “Create an Azure Monitor action group with Azure PowerShell

  1. Pingback: Azure Service Health: How to create a pinned health world map and a service health alert – Wim Matthyssen

  2. Pingback: Azure Advent Calendar 2019 – Azure Service Health – Wim Matthyssen

  3. Pingback: Azure Service Health: Remain informed about Azure service issues, planned maintenance, health and security advisories - MC2MC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: