Редагувати

Поділитися через


Get compliance data of Azure resources

One of the largest benefits of Azure Policy is the insight and controls it provides over resources in a subscription or management group of subscriptions. This control can be used to prevent resources from being created in the wrong location, enforce common and consistent tag usage, or audit existing resources for appropriate configurations and settings. In all cases, data is generated by Azure Policy to enable you to understand the compliance state of your environment.

Before reviewing compliance data, it's important to understand compliance states in Azure Policy.

There are several ways to access the compliance information generated by your policy and initiative assignments:

Before looking at the methods to report on compliance, let's look at when compliance information is updated and the frequency and events that trigger an evaluation cycle.

Evaluation triggers

The results of a completed evaluation cycle are available in the Microsoft.PolicyInsights Resource Provider through PolicyStates and PolicyEvents operations. For more information about the operations of the Azure Policy Insights REST API, see Azure Policy Insights.

Evaluations of assigned policies and initiatives happen as the result of various events:

  • A policy or initiative is newly assigned to a scope. It takes around five minutes for the assignment to be applied to the defined scope, then the evaluation cycle begins for applicable resources against the newly assigned policy or initiative. Depending on the effects used, resources are marked as compliant, non-compliant, exempt, or unknown. A large policy or initiative evaluated against a large scope of resources can take time, so there's no predefined expectation of when the evaluation cycle completes. After it completes, updated compliance results are available in the portal and SDKs.

  • A policy or initiative already assigned to a scope is updated. The evaluation cycle and timing for this scenario is the same as for a new assignment to a scope.

  • A resource is deployed to or updated within a scope with an assignment via Azure Resource Manager, REST API, or a supported SDK. In this scenario, the effect event (append, audit, deny, deploy) and compliant status information for the individual resource becomes available in the portal and SDKs around 15 minutes later. This event doesn't cause an evaluation of other resources.

  • A subscription (resource type Microsoft.Resources/subscriptions) is created or moved within a management group hierarchy with an assigned policy definition targeting the subscription resource type. Evaluation of the subscription supported effects (audit, auditIfNotExist, deployIfNotExists, modify), logging, and any remediation actions takes around 30 minutes.

  • A policy exemption is created, updated, or deleted. In this scenario, the corresponding assignment is evaluated for the defined exemption scope.

  • Standard compliance evaluation cycle. Once every 24 hours, assignments are automatically reevaluated. A large policy or initiative of many resources can take time, so there's no pre-defined expectation of when the evaluation cycle completes. Once it completes, updated compliance results are available in the portal and SDKs.

  • The machine configuration resource provider is updated with compliance details by a managed resource.

  • On-demand scan

Note

By design, Azure Policy exempts all resources under the Microsoft.Resources resource provider (RP) from policy evaluation with the exception of subscriptions and resource groups, which can be evaluated.

On-demand evaluation scan

An evaluation scan for a subscription or a resource group can be started with Azure CLI, Azure PowerShell, a call to the REST API, or by using the Azure Policy Compliance Scan GitHub Action. This scan is an asynchronous process.

Note

Not all Azure resource providers support on-demand evaluation scans. For example, Azure Virtual Network Manager (AVNM) currently doesn't support either manual triggers or the standard policy compliance evaluation cycle (daily scans).

On-demand evaluation scan - GitHub Action

Use the Azure Policy Compliance Scan action to trigger an on-demand evaluation scan from your GitHub workflow on one or multiple resources, resource groups, or subscriptions, and gate the workflow based on the compliance state of resources. You can also configure the workflow to run at a scheduled time so that you get the latest compliance status at a convenient time. Optionally, GitHub Actions can generate a report on the compliance state of scanned resources for further analysis or for archiving.

The following example runs a compliance scan for a subscription.

on:
  schedule:
    - cron:  '0 8 * * *'  # runs every morning 8am
jobs:
  assess-policy-compliance:
    runs-on: ubuntu-latest
    steps:
    - name: Login to Azure
      uses: azure/login@v1
      with:
        creds: ${{secrets.AZURE_CREDENTIALS}}

    - name: Check for resource compliance
      uses: azure/policy-compliance-scan@v0
      with:
        scopes: |
          /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

