获取 Azure 资源的符合性数据Get compliance data of Azure resources

Azure Policy 的最大优势之一在于它针对订阅或订阅管理组中的资源提供的见解和控制度。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 exercised in many different ways, such as preventing resources being created in the wrong location, enforcing common and consistent tag usage, or auditing existing resources for appropriate configurations and settings. 在所有情况下,数据都由 Azure Policy 生成,使你能够了解环境的符合性状态。In all cases, data is generated by Azure Policy to enable you to understand the compliance state of your environment.

可通过多种方式访问策略和计划分配生成的符合性信息: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.

Warning

如果符合性状态被报告为“未注册”,请验证是否已注册 Microsoft.PolicyInsights 资源提供程序,并验证用户是否具有适当的基于角色的访问控制 (RBAC) 权限,如 Azure Policy 中的 RBAC 所述。If compliance state is being reported as Not registered, verify that the Microsoft.PolicyInsights Resource Provider is registered and that the user has the appropriate role-based access control (RBAC) permissions as described in RBAC in Azure Policy.

评估触发器Evaluation triggers

已完成的评估周期的结果通过 PolicyStatesPolicyEvents 操作在 Microsoft.PolicyInsights 资源提供程序中获取。The results of a completed evaluation cycle are available in the Microsoft.PolicyInsights Resource Provider through PolicyStates and PolicyEvents operations. 有关 Azure Policy Insights REST API 的操作的详细信息,请参阅 Azure Policy InsightsFor 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. 需要大约花费 30 分钟将分配应用到定义的范围。It takes around 30 minutes for the assignment to be applied to the defined scope. 应用分配后,将会针对新分配的策略或计划,对该范围内的资源执行评估周期,同时,会根据策略或计划使用的效果,将资源标记为合规或不合规。Once it's applied, the evaluation cycle begins for resources within that scope against the newly assigned policy or initiative and depending on the effects used by the policy or initiative, resources are marked as compliant or non-compliant. 针对大范围的资源评估的大型策略或计划可能需要花费一段时间。A large policy or initiative evaluated against a large scope of resources can take time. 因此,在评估周期何时完成方面,无法预先定义预期目标。As such, there's no pre-defined expectation of when the evaluation cycle will complete. 完成评估后,更新的符合性结果会在门户和 SDK 中提供。Once 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.

  • 资源将通过资源管理器、REST、Azure CLI 或 Azure PowerShell 部署到包含分配的范围。A resource is deployed to a scope with an assignment via Resource Manager, REST, Azure CLI, or Azure PowerShell. 在此场景中,个体资源的效果事件(追加、审核、拒绝、部署)和符合性状态将在大约 15 分钟后出现在门户与 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.

  • 标准符合性评估周期。Standard compliance evaluation cycle. 分配每隔 24 小时自动重新评估一次。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 will complete. 完成评估后,更新的符合性结果会在门户和 SDK 中提供。Once it completes, updated compliance results are available in the portal and SDKs.

  • 来宾配置资源提供程序更新受管理资源的符合性详细信息。The Guest Configuration resource provider is updated with compliance details by a managed resource.

  • 按需扫描On-demand scan

按需评估扫描On-demand evaluation scan

可以通过调用 REST API 来启动订阅或资源组的评估扫描。An evaluation scan for a subscription or a resource group can be started with a call to the REST API. 此扫描是一个异步过程。This scan is an asynchronous process. 因此,启动扫描的 REST 终结点不是等到扫描完成才能响应。As such, the REST endpoint to start the scan doesn't wait until the scan is complete to respond. 而是提供一个 URI,用于查询请求的评估的状态。Instead, it provides a URI to query the status of the requested evaluation.

在每个 REST API URI 中,包含替换为自己的值所使用的变量:In each REST API URI, there are variables that are used that you need to replace with your own values:

  • {YourRG} - 替换为资源组的名称{YourRG} - Replace with the name of your resource group
  • {subscriptionId} - 替换为订阅 ID{subscriptionId} - Replace with your subscription ID

扫描支持评估订阅或资源组中的资源。The scan supports evaluation of resources in a subscription or in a resource group. 使用以下 URI 结构,通过 REST API POST 命令开始按范围扫描:Start a scan by scope with a REST API POST command using the following URI structures:

  • 订阅Subscription

    POST https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview
    
  • 资源组Resource group

    POST https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/{YourRG}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview
    

该调用返回“202 Accepted”状态。The call returns a 202 Accepted status. 响应标头中包含 Location 属性,格式如下:Included in the response header is a Location property with the following format:

https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/asyncOperationResults/{ResourceContainerGUID}?api-version=2018-07-01-preview

以静态方式为请求的范围生成了 {ResourceContainerGUID}{ResourceContainerGUID} is statically generated for the scope requested. 如果某个范围已在运行按需扫描,则不会启动新扫描。If a scope is already running an on-demand scan, a new scan isn't started. 相反,会为新请求提供同一 {ResourceContainerGUID} 位置 URI 以查询状态。Instead, the new request is provided the same {ResourceContainerGUID} location URI for status. 在评估过程中,位置 URI 的 REST API GET 命令返回“202 Accepted”状态 。A REST API GET command to the Location URI returns a 202 Accepted while the evaluation is ongoing. 评估扫描完成后,返回“200 OK”状态。When the evaluation scan has completed, it returns a 200 OK status. 已完成的扫描的正文为 JSON 响应,其状态为:The body of a completed scan is a JSON response with the status:

{
    "status": "Succeeded"
}

符合性的工作原理How compliance works

在分配中,如果某资源不符合策略或计划规则,则该资源不合规。In an assignment, a resource is Non-compliant if it doesn't follow policy or initiative rules. 下表显示了对于生成的符合性状态,不同的策略效果是如何与条件评估配合使用的:The following table shows how different policy effects work with the condition evaluation for the resulting compliance state:

资源状态Resource state 效果Effect 策略评估Policy evaluation 符合性状态Compliance state
ExistsExists Deny、Audit、Append*、DeployIfNotExist*、AuditIfNotExist*Deny, Audit, Append*, DeployIfNotExist*, AuditIfNotExist* TrueTrue 不符合Non-compliant
ExistsExists Deny、Audit、Append*、DeployIfNotExist*、AuditIfNotExist*Deny, Audit, Append*, DeployIfNotExist*, AuditIfNotExist* FalseFalse 符合Compliant
新建New Audit、AuditIfNotExist*Audit, AuditIfNotExist* TrueTrue 不符合Non-compliant
新建New Audit、AuditIfNotExist*Audit, AuditIfNotExist* FalseFalse 符合Compliant

*Append、DeployIfNotExist 和 AuditIfNotExist 效果要求 IF 语句为 TRUE。* The Append, DeployIfNotExist, and AuditIfNotExist effects require the IF statement to be TRUE. 这些效果还要求存在条件为 FALSE 才能将资源判定为不合规。The effects also require the existence condition to be FALSE to be non-compliant. 如果为 TRUE,则 IF 条件会触发相关资源存在条件的计算。When TRUE, the IF condition triggers evaluation of the existence condition for the related resources.

例如,假设有一个资源组 ContsoRG,其中包含一些向公共网络公开的存储帐户(以红色突出显示)。For example, assume that you have a resource group – ContsoRG, with some storage accounts (highlighted in red) that are exposed to public networks.

向公共网络公开的存储帐户

在此示例中,需要慎重考虑安全风险。In this example, you need to be wary of security risks. 创建策略分配后,将会针对 ContosoRG 资源组中的所有存储帐户评估该分配。Now that you've created a policy assignment, it's evaluated for all storage accounts in the ContosoRG resource group. 它对这三个不合规的存储帐户进行审核,并因此将其状态更改为“不合规”。It audits the three non-compliant storage accounts, consequently changing their states to Non-compliant.

已审核不合规的存储帐户

除“符合”和“不符合”外,政策和资源还有 3 种状态 :Besides Compliant and Non-compliant, policies and resources have three other states:

  • 冲突:两项或多项策略的规则存在冲突。Conflicting: Two or more policies exist with conflicting rules. 例如,两项策略向不同的值附加了相同的标记。For example, two policies appending the same tag with different values.
  • 未启动:尚未针对策略或资源启动评估周期。Not started: The evaluation cycle hasn't started for the policy or resource.
  • 未注册:尚未注册 Azure Policy 资源提供程序,或者登录的帐户无权读取符合性数据。Not registered: The Azure Policy Resource Provider hasn't been registered or the account logged in doesn't have permission to read compliance data.

Azure Policy 使用定义中的“类型”和“名称”字段来确定资源是否匹配 。Azure Policy uses the type and name fields in the definition to determine if a resource is a match. 如果资源匹配,则被视为适用,状态为“符合”或“不符合” 。When the resource matches, it's considered applicable and has a status of either Compliant or Non-compliant. 如果“类型”或“名称”是定义中的唯一属性,则将所有资源视为适用并对其进行评估 。If either type or name is the only property in the definition, then all resources are considered applicable and are evaluated.

