How To Export and Backup Azure Policy Definitions

3 Min. Read

In this article, we will share with you how to export and back up Azure Policy definitions with PowerShell.

Introduction

A common theme in cloud environments is enforcing organizational standards and adopting cloud governance since day one. And this is very important since it will give you the ability to define policies, processes, and procedures. These policies then dictate what can be done and verify that what does exist is correct. A service from Microsoft called Azure Policy is a great way to make that happen and take proactive action.

Azure Policy is a service in Azure that you use to create, assign, and manage policies. These policies enforce different rules and effects on your resources, so those resources stay compliant with your corporate standards and service level agreements. Azure Policy meets this need by continuously evaluating your resources for non-compliance with assigned policies.

In this article, we will share with you a PowerShell script that will help you to export Azure Policy (custom) definitions, and then upload them to an Azure storage account for backup. This comes in handy when working and updating many policies, so you can have a backup copy to revert back if needed, and this is also helpful for auditing purposes. Please note that this approach is not perfect in any way, but I think it serves its purpose.

PowerShell script

Here is the script that will do the job for you. As a prerequisite, you need to have a storage account and one container with private access.

<#
.Synopsis
A script used to export and backup all Azure Policy custom definitions

.DESCRIPTION
A script used to get the list of all Azure Policy custom definitions in your Azure Subscription(s).
Finally, it will export the Policies into JSON files and then upload them to an Azure storage account.

.Notes
Created   : 2021-01-07
Version   : 1.0
Author    : Charbel Nemnom
Twitter   : @CharbelNemnom
Blog      : https://charbelnemnom.com
Disclaimer: This script is provided "AS IS" with no warranties.
#>

# Define Variables
$date = Get-Date -Format "dd-MM-yyyy"
$storageAccountRG     = "rg-storage-backup"
$storageAccountName   = "storaccazpolicybackup01"
$storageContainerName = "azure-policies"

# Get Storage Account Key
$storageAccountKey = (Get-AzStorageAccountKey -ResourceGroupName $storageAccountRG -AccountName $storageAccountName).Value[0]

# Set AzStorageContext
$destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey

# Generate SAS URI Token which is valid for 15 minutes ONLY
$containerSASURI = New-AzStorageContainerSASToken -Context $destinationContext -ExpiryTime(get-date).AddSeconds(900) -FullUri -Name $storageContainerName -Permission rw