For more information and workflow samples, see the GitHub Actions for Azure Policy Compliance Scan repo.

On-demand evaluation scan - Azure CLI

The compliance scan is started with the az policy state trigger-scan command.

By default, az policy state trigger-scan starts an evaluation for all resources in the current subscription. To start an evaluation on a specific resource group, use the resource-group parameter. The following example starts a compliance scan in the current subscription for the MyRG resource group:

az policy state trigger-scan --resource-group "MyRG"

You can choose not to wait for the asynchronous process to complete before continuing with the no-wait parameter.

On-demand evaluation scan - Azure PowerShell

The compliance scan is started with the Start-AzPolicyComplianceScan cmdlet.

By default, Start-AzPolicyComplianceScan starts an evaluation for all resources in the current subscription. To start an evaluation on a specific resource group, use the ResourceGroupName parameter. The following example starts a compliance scan in the current subscription for the MyRG resource group:

Start-AzPolicyComplianceScan -ResourceGroupName 'MyRG'

You can have PowerShell wait for the asynchronous call to complete before providing the results output or have it run in the background as a job. To use a PowerShell job to run the compliance scan in the background, use the AsJob parameter and set the value to an object, such as $job in this example:

$job = Start-AzPolicyComplianceScan -AsJob

You can check on the status of the job by checking on the $job object. The job is of the type Microsoft.Azure.Commands.Common.AzureLongRunningJob. Use Get-Member on the $job object to see available properties and methods.

While the compliance scan is running, checking the $job object outputs results such as these:

$job

Id     Name              PSJobTypeName     State         HasMoreData     Location             Command
--     ----              -------------     -----         -----------     --------             -------
2      Long Running O... AzureLongRunni... Running       True            localhost            Start-AzPolicyCompliance...

When the compliance scan completes, the State property changes to Completed.

On-demand evaluation scan - REST

As an asynchronous process, the REST endpoint to start the scan doesn't wait until the scan is complete to respond. Instead, it provides a URI to query the status of the requested evaluation.

In each REST API URI, there are variables that are used that you need to replace with your own values:

  • {YourRG} - Replace with the name of your resource group
  • {subscriptionId} - Replace with your subscription ID

The scan supports evaluation of resources in a subscription or in a resource group. Start a scan by scope with a REST API POST command using the following URI structures:

  • Subscription

    POST https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2019-10-01
    
  • Resource group

    POST https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{YourRG}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2019-10-01
    

The call returns a 202 Accepted status. Included in the response header is a location property with the following format:

https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/asyncOperationResults/{ResourceContainerGUID}?api-version=2019-10-01

{ResourceContainerGUID} is statically generated for the scope requested. If a scope is already running an on-demand scan, a new scan isn't started. Instead, the new request is provided the same {ResourceContainerGUID} location URI for status. A REST API GET command to the location URI returns a 202 Accepted while the evaluation is ongoing. When the evaluation scan is complete, it returns a 200 OK status. The body of a completed scan is a JSON response with the status:

{
  "status": "Succeeded"
}

On-demand evaluation scan - Visual Studio Code

The Azure Policy extension for Visual Studio Code is capable of running an evaluation scan for a specific resource. This scan is a synchronous process, unlike the Azure PowerShell and REST methods. For details and steps, see On-demand evaluation with the VS Code extension.

Portal

The Azure portal showcases a graphical experience of visualizing and understanding the state of compliance in your environment. On the Policy page, the Overview option provides details for available scopes on the compliance of both policies and initiatives. Along with the compliance state and count per assignment, it contains a chart showing compliance over the last seven days. The Compliance page contains much of this same information (except the chart), but provides more filtering and sorting options.

Screenshot of Compliance page, filtering options, and details.

Since a policy or initiative can be assigned to different scopes, the table includes the scope for each assignment and the type of definition that was assigned. The number of non-compliant resources and non-compliant policies for each assignment are also provided. Selecting on a policy or initiative in the table provides a deeper look at the compliance for that particular assignment.

Screenshot of Compliance Details page, including counts and resource compliant details.

The list of resources on the Resource compliance tab shows the evaluation status of existing resources for the current assignment. The tab defaults to Non-compliant, but can be filtered. Events (append, audit, deny, deploy, modify) triggered by the request to create a resource are shown under the Events tab.

