Export all custom Azure Policies - Code Sample

@20aman    Nov 11, 2021

Azure Policies are a key component in any Azure governance strategy. These help you allow or deny particular operations in your environment. These can also help you audit your environment for compliance with your standards (both out of the box and custom). There are two types of Azure policies:

  1. Built-In - also called out of the box, that are provided by Microsoft
  2. Custom - that you build for your environment as per your policies and standards.

It is a best practice to store all the custom policies in a version control system e.g. Azure DevOps repositories. If the policies were built directly within the Azure Policies definitions, then you would want to export all of the policies. Exporting one policy at a time can be time-consuming and also prone to end-user errors. You can leverage the script sample from this blog post to automate exporting all the custom policies in your environment (for all subscriptions).

Script location in GitHub

The complete script to export all the custom Azure policies across various subscriptions, can be found here:

Export-AllAzureCustomPolicies

Script working

The script works by iterating over various subscriptions and then fetching the Azure policies in that subscription. It filters on the "PolicyType" property to filter out only the policies that are Custom.

$policies = Get-AzPolicyDefinition | where {$_.Properties.PolicyType -eq 'Custom'}

Once all the custom policies have been fetched, the script then iterates through all policies using a "foreach" loop. For each policy, it sets the policy name to the subscription name then an underscore, and then the policy name. The file type is set to ".json".

$fileName = $currentSubscription.Name + "_" + $policyName + ".json"

The script then exports the policy to a JSON file using the ConvertTo-Json cmdlet.

$policy | ConvertTo-Json -Depth 10 | Out-File ".\Export-AzurePolicies\Output\$fileName"

Give it a try in your environment. Once you have exported JSON files for all the custom policies, make sure to move this into a version control system like Azure DevOps repositories.





Comments powered by Disqus