You dont have javascript enabled! Please enable it! Export Microsoft Sentinel Automation Rules With Ease - CHARBEL NEMNOM - MVP | MCT | CCSP | CISM - Cloud & CyberSecurity

Export Microsoft Sentinel Automation Rules With Ease

6 Min. Read

Like all automation, Microsoft Sentinel automation aims to transform repetitive tasks into automated tasks. Automation rules are used to manage automation in Microsoft Sentinel centrally, and they contain triggers, conditions, and actions that dictate how an automation rule will respond.

Exporting Microsoft Sentinel automation rules is useful for backing up, restoring, or importing scenarios to different environments. Additionally, exporting automation rules as code helps automate the creation of these rules through the Microsoft Sentinel Repositories feature.

This article will show you how to export Microsoft Sentinel Automation Rules at scale using PowerShell and REST API.

Export Microsoft Sentinel Automation Rules

Microsoft Sentinel is a cloud-native Security Information Event Management (SIEM) and Security Orchestration Automated Response (SOAR) solution. Microsoft Sentinel delivers intelligent security analytics and threat intelligence across the enterprise, providing a single solution for alert detection, threat visibility, proactive hunting, and threat response.

As mentioned, automation rules can be created to manage automation in Microsoft Sentinel centrally. Automation rules in Microsoft Sentinel have three main aspects: Triggers, Conditions, and Actions.

Create and use Microsoft Sentinel automation rules to manage response
Create and use Microsoft Sentinel automation rules to manage response

Automation rules are sorted in order, which is a critical element since all automation rules will run from the lowest order number (for example, 1) to the highest (for example, 40) and run sequentially.

Microsoft Sentinel automation rules are located under the Configuration menu in the Automation Rules sub-menu in the Azure portal, as shown in the figure below. For Microsoft Sentinel in the Defender portal, they are located under Microsoft Sentinel > Configuration > Automation.

Microsoft Sentinel | Automation
Microsoft Sentinel | Automation

In this menu, we can create an automation rule, edit an automation rule, enable or disable it, move it up or down, or remove an automation rule. We can also filter automation rules by analytic rules, actions, triggers, statuses, who created them, and when they were last modified. Today, we don’t have the option to export or import automation rules as we do for analytics rules; however, this might change in the not-too-distant future. Stay Tuned!

Manage Microsoft Sentinel Automation rules
Manage Microsoft Sentinel Automation rules

The question often arises: how can we export the Automation Rule as code? There is no export or code editor for Automation Rules. We can easily export the Playbook (Logic App) as code, but we can’t find much documentation on automating this procedure to create an Automation Rule through the Sentinel Repositories. Exporting and importing Microsoft Sentinel automation rules is also useful for backing up, restoring, or importing scenarios to different environments.

RelatedCheck how to enable Microsoft Sentinel Analytics Rules at Scale.

Let’s see how to automate this process and export Microsoft Sentinel Automation rules at scale.

Prerequisites

To follow this article, you need to have the following:

1) Azure subscription – If you don’t have an Azure subscription, you can create one here for free.

2) Log Analytics workspace – To create a new workspace, follow the instructions to create a Log Analytics workspace.

3) Enable Microsoft Sentinel at no additional cost on an Azure Monitor Log Analytics workspace for the first 31 days; follow the quick onboarding process. Once Microsoft Sentinel is enabled on your Azure Monitor Log Analytics workspace, every GB of data ingested into the workspace can be retained at no charge for the first 90 days.

4) Azure PowerShell is installed locally on your machine or using Cloud Shell.

To install Azure Accounts PowerShell modules on your machine, you can run the following command:

# Install and update to the latest Az PowerShell module
Install-Module -Name Az.Accounts -AllowClobber -Force

# Check the Az PowerShell modules version installed
Get-Module -Name Az.Accounts -ListAvailable | Select Name, Version

5) Before running the script below, you must have created one or more automation rules.

6) Last, ensure you have permission for the Microsoft Sentinel Contributor role, which is required to create and manage automation rules.

RelatedCheck how to update Microsoft Sentinel Analytics Rules at Scale.

Assuming you have all the prerequisites in place, take the following steps:

Export Automation Rules

This section will describe how to export the Microsoft Sentinel Automation Rules you created automatically. This tool will also work for automation rules that are enabled or disabled.