# Export Azure Policy definitions
$policies = Get-AzPolicyDefinition | Where-Object {$_.Properties.PolicyType -eq "Custom"}
foreach ($policy in $policies) {
$policy.properties | ConvertTo-Json -Depth 12 | `
 Out-File "$($home)/clouddrive/Backup_$($policy.properties.DisplayName)_$date.json"
# Backup Azure Policy to Azure Storage
 azcopy cp "$($home)/clouddrive/Backup_$($policy.properties.DisplayName)_$date.json" $containerSASURI 
}

# Delete Azure Policies from the Azure Shell cloud drive
Remove-Item Backup* -Force

From the example above, we are performing the following steps:

  • Generate a temporary shared access signature (SAS) URI token for the container valid for 15 minutes with (Read and Write) permission.
  • Export all Azure Policy (custom) definitions as a JSON file.
  • Upload the Policies to a storage container using the AzCopy command line.
  • Finally, delete the JSON files from the cloud shell drive.

Run the script

To run the script, you need to use the Azure Cloud Shell at (https://shell.azure.com), or you can use the Azure Cloud Shell Connector in Windows Terminal.

How To Export and Backup Azure Policy Definitions 1

The policies will be exported to the clouddrive path following the Policy Display name. In my example, I have 4 custom policies.

How To Export and Backup Azure Policy Definitions 2

Finally, switch to the storage account container and check the policies are uploaded as shown in the figure below.

How To Export and Backup Azure Policy Definitions 3

Please note that you can accomplish the same thing using Azure CLI; however, I prefer to use Azure PowerShell. Additionally, you can automate it and have it run on a scheduled basis.

In Summary

In this article, we showed you how to export and back up Azure Policy definitions with PowerShell.

Azure Cloud Shell is so powerful that you don’t need to install Azure CLI or PowerShell modules locally on your machine to automate your tasks.

This is version 1.0 of this tool, do you want additional features? Please feel free to leave a comment below.

Hope this helps!

__
Thank you for reading my blog.

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

-Charbel Nemnom-

Previous

Export All NSG Rules from All Azure Subscriptions with PowerShell

Sync Between Azure File Share and Azure Blob Container

Next

8 thoughts on “How To Export and Backup Azure Policy Definitions”

Leave a comment...

  1. Hello Padenom, thanks for the comment!
    Yes sure, you can import the policies to another or the same tenant, to a subscription, or to a management group.
    You can use the following syntax to import the policies:

    # Import Policy to a Management Group
    New-AzPolicyDefinition -Name "PolicyName" -ManagementGroupName "MgmtGroupName" -Policy C:\BackupLocationPolicy.json
    
    # Import Policy to a Subscription
    New-AzPolicyDefinition -Name "PolicyName" -SubscriptionId "Sub-Id-Number" -Policy C:\BackupLocationPolicy.json

    Hope it helps!

  2. Hello Niharika, thanks for the comment!

    Yes, there is a DevOps-friendly approach to exporting Azure Policy definitions, especially now that GitHub exports have been deprecated. You can achieve this by integrating Azure Policy with Azure DevOps or GitHub Actions using automation pipelines.

    You can create an Azure DevOps pipeline that runs on a scheduled basis or triggered by a change in policies. The pipeline will run a PowerShell or Azure CLI script to export Azure Policy definitions and store them in a repository (e.g., Azure Repos) or backup them to an Azure storage account.

    Below are some key steps to achieve this using Azure DevOps pipelines:

    1) Create a PowerShell Script: Use the PowerShell script provided in the article above or modify it to suit your needs.

    > Use Get-AzPolicyDefinition to export custom policy definitions.
    > Store the policies in a location accessible by your pipeline (e.g., Azure storage, a Git repository, or an artifact repository).

    2) Define a Pipeline in Azure DevOps: Create a pipeline that will run the PowerShell script. Here is a basic example of the pipeline YAML configuration:

    trigger:
      branches:
        include:
          - main  # Run on the main branch changes
    
    schedule:
      cron: "0 2 * * *"  # Daily schedule at 2 AM
    
    jobs:
      - job: ExportAzurePolicies
        pool:
          vmImage: 'ubuntu-latest'
    
        steps:
        - task: AzureCLI@2
          inputs:
            azureSubscription: 'Your-Service-Connection'
            scriptType: 'pscore'
            scriptLocation: 'inlineScript'
            inlineScript: |
              # Call your PowerShell script here to export policies
              ./export-azure-policies.ps1

    3) Store the Exported Policies in a Git Repo or Storage Account:

    Last, you can use the same approach mentioned in the article above to upload the exported policy files to an Azure Storage account. Alternatively, the policies can be committed to Azure Repos or even pushed back into a different branch of the same repository if needed.

    Hope it helps!

  3. Is there a way to back up the Azure Policy Initiative with the policies and settings, as I don’t see a way of doing this currently?

  4. Hello Coote, thanks for your comment and great question!
    Yes, you can back up Azure Policy Initiatives (Policy Set Definitions) using a similar approach. You can use the Get-AzPolicySetDefinition PowerShell cmdlet to export them, or use Azure CLI with az policy set-definition list. This will capture the initiative definition along with its referenced policies and parameter settings. You can then export the output to JSON for backup.
    Hope it helps!

  5. The initative backup doesn’t allow you to also export the policies as part of the initative. Seems only to provide the information of the policy within the initative.

  6. Thanks for the follow-up! Yes this is true, exporting an initiative only gives you the initiative structure with references to the policy IDs and parameter mappings, not the full policy definitions themselves.
    To do a complete backup of an initiative with all its policies, you’d need a combined approach as follows:

    1. Export the initiative definition using Get-AzPolicySetDefinition
    2. Parse the referenced policyDefinitionId values from the output
    3. Loop through each and export the full policy definition using Get-AzPolicyDefinition

    This way you capture both the initiative structure and the actual policy content. Unfortunately, there’s no single built-in command or REST API endpoint that does this all in one step, as Policy Set Definitions and Policy Definitions are separate resources. This could be automated with a PowerShell script or an Azure Function for recurring backups.
    Hope this helps!

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