符合百分比是合规资源与总资源之比。The compliance percentage is determined by dividing Compliant resources by total resources. 根据定义,总资源是指合规资源、不合规资源和冲突资源的总和 。Total resources is defined as the sum of the Compliant, Non-compliant, and Conflicting resources. 整体符合性是不同合规资源的总和除以所有唯一资源。The overall compliance numbers are the sum of distinct resources that are Compliant divided by the sum of all distinct resources. 在下图中,有 20 种不同的资源适用,只有一种资源“不合规”。In the image below, there are 20 distinct resources that are applicable and only one is Non-compliant. 因此,资源的整体符合性为 95%(19/20)。The overall resource compliance is 95% (19 out of 20).

符合性页面上的策略符合性示例

门户Portal

Azure 门户展示了一个图形体验用于可视化和了解环境中的符合性状态。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 provide additional filtering and sorting options.

Azure Policy 符合性页面的示例

由于策略或计划可分配到不同的范围,因此表中包含每个分配的范围,以及分配的定义类型。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. 单击表中的某个策略或计划可以更深入地了解该特定分配的符合性。Clicking on a policy or initiative in the table provides a deeper look at the compliance for that particular assignment.

Azure Policy 符合性详细信息页面的示例

“资源符合性”选项卡上的资源列表显示当前分配的现有资源的评估状态。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) triggered by the request to create a resource are shown under the Events tab.

Azure Policy 符合性事件的示例

对于“资源提供程序”模式资源,在“资源符合性”选项卡上选择资源或右键单击行并选择“查看符合性详细信息”即可打开组件符合性详细信息。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.

Azure Policy 组件符合性详细信息的示例

回到资源符合性页,右键单击要收集其更多详细信息的事件所在的行,然后选择“显示活动日志”。Back on the resource compliance page, 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 pre-filtered to the search showing details for the assignment and the events. 活动日志提供有关这些事件的其他上下文和信息。The activity log provides additional context and information about those events.

Azure Policy 符合性活动日志的示例

了解不符合性Understand non-compliance

当确定资源为不符合时,有许多可能的原因。When a resources is determined to be non-compliant, there are many possible reasons. 若要确定资源不符合的原因或查找负责的更改,请参阅确定不符合性To determine the reason a resource is non-compliant or to find the change responsible, see Determine non-compliance.

命令行Command line

可以使用 REST API(包括使用 ARMClient)、Azure PowerShell 和 Azure CLI(预览版)来检索门户中提供的相同信息。The same information available in the portal can be retrieved with the REST API (including with ARMClient), Azure PowerShell, and Azure CLI (preview). 有关 REST API 的完整详细信息,请参阅 Azure Policy Insights 参考文章。For full details on the REST API, see the Azure Policy Insights reference. REST API 参考页上针对每个操作提供了一个绿色的“试用”按钮,使用该按钮可在浏览器中直接试用该操作。The REST API reference pages have a green 'Try It' button on each operation that allows you to try it right in the browser.

对于 REST API 示例,请使用 ARMClient 或类似工具处理向 Azure 进行身份验证的问题。Use ARMClient or a similar tool to handle authentication to Azure for the REST API examples.

汇总结果Summarize results

使用 REST API 时,可以按容器、定义或分配进行汇总。With the REST API, summarization can be performed by container, definition, or assignment. 下面是使用 Azure Policy Insight 的按订阅汇总功能在订阅级别执行的汇总示例:Here is an example of summarization at the subscription level using Azure Policy Insight's Summarize For Subscription:

POST https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/summarize?api-version=2018-04-04

输出将汇总订阅。The output summarizes the subscription. 在以下示例输出中,汇总的符合性位于 value.results.nonCompliantResourcesvalue.results.nonCompliantPolicies 下面。In the example output below, 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. 层次结构中的每个策略对象提供一个可用于获取该级别的更多详细信息的 queryResultsUriEach policy object in the hierarchy provides a queryResultsUri that can be used to get additional detail at that level.

