I wrote many blogs about policies in Azure. First, I started talking about How essential Policies are. After that, I included them in a blog about Azure SQL AD Only Authentication and finally about how to ensure Azure SQL is with Azure AD Only Authentication enabled.
Using both, policies and management groups, we can manage standards across a word-wide company tenant. We can create policies on many hierarchical levels and apply them.
When we create new policies and assign them to a management group, we may would like to have an evaluation of these policies, know the compliance of the existing objects.
We can manually trigger this evaluation even in a world-wide level. The evaluation is always triggered on a resource group level.
Manually Triggering the Policies
That’s what I’m including on this post: A powershell script to trigger the policy evaluation for all resource groups in a company tenant.
The resource groups may be in different subscriptions. We will need to list the subscriptions and execute the evaluation for the resources groups on each subscription at a time.
For this, I will use another trick I already wrote about many times: KQL – Kusto Query Language.
You may would like to check some articles I wrote about KQL:
- Saving Money with Log Analytics
- Connecting to Log Analytics using Azure Data Studio and KQL
- Log Analytics and Azure Data Studio: New Extension
- Create Kusto Sub-Queries
- Creating Functions in Kusto Queries
- Using Power BI to Query Log Analytics
Microsoft built a layer on Azure background called Azure Resource Graph. Azure Resource Graph allow us to use KQL to query Azure Resources.
We can execute a KQL query in Powershell to retrieve the objects we need to deal with, then we process these objects. This can make some powershell code way easier.
The script below does this task
- Retrieves the subscriptions from Azure
- Loop through the retrieved subscriptions
- For each subscription, change Azure context to it
- Get all resource groups
- For each resource group, start processing the policies as a powershell job
Executing the Script
This script doesn’t care about the azure authentication because it’s built to be executed inside the Cloud Shell. In this way, the authentication will already be present and the script works exactly as it is now.
The cloud shell can make things even easier for us. It’s linked to a File share in a storage account. We can create a map of this file share in our local machine and use it to create and edit scripts like this one on your local machine and directly save them to the cloud shell.
On the storage account containing the cloud shell, you can access the cloud shell file share and click the Connect button
This opens a window with scripts. We need to run these scripts locally to create the windows drive mapping to the cloud shell file share.