Screenshot of the Events tab on Compliance Details page.

For Resource Provider mode resources, on the Resource compliance tab, selecting the resource or right-clicking on the row and selecting View compliance details opens the component compliance details. This page also offers tabs to see the policies that are assigned to this resource, events, component events, and change history.

Screenshot of Component Compliance tab and compliance details for a Resource Provider mode assignment.

Back on the resource compliance page, select and hold (or right-click) on the row of the event you would like to gather more details on and select Show activity logs. The activity log page opens and is prefiltered to the search showing details for the assignment and the events. The activity log provides more context and information about those events.

Screenshot of the Activity Log for Azure Policy activities and evaluations.

Note

Compliance results can be exported from the Portal through Azure Resource Graph queries.

Command line

The same information available in the portal can be retrieved with the REST API (including with ARMClient), Azure PowerShell, and Azure CLI. For full details on the REST API, see the Azure Policy reference. The REST API reference pages have a green Try It button on each operation that allows you to try it right in the browser.

Use ARMClient or a similar tool to handle authentication to Azure for the REST API examples.

Summarize results

With the REST API, summarization can be performed by container, definition, or assignment. Here's an example of summarization at the subscription level using Azure Policy Insight's Summarize For Subscription:

POST https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/summarize?api-version=2019-10-01

The output summarizes the subscription. In the following example output, the summarized compliance are under value.results.nonCompliantResources and value.results.nonCompliantPolicies. This request provides further details, including each assignment that made up the non-compliant numbers and the definition information for each assignment. Each policy object in the hierarchy provides a queryResultsUri that can be used to get more detail at that level.

{
  "@odata.context": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#summary",
  "@odata.count": 1,
  "value": [
    {
      "@odata.id": null,
      "@odata.context": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#summary/$entity",
      "results": {
        "queryResultsUri": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=ComplianceState eq 'NonCompliant'",
        "nonCompliantResources": 15,
        "nonCompliantPolicies": 1
      },
      "policyAssignments": [
        {
          "policyAssignmentId": "/subscriptions/{subscriptionId}/resourcegroups/rg-tags/providers/microsoft.authorization/policyassignments/37ce239ae4304622914f0c77",
          "policySetDefinitionId": "",
          "results": {
            "queryResultsUri": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=ComplianceState eq 'NonCompliant' and PolicyAssignmentId eq '/subscriptions/{subscriptionId}/resourcegroups/rg-tags/providers/microsoft.authorization/policyassignments/37ce239ae4304622914f0c77'",
            "nonCompliantResources": 15,
            "nonCompliantPolicies": 1
          },
          "policyDefinitions": [
            {
              "policyDefinitionReferenceId": "",
              "policyDefinitionId": "/providers/microsoft.authorization/policydefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62",
              "effect": "deny",
              "results": {
                "queryResultsUri": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=ComplianceState eq 'NonCompliant' and PolicyAssignmentId eq '/subscriptions/{subscriptionId}/resourcegroups/rg-tags/providers/microsoft.authorization/policyassignments/37ce239ae4304622914f0c77' and PolicyDefinitionId eq '/providers/microsoft.authorization/policydefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62'",
                "nonCompliantResources": 15
              }
            }
          ]
        }
      ]
    }
  ]
}

Query for resources

In the previous example, value.policyAssignments.policyDefinitions.results.queryResultsUri provides a sample URI for all non-compliant resources for a specific policy definition. In the $filter value, ComplianceState is equal (eq) to NonCompliant, PolicyAssignmentId is specified for the policy definition, and then the PolicyDefinitionId itself. The reason for including the PolicyAssignmentId in the filter is because the PolicyDefinitionId could exist in several policy or initiative assignments with different scopes. By specifying both the PolicyAssignmentId and the PolicyDefinitionId, we can be explicit in the results we're looking for. Previously, for PolicyStates we used latest, which automatically sets a from and to time window of the last 24-hours.

https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=ComplianceState eq 'NonCompliant' and PolicyAssignmentId eq '/subscriptions/{subscriptionId}/resourcegroups/rg-tags/providers/microsoft.authorization/policyassignments/37ce239ae4304622914f0c77' and PolicyDefinitionId eq '/providers/microsoft.authorization/policydefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62'

