Monday, 14 December 2020

Speed up Azure policy compliance scan

One of the painful things when I first started to use Azure policy to conduct audits was that it could take up to 24 hours before it would do it first initial scan. If I was to make changes it could take up to 24 hours before the policy would run again. Going backwards and forwards like this means usually it could take up to a week before the policy I am writing could be completed. There were ways to speed it up by either: issuing API calls to force a rescan but it was something that I couldn't quite grasp at the time or you could delete the policy and recreate it which would trigger a initial scan which nowdays should run within a few hours.

Moving forward now, there is a powershell cmdlet to help speed up the policy rescan which can be targeted at specific resource group or a complete subscription. At present there doesn't seem to be a way with powershell to trigger a specific policy rescan.

Here is how you do it

As this cmdlet is based on the new Az modules I tend to just use the cloud shell which you can launch once you have logged in to the azure portal (https://portal.azure.com)

If you have access to multiple subscriptions then the first cmdlet to run is Set-AzContext -Subscription "Replace_With_Subscription_Name" so that we are working within the correct subscription context

For me I always attach a policy to a resource group first and tend to test the policy against resources within a resource group. The cmdlet to use is Start-AzPolicyComplianceScan which will do a full scan across the subscription that is in context. To do a scan for a specfic resource group you would use Start-AzPolicyComplianceScan -ResourceGroupName "Replace_With_Resource_Group_Name". Below I have start the scan as a Job where we wait for the job to complete. The command used is $job = Start-AzPolicyComplianceScan -AsJob.
As I said before we are running this as a job which means if you was to chain more powershell commands then they would not run until this job is completed, To see if the job is completed or not then we issue $job to see the status. Once you see the status as per below then it means the scan has completed.
Now go into the Azure portal and go to policy > compliance section and select your subscription. Look for the compliance of your policy and see if it has changed. If it has not changed the click on refresh a few times and hopefully you will see your changes.

I have found this cmdlet really useful as it helps me see my changes to the policy definition quicker and I can edit and amend changes faster.


For more information go https://docs.microsoft.com/en-us/azure/governance/policy/how-to/get-compliance-data

No comments:

Post a Comment

Azure Resource Support for Availability Zone

Over the years, an increasing number of services are consumed in the cloud and as architects one of the key considerations is designing the ...