{
    "@odata.context": "https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#summary",
    "@odata.count": 1,
    "value": [{
        "@odata.id": null,
        "@odata.context": "https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#summary/$entity",
        "results": {
            "queryResultsUri": "https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2018-04-04&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=IsCompliant eq false",
            "nonCompliantResources": 15,
            "nonCompliantPolicies": 1
        },
        "policyAssignments": [{
            "policyAssignmentId": "/subscriptions/{subscriptionId}/resourcegroups/rg-tags/providers/microsoft.authorization/policyassignments/37ce239ae4304622914f0c77",
            "policySetDefinitionId": "",
            "results": {
                "queryResultsUri": "https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2018-04-04&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=IsCompliant eq false 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.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2018-04-04&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=IsCompliant eq false 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

在上面的示例中,value.policyAssignments.policyDefinitions.results.queryResultsUri 提供了一个示例 URI,用于特定策略定义的所有不符合资源。In the example above, value.policyAssignments.policyDefinitions.results.queryResultsUri provides a sample Uri for all non-compliant resources for a specific policy definition. 查看 $filter 值,IsCompliant 等于 (eq) false,PolicyAssignmentId 是针对策略定义,然后针对 PolicyDefinitionId 本身指定的。Looking at the $filter value, IsCompliant is equal (eq) to false, PolicyAssignmentId is specified for the policy definition, and then the PolicyDefinitionId itself. 在筛选器中包含 PolicyAssignmentId 的原因是,PolicyDefinitionId 可能在具有不同范围的多个策略或计划分配中存在。The reason for including the PolicyAssignmentId in the filter is because the PolicyDefinitionId could exist in several policy or initiative assignments with different scopes. 通过指定 PolicyAssignmentId 和 PolicyDefinitionId,可以明确指定想要查找的结果。By specifying both the PolicyAssignmentId and the PolicyDefinitionId, we can be explicit in the results we're looking for. 以前,我们使用了 latest 作为 PolicyStates,因此将起始截止时间范围自动设置成了过去 24 小时。Previously, for PolicyStates we used latest, which automatically sets a from and to time window of the last 24-hours.

https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2018-04-04&$from=2018-05-18 04:28:22Z&$to=2018-05-19 04:28:22Z&$filter=IsCompliant eq false 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 example response below has been 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.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest",
    "@odata.count": 15,
    "value": [{
        "@odata.id": null,
        "@odata.context": "https://management.chinacloudapi.cn/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": "",
        "isCompliant": false,
        "subscriptionId": "{subscriptionId}",
        "resourceType": "/Microsoft.Compute/virtualMachines",
        "resourceLocation": "chinaeast2",
        "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. 使用以下 URI 查看与订阅关联的最近策略事件。Use the following Uri to view recent policy events associated with the subscription.

https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/default/queryResults?api-version=2018-04-04

结果应如以下示例所示:Your results resemble the following example:

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

有关查询策略事件的详细信息,请参阅 Azure Policy 事件参考文章。For more information about querying policy events, see the Azure Policy Events reference article.

Azure PowerShellAzure PowerShell

适用于 Azure Policy 的 Azure PowerShell 模块在 PowerShell 库中以 Az.PolicyInsights 的形式提供。The Azure PowerShell module for Azure Policy is available on the PowerShell Gallery as Az.PolicyInsights. 使用 PowerShellGet,可以使用 Install-Module -Name Az.PolicyInsights 安装模块(请确保已安装了最新版 Azure PowerShell):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 CLI
Connect-AzAccount -EnvironmentName AzureChinaCloud

该模块拥有以下 cmdlet: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
IsCompliant                : False
SubscriptionId             : {subscriptionId}
ResourceType               : /Microsoft.Network/networkInterfaces
ResourceLocation           : chinaeast2
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
IsCompliant                : False
SubscriptionId             : {subscriptionId}
ResourceType               : /Microsoft.Network/virtualNetworks
ResourceLocation           : chinaeast2
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.

PS> Get-AzPolicyEvent -Filter "ResourceType eq '/Microsoft.Network/virtualNetworks'" -From '2018-05-19'

Timestamp                  : 5/19/2018 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
IsCompliant                : False
SubscriptionId             : {subscriptionId}
ResourceType               : /Microsoft.Network/virtualNetworks
ResourceLocation           : chinaeast2
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}

可以结合 Azure PowerShell cmdlet Get-AzADUser 使用 PrincipalOid 字段来获取特定的用户。The PrincipalOid field can be used to get a specific user with the Azure PowerShell cmdlet Get-AzADUser. 请将 {principalOid} 替换为在前一示例中获取的响应。Replace {principalOid} with the response you get from the previous example.

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

Azure Monitor 日志Azure Monitor logs

如果已将包含来自 Activity Log Analytics 解决方案AzureActivityLog Analytics 工作区绑定到订阅,则还可以使用简单的 Kusto 查询和 AzureActivity 表来查看评估周期中的不符合结果。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 cycle using simple Kusto queries and the AzureActivity table. 借助 Azure Monitor 日志中的详细信息,可对警报进行配置,以监视不符合情况。With details in Azure Monitor logs, alerts can be configured to watch for non-compliance.

使用 Azure Monitor 日志实现的 Azure Policy 符合性

后续步骤Next steps