The following example response was trimmed to a single non-compliant resource for brevity. The detailed response has several pieces of data about the resource, the policy or initiative, and the assignment. Notice that you can also see what assignment parameters were passed to the policy definition.

{
  "@odata.context": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest",
  "@odata.count": 15,
  "value": [
    {
      "@odata.id": null,
      "@odata.context": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
      "timestamp": "2018-05-19T04:41:09Z",
      "resourceId": "/subscriptions/{subscriptionId}/resourceGroups/rg-tags/providers/Microsoft.Compute/virtualMachines/linux",
      "policyAssignmentId": "/subscriptions/{subscriptionId}/resourceGroups/rg-tags/providers/Microsoft.Authorization/policyAssignments/37ce239ae4304622914f0c77",
      "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62",
      "effectiveParameters": "",
      "ComplianceState": "NonCompliant",
      "subscriptionId": "{subscriptionId}",
      "resourceType": "/Microsoft.Compute/virtualMachines",
      "resourceLocation": "westus2",
      "resourceGroup": "RG-Tags",
      "resourceTags": "tbd",
      "policyAssignmentName": "37ce239ae4304622914f0c77",
      "policyAssignmentOwner": "tbd",
      "policyAssignmentParameters": "{\"tagName\":{\"value\":\"costCenter\"},\"tagValue\":{\"value\":\"Contoso-Test\"}}",
      "policyAssignmentScope": "/subscriptions/{subscriptionId}/resourceGroups/RG-Tags",
      "policyDefinitionName": "1e30110a-5ceb-460c-a204-c1c3969c6d62",
      "policyDefinitionAction": "deny",
      "policyDefinitionCategory": "tbd",
      "policySetDefinitionId": "",
      "policySetDefinitionName": "",
      "policySetDefinitionOwner": "",
      "policySetDefinitionCategory": "",
      "policySetDefinitionParameters": "",
      "managementGroupIds": "",
      "policyDefinitionReferenceId": ""
    }
  ]
}

View events

When a resource is created or updated, a policy evaluation result is generated. Results are called policy events. Use the following URI to view recent policy events associated with the subscription.

https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/default/queryResults?api-version=2019-10-01

Your results resemble the following example:

{
  "@odata.context": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/$metadata#default",
  "@odata.count": 1,
  "value": [
    {
      "@odata.id": null,
      "@odata.context": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/$metadata#default/$entity",
      "NumAuditEvents": 16
    }
  ]
}

For more information about querying policy events, see the Azure Policy Events reference article.

Azure CLI

The Azure CLI command group for Azure Policy covers most operations that are available in REST or Azure PowerShell. For the full list of available commands, see Azure CLI - Azure Policy Overview.

Example: Getting the state summary for the topmost assigned policy with the highest number of non-compliant resources.

az policy state summarize --top 1

The top portion of the response looks like this example:

{
  "odatacontext": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#summary/$entity",
  "odataid": null,
  "policyAssignments": [
    {
      "policyAssignmentId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policyassignments/e0704696df5e4c3c81c873e8",
      "policyDefinitions": [
        {
          "effect": "audit",
          "policyDefinitionGroupNames": [
            ""
          ],
          "policyDefinitionId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policydefinitions/2e3197b6-1f5b-4b01-920c-b2f0a7e9b18a",
          "policyDefinitionReferenceId": "",
          "results": {
            "nonCompliantPolicies": null,
            "nonCompliantResources": 398,
            "policyDetails": [
              {
                "complianceState": "noncompliant",
                "count": 1
              }
            ],
            "policyGroupDetails": [
              {
                "complianceState": "noncompliant",
                "count": 1
              }
            ],
            "queryResultsUri": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01&$from=2020-07-14 14:01:22Z&$to=2020-07-15 14:01:22Z and PolicyAssignmentId eq '/subscriptions/{subscriptionId}/providers/microsoft.authorization/policyassignments/e0704696df5e4c3c81c873e8' and PolicyDefinitionId eq '/subscriptions/{subscriptionId}/providers/microsoft.authorization/policydefinitions/2e3197b6-1f5b-4b01-920c-b2f0a7e9b18a'",
            "resourceDetails": [
              {
                "complianceState": "noncompliant",
                "count": 398
              },
              {
                "complianceState": "compliant",
                "count": 4
              }
            ]
          }
        }
      ],
  ...

Example: Getting the state record for the most recently evaluated resource (default is by timestamp in descending order).

az policy state list --top 1
[
  {
    "complianceReasonCode": "",
    "complianceState": "Compliant",
    "effectiveParameters": "",
    "isCompliant": true,
    "managementGroupIds": "{managementgroupId}",
    "odatacontext": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
    "odataid": null,
    "policyAssignmentId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policyassignments/securitycenterbuiltin",
    "policyAssignmentName": "SecurityCenterBuiltIn",
    "policyAssignmentOwner": "tbd",
    "policyAssignmentParameters": "",
    "policyAssignmentScope": "/subscriptions/{subscriptionId}",
    "policyAssignmentVersion": "",
    "policyDefinitionAction": "auditifnotexists",
    "policyDefinitionCategory": "tbd",
    "policyDefinitionGroupNames": [
      ""
    ],
    "policyDefinitionId": "/providers/microsoft.authorization/policydefinitions/aa633080-8b72-40c4-a2d7-d00c03e80bed",
    "policyDefinitionName": "aa633080-8b72-40c4-a2d7-d00c03e80bed",
    "policyDefinitionReferenceId": "identityenablemfaforownerpermissionsmonitoring",
    "policyDefinitionVersion": "",
    "policyEvaluationDetails": null,
    "policySetDefinitionCategory": "security center",
    "policySetDefinitionId": "/providers/Microsoft.Authorization/policySetDefinitions/1f3afdf9-d0c9-4c3d-847f-89da613e70a8",
    "policySetDefinitionName": "1f3afdf9-d0c9-4c3d-847f-89da613e70a8",
    "policySetDefinitionOwner": "",
    "policySetDefinitionParameters": "",
    "policySetDefinitionVersion": "",
    "resourceGroup": "",
    "resourceId": "/subscriptions/{subscriptionId}",
    "resourceLocation": "",
    "resourceTags": "tbd",
    "resourceType": "Microsoft.Resources/subscriptions",
    "subscriptionId": "{subscriptionId}",
    "timestamp": "2020-07-15T08:37:07.903433+00:00"
  }
]

Example: Getting the details for all non-compliant virtual network resources.

az policy state list --filter "ResourceType eq 'Microsoft.Network/virtualNetworks'"
[
  {
    "complianceReasonCode": "",
    "complianceState": "NonCompliant",
    "effectiveParameters": "",
    "isCompliant": false,
    "managementGroupIds": "{managementgroupId}",
    "odatacontext": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
    "odataid": null,
    "policyAssignmentId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policyassignments/e0704696df5e4c3c81c873e8",
    "policyAssignmentName": "e0704696df5e4c3c81c873e8",
    "policyAssignmentOwner": "tbd",
    "policyAssignmentParameters": "",
    "policyAssignmentScope": "/subscriptions/{subscriptionId}",
    "policyAssignmentVersion": "",
    "policyDefinitionAction": "audit",
    "policyDefinitionCategory": "tbd",
    "policyDefinitionGroupNames": [
      ""
    ],
    "policyDefinitionId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policydefinitions/2e3197b6-1f5b-4b01-920c-b2f0a7e9b18a",
    "policyDefinitionName": "2e3197b6-1f5b-4b01-920c-b2f0a7e9b18a",
    "policyDefinitionReferenceId": "",
    "policyDefinitionVersion": "",
    "policyEvaluationDetails": null,
    "policySetDefinitionCategory": "",
    "policySetDefinitionId": "",
    "policySetDefinitionName": "",
    "policySetDefinitionOwner": "",
    "policySetDefinitionParameters": "",
    "policySetDefinitionVersion": "",
    "resourceGroup": "RG-Tags",
    "resourceId": "/subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Microsoft.Network/virtualNetworks/RG-Tags-vnet",
    "resourceLocation": "westus2",
    "resourceTags": "tbd",
    "resourceType": "Microsoft.Network/virtualNetworks",
    "subscriptionId": "{subscriptionId}",
    "timestamp": "2020-07-15T08:37:07.901911+00:00"
  }
]

Example: Getting events related to non-compliant virtual network resources that occurred after a specific date.

az policy state list --filter "ResourceType eq 'Microsoft.Network/virtualNetworks'" --from '2020-07-14T00:00:00Z'
[
  {
    "complianceReasonCode": "",
    "complianceState": "NonCompliant",
    "effectiveParameters": "",
    "isCompliant": false,
    "managementGroupIds": "{managementgroupId}",
    "odatacontext": "https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest/$entity",
    "odataid": null,
    "policyAssignmentId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policyassignments/e0704696df5e4c3c81c873e8",
    "policyAssignmentName": "e0704696df5e4c3c81c873e8",
    "policyAssignmentOwner": "tbd",
    "policyAssignmentParameters": "",
    "policyAssignmentScope": "/subscriptions/{subscriptionId}",
    "policyAssignmentVersion": "",
    "policyDefinitionAction": "audit",
    "policyDefinitionCategory": "tbd",
    "policyDefinitionGroupNames": [
      ""
    ],
    "policyDefinitionId": "/subscriptions/{subscriptionId}/providers/microsoft.authorization/policydefinitions/2e3197b6-1f5b-4b01-920c-b2f0a7e9b18a",
    "policyDefinitionName": "2e3197b6-1f5b-4b01-920c-b2f0a7e9b18a",
    "policyDefinitionReferenceId": "",
    "policyDefinitionVersion": "",
    "policyEvaluationDetails": null,
    "policySetDefinitionCategory": "",
    "policySetDefinitionId": "",
    "policySetDefinitionName": "",
    "policySetDefinitionOwner": "",
    "policySetDefinitionParameters": "",
    "policySetDefinitionVersion": "",
    "resourceGroup": "RG-Tags",
    "resourceId": "/subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Microsoft.Network/virtualNetworks/RG-Tags-vnet",
    "resourceLocation": "westus2",
    "resourceTags": "tbd",
    "resourceType": "Microsoft.Network/virtualNetworks",
    "subscriptionId": "{subscriptionId}",
    "timestamp": "2020-07-15T08:37:07.901911+00:00"
  }
]

Azure PowerShell

The Azure PowerShell module for Azure Policy is available on the PowerShell Gallery as Az.PolicyInsights. Using PowerShellGet, you can install the module using Install-Module -Name Az.PolicyInsights (make sure you have the latest Azure PowerShell installed):

# Install from PowerShell Gallery via PowerShellGet
Install-Module -Name Az.PolicyInsights

# Import the downloaded module
Import-Module Az.PolicyInsights

# Login with Connect-AzAccount if not using Cloud Shell
Connect-AzAccount

The module has the following cmdlets:

  • Get-AzPolicyStateSummary
  • Get-AzPolicyState
  • Get-AzPolicyEvent
  • Get-AzPolicyRemediation
  • Remove-AzPolicyRemediation
  • Start-AzPolicyRemediation
  • Stop-AzPolicyRemediation

Example: Getting the state summary for the topmost assigned policy with the highest number of non-compliant resources.

PS> Get-AzPolicyStateSummary -Top 1

NonCompliantResources : 15
NonCompliantPolicies  : 1
PolicyAssignments     : {/subscriptions/{subscriptionId}/resourcegroups/RG-Tags/providers/micros
                        oft.authorization/policyassignments/37ce239ae4304622914f0c77}

Example: Getting the state record for the most recently evaluated resource (default is by timestamp in descending order).

PS> Get-AzPolicyState -Top 1

Timestamp                  : 5/22/2018 3:47:34 PM
ResourceId                 : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Mi
                             crosoft.Network/networkInterfaces/linux316
PolicyAssignmentId         : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Mi
                             crosoft.Authorization/policyAssignments/37ce239ae4304622914f0c77
PolicyDefinitionId         : /providers/Microsoft.Authorization/policyDefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62
ComplianceState            : NonCompliant
SubscriptionId             : {subscriptionId}
ResourceType               : /Microsoft.Network/networkInterfaces
ResourceLocation           : westus2
ResourceGroup              : RG-Tags
ResourceTags               : tbd
PolicyAssignmentName       : 37ce239ae4304622914f0c77
PolicyAssignmentOwner      : tbd
PolicyAssignmentParameters : {"tagName":{"value":"costCenter"},"tagValue":{"value":"Contoso-Test"}}
PolicyAssignmentScope      : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags
PolicyDefinitionName       : 1e30110a-5ceb-460c-a204-c1c3969c6d62
PolicyDefinitionAction     : deny
PolicyDefinitionCategory   : tbd

Example: Getting the details for all non-compliant virtual network resources.

PS> Get-AzPolicyState -Filter "ResourceType eq '/Microsoft.Network/virtualNetworks'"

Timestamp                  : 5/22/2018 4:02:20 PM
ResourceId                 : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Mi
                             crosoft.Network/virtualNetworks/RG-Tags-vnet
PolicyAssignmentId         : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Mi
                             crosoft.Authorization/policyAssignments/37ce239ae4304622914f0c77
PolicyDefinitionId         : /providers/Microsoft.Authorization/policyDefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62
ComplianceState            : NonCompliant
SubscriptionId             : {subscriptionId}
ResourceType               : /Microsoft.Network/virtualNetworks
ResourceLocation           : westus2
ResourceGroup              : RG-Tags
ResourceTags               : tbd
PolicyAssignmentName       : 37ce239ae4304622914f0c77
PolicyAssignmentOwner      : tbd
PolicyAssignmentParameters : {"tagName":{"value":"costCenter"},"tagValue":{"value":"Contoso-Test"}}
PolicyAssignmentScope      : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags
PolicyDefinitionName       : 1e30110a-5ceb-460c-a204-c1c3969c6d62
PolicyDefinitionAction     : deny
PolicyDefinitionCategory   : tbd

Example: Getting events related to non-compliant virtual network resources that occurred after a specific date, converting to a CSV object, and exporting to a file.

$policyEvents = Get-AzPolicyEvent -Filter "ResourceType eq '/Microsoft.Network/virtualNetworks'" -From '2020-09-19'
$policyEvents | ConvertTo-Csv | Out-File 'C:\temp\policyEvents.csv'

The output of the $policyEvents object looks like the following output:

Timestamp                  : 9/19/2020 5:18:53 AM
ResourceId                 : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Mi
                             crosoft.Network/virtualNetworks/RG-Tags-vnet
PolicyAssignmentId         : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags/providers/Mi
                             crosoft.Authorization/policyAssignments/37ce239ae4304622914f0c77
PolicyDefinitionId         : /providers/Microsoft.Authorization/policyDefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62
ComplianceState            : NonCompliant
SubscriptionId             : {subscriptionId}
ResourceType               : /Microsoft.Network/virtualNetworks
ResourceLocation           : eastus
ResourceGroup              : RG-Tags
ResourceTags               : tbd
PolicyAssignmentName       : 37ce239ae4304622914f0c77
PolicyAssignmentOwner      : tbd
PolicyAssignmentParameters : {"tagName":{"value":"costCenter"},"tagValue":{"value":"Contoso-Test"}}
PolicyAssignmentScope      : /subscriptions/{subscriptionId}/resourceGroups/RG-Tags
PolicyDefinitionName       : 1e30110a-5ceb-460c-a204-c1c3969c6d62
PolicyDefinitionAction     : deny
PolicyDefinitionCategory   : tbd
TenantId                   : {tenantId}
PrincipalOid               : {principalOid}

The PrincipalOid field can be used to get a specific user with the Azure PowerShell cmdlet Get-AzADUser. Replace {principalOid} with the response you get from the previous example.

PS> (Get-AzADUser -ObjectId {principalOid}).DisplayName
Trent Baker

Azure Monitor logs

If you have a Log Analytics workspace with AzureActivity from the Activity Log Analytics solution tied to your subscription, you can also view non-compliance results from the evaluation of new and updated resources using simple Kusto queries and the AzureActivity table. With details in Azure Monitor logs, alerts can be configured to watch for non-compliance.

Screenshot of Azure Monitor logs showing Azure Policy actions in the AzureActivity table.

Azure Resource Graph

Compliance records are stored in Azure Resource Graph (ARG). Data can be exported from ARG queries to form customized dashboards based on the scopes and policies of interest. Review our sample queries for exporting compliance data through ARG.

Next steps