You have several options for running the script: Azure Cloud Shell, Visual Studio Code, or Windows Terminal. The Script works with PowerShell 5.1 or PowerShell 7 (core) with the Az module.

.EXAMPLE-1

.\Export-AutomationRules.ps1 -SubscriptionId "SUB-ID" -ResourceGroup "RG-Name" `
     -WorkspaceName "Log-Analytics-Name" -Status "Enabled/Disabled/All" -Verbose

This example will connect to your Azure account using the subscription ID specified and then export all automation rules to JSON templates. The state “Enabled” automation rules will be exported by default. You can also export “Disabled” or “All” automation rules.

Here is an example of the output once you run this tool:

Export Automation Rules
Export Automation Rules

By default, all the automation rules JSON templates are exported to the following path: “C:\temp“. You can change the default path as needed.

Export Automation Rules locally
Export Automation Rules locally

This is version 1.0. If you have any feedback or changes that everyone should receive, please feel free to leave a comment below.

PowerShell Code

Below is the script to automatically export Microsoft Sentinel Automation Rules. You need to run this script on demand; check this article to learn how to automate the export process based on a weekly schedule.

<#
.SYNOPSIS
Export Microsoft Sentinel automation rules.

.DESCRIPTION
How to export Microsoft Sentinel automation rules at once using PowerShell and REST API.

.NOTES
File Name : Export-AutomationRules.ps1
Author    : Microsoft MVP/MCT - Charbel Nemnom
Version   : 1.0
Date      : 01-May-2024
Updated   : 02-May-2024
Requires  : PowerShell 6.2 or PowerShell 7.x.x (Core)
Module    : Az Module

.LINK
To provide feedback or for further assistance please visit:
https://charbelnemnom.com

.EXAMPLE
.\Export-AutomationRules.ps1 -SubscriptionId <SUB-ID> -ResourceGroup <RG-Name> `
    -WorkspaceName <Log-Analytics-Name> -Status <Enabled> -Verbose
This example will connect to your Azure account using the subscription Id specified, and then export all automation rules to JSON templates.
By default, the automation rules with the state "Enabled" will be exported. Optionally, you can export both Enabled and Disabled automation rules.
#>

param (
    [Parameter(Position = 0, Mandatory = $true, HelpMessage = 'Enter Azure Subscription ID')]
    [string]$subscriptionId,
    [Parameter(Position = 1, Mandatory = $true, HelpMessage = 'Enter Resource Group Name where Microsoft Sentinel is deployed')]
    [string]$resourceGroupName,
    [Parameter(Position = 2, Mandatory = $true, HelpMessage = 'Enter Log Analytics Workspace Name')]
    [string]$workspaceName,
    [Parameter(Position = 3, Mandatory = $true, HelpMessage = 'Select the status of the automation rules to export')]
    [ValidateSet('Enabled', 'Disabled', 'All')]
    [String]$status = 'Enabled'
)

#! Install Az Module If Needed
function Install-Module-If-Needed {
    param([string]$ModuleName)

    if (Get-Module -ListAvailable -Name $ModuleName) {
        Write-Host "Module '$($ModuleName)' already exists, continue..." -ForegroundColor Green
    }
    else {
        Write-Host "Module '$($ModuleName)' does not exist, installing..." -ForegroundColor Yellow
        Install-Module $ModuleName -Force -AllowClobber -ErrorAction Stop
        Write-Host "Module '$($ModuleName)' installed." -ForegroundColor Green
    }
}

function Export-AutomationRules {
    param (
        $subscriptionId,
        $apiVersion,
        $resourceGroupNam,
        $workspaceName
    )

    #! Get Az Access Token
    $token = Get-AzAccessToken #This will default to Azure Resource Manager endpoint
    $authHeader = @{
        'Content-Type'  = 'application/json'
        'Authorization' = 'Bearer ' + $token.Token
    }

    # Define Automation Rules URI
    $ruleURI = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.OperationalInsights/workspaces/$workspaceName/providers/Microsoft.SecurityInsights/automationRules$($apiVersion)"
    $ruleResult = Invoke-RestMethod $ruleURI -Method 'GET' -Headers $authHeader       
    return $ruleResult
}

#! Install Az Accounts Module If Needed
Install-Module-If-Needed Az.Accounts

#! Check Azure Connection
Try {
    Write-Verbose "Connecting to Azure Cloud..."
    Connect-AzAccount -ErrorAction Stop | Out-Null
}
Catch {
    Write-Warning "Cannot connect to Azure Cloud. Please check your credentials. Exiting!"
    Break
}

# Define the latest API Version to use for Microsoft Sentinel
$apiVersion = "?api-version=2024-03-01"

If ($status -eq 'Enabled') {   
    Write-Verbose "Getting $($status) Automation Rules..."
    # Get all Enabled Automation Rules  
    $ruleResult = (Export-AutomationRules -apiVersion $apiVersion -subscriptionId $subscriptionId -resourceGroupName $resourceGroupName -workspaceName $workspaceName).value
    $activeRules = $ruleResult | Where-Object { $_.properties.triggeringLogic.isEnabled -eq $true }
    Write-Verbose "Exporting $($status) Automation Rules..." 
}
elseif ($status -eq 'Disabled') {
    Write-Verbose "Getting $($status) Automation Rules..."
    # Get all Disabled Automation Rules    
    $ruleResult = (Export-AutomationRules -apiVersion $apiVersion -subscriptionId $subscriptionId -resourceGroupName $resourceGroupName -workspaceName $workspaceName).value
    $activeRules = $ruleResult | Where-Object { $_.properties.triggeringLogic.isEnabled -eq $false }
    Write-Verbose "Exporting $($status) Automation Rules..." 
}
else {
    Write-Verbose "Getting $($status) Automation Rules..."
    # Get all Automation Rules    
    $ruleResult = (Export-AutomationRules -apiVersion $apiVersion -subscriptionId $subscriptionId -resourceGroupName $resourceGroupName -workspaceName $workspaceName).value
    $activeRules = $ruleResult
    Write-Verbose "Exporting $($status) Automation Rules..." 
}

try {    
    if ($activeRules.count -eq 0) {
        throw "No $($status) Automation Rules were found!"
    }
    else {
        Write-Output "$($activeRules.count) $($status) Automation Rules were found!"
    }
}
catch {
    Write-Error $_ -ErrorAction Stop
}

$exportedActiveRules = @()

foreach ($activeRule in $activeRules) {
    $ruleExport = $activeRule | ConvertTo-Json -Depth 100

    Write-Verbose "Exporting [$($activeRule.properties.displayName).json] to C:\temp\"
    $ruleExport | Out-File -FilePath "C:\temp\$($activeRule.properties.displayName).json" -Force
    $exportedActiveRules += $rule
}

try {    
    if ($exportedActiveRules.count -eq 0) {
        throw "No $($status) Automation Rules were exported!"
    }
    else {
        Write-Output "$($exportedActiveRules.count) $($status) Automation Rules were exported!"
    }
}
catch {
    Write-Error $_ -ErrorAction Stop
}

Once the export is completed, you can verify the JSON template in VSCode.

Automation rule JSON template
Automation rule JSON template

That’s it, there you have it. Happy Exporting Microsoft Sentinel Automation Rules at Scale!

In Summary

This article showed you how to use PowerShell and REST API to export Microsoft Sentinel Automation Rules at scale. This is very useful if you have many automation rules and want to automate their export and import to different environments.

Once you have the JSON templates of these rules, you can use them as code to create new Automation Rules through the Microsoft Sentinel Repositories feature as part of your Microsoft Sentinel lifecycle management.

The power of Microsoft Sentinel comes from the ability to detect, investigate, respond to, and remediate threats.

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Photo of author
About the Author
Charbel Nemnom
Charbel Nemnom is a Senior Cloud Architect with 21+ years of IT experience. As a Swiss Certified Information Security Manager (ISM), CCSP, CISM, Microsoft MVP, and MCT, he excels in optimizing mission-critical enterprise systems. His extensive practical knowledge spans complex system design, network architecture, business continuity, and cloud security, establishing him as an authoritative and trustworthy expert in the field. Charbel frequently writes about Cloud, Cybersecurity, and IT Certifications.
Previous

How to Restrict Non-Admin Users from Creating Tenants in Microsoft Entra ID: A Step-by-Step Guide

Create Promptbooks in Microsoft Copilot for Security

Next

Let us know what you think, or ask a question...