快速入门:使用 Python 创建策略分配以识别不合规的资源Quickstart: Create a policy assignment to identify non-compliant resources using Python

若要了解 Azure 中的符合性,第一步是确定资源的状态。The first step in understanding compliance in Azure is to identify the status of your resources. 在本快速入门中,我们将创建策略分配,以识别未使用托管磁盘的虚拟机。In this quickstart, you create a policy assignment to identify virtual machines that aren't using managed disks. 完成后,我们便可以识别不合规的虚拟机。 When complete, you'll identify virtual machines that are non-compliant.

Python 库用于从命令行或脚本管理 Azure 资源。The Python library is used to manage Azure resources from the command line or in scripts. 本指南介绍如何使用 Python 库来创建策略分配。This guide explains how to use Python library to create a policy assignment.

先决条件Prerequisites

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

启动 Azure Cloud ShellLaunch Azure Cloud Shell

Azure Cloud Shell 是可直接在 Azure 门户中运行的免费 Bash shell。The Azure Cloud Shell is a free Bash shell that you can run directly within the Azure portal. 它预安装有 Azure CLI 并将其配置与你的帐户一起使用。It has the Azure CLI preinstalled and configured to use with your account. 单击 Azure 门户右上角菜单上的“Cloud Shell”按钮。Click the Cloud Shell button on the menu in the upper-right of the Azure portal.

Cloud ShellCloud Shell

该按钮会启动交互式 shell,可以使用它运行本主题中的所有步骤:The button launches an interactive shell that you can use to run all of the steps in this topic:

屏幕截图,显示门户中的 Cloud Shell 窗口Screenshot showing the Cloud Shell window in the portal

添加 Policy 库Add the Policy library

若要使 Python 能够与 Azure Policy 配合使用,必须添加库。To enable Python to work with Azure Policy, the library must be added. 此库适用于可使用 Python 的任何情况,包括 Windows 10 上的 bash 或本地安装的 bash。This library works wherever Python can be used, including bash on Windows 10 or locally installed.

  1. 请确保安装最新的 Python(至少为 3.8)。Check that the latest Python is installed (at least 3.8). 如果尚未安装,请在 Python.org 下载。If it isn't yet installed, download it at Python.org.

  2. 请确保安装最新的 Azure CLI(至少为 2.5.1)。Check that the latest Azure CLI is installed (at least 2.5.1). 如果尚未安装,请参阅安装 Azure CLIIf it isn't yet installed, see Install the Azure CLI.

    备注

    在下面的示例中需要使用 Azure CLI,这样 Python 才能使用基于 CLI 的身份验证。Azure CLI is required to enable Python to use the CLI-based authentication in the following examples. 有关其他选项的信息,请参阅使用适用于 Python 的 Azure 管理库进行身份验证For information about other options, see Authenticate using the Azure management libraries for Python.

  3. 通过 Azure CLI 进行身份验证。Authenticate through Azure CLI.

    az login
    
  4. 在所选的 Python 环境中,安装 Azure Resource Graph 所需的库:In your Python environment of choice, install the required libraries for Azure Resource Graph:

    # Add the Python library for Python
    pip install azure-mgmt-policyinsights
    
    # Add the Resources library for Python
    pip install azure-mgmt-resource
    
    # Add the CLI Core library for Python for authentication (development only!)
    pip install azure-cli-core
    

    备注

    如果已为所有用户安装了 Python,则必须从提升的控制台运行这些命令。If Python is installed for all users, these commands must be run from an elevated console.

  5. 验证是否已安装这些库。Validate that the libraries have been installed. azure-mgmt-policyinsights 应为 0.5.0 或更高版本,azure-mgmt-resource 应为 9.0.0 版或更高版本,azure-cli-core 应为 2.5.0 或更高版本 。azure-mgmt-policyinsights should be 0.5.0 or higher, azure-mgmt-resource should be 9.0.0 or higher, and azure-cli-core should be 2.5.0 or higher.

    # Check each installed library
    pip show azure-mgmt-policyinsights azure-mgmt-resource azure-cli-core
    

创建策略分配Create a policy assignment

本快速入门将创建一个策略分配,并分配“审核未使用托管磁盘的 VM”(06a78e20-9358-41c9-923c-fb736d382a4d) 定义。In this quickstart, you create a policy assignment and assign the Audit VMs that do not use managed disks (06a78e20-9358-41c9-923c-fb736d382a4d) definition. 此策略定义可识别不符合策略定义中设置的条件的资源。This policy definition identifies resources that aren't compliant to the conditions set in the policy definition.

运行以下代码创建新的策略分配:Run the following code to create a new policy assignment:

# Import specific methods and models from other libraries
from azure.common.credentials import get_azure_cli_credentials
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.resource.policy import PolicyClient
from azure.mgmt.resource.policy.models import PolicyAssignment

# Get your credentials from Azure CLI (development only!) and get your subscription list
policyClient = get_client_from_cli_profile(PolicyClient)

# Create details for the assignment
policyAssignmentDetails = PolicyAssignment(display_name="Audit VMs without managed disks Assignment", policy_definition_id="/providers/Microsoft.Authorization/policyDefinitions/06a78e20-9358-41c9-923c-fb736d382a4d", scope="{scope}", description="Shows all virtual machines not using managed disks")

# Create new policy assignment
policyAssignment = policyClient.policy_assignments.create("{scope}", "audit-vm-manageddisks", policyAssignmentDetails)

# Show results
print(policyAssignment)

上述命令使用以下信息:The preceding commands use the following information:

分配详细信息:Assignment details:

  • display_name - 策略分配的显示名称。display_name - Display name for the policy assignment. 本例使用了“审核未使用托管磁盘分配的虚拟机” 。In this case, you're using Audit VMs without managed disks Assignment.
  • policy_definition_id - 策略定义路径,用作创建分配的依据。policy_definition_id – The policy definition path, based on which you're using to create the assignment. 在本例中,它为策略定义“审核未使用托管磁盘的 VM”的 ID 。In this case, it's the ID of policy definition Audit VMs that do not use managed disks. 在此示例中,策略定义是内置的,路径不包括管理组或订阅信息。In this example, the policy definition is a built-in and the path doesn't include management group or subscription information.
  • 作用域 - 作用域确定要对哪些资源或资源分组实施策略分配。scope - A scope determines what resources or grouping of resources the policy assignment gets enforced on. 它的范围可以从管理组到单个资源。It could range from a management group to an individual resource. 请确保将 {scope} 替换为以下某个模式:Be sure to replace {scope} with one of the following patterns:
    • 管理组:/providers/Microsoft.Management/managementGroups/{managementGroup}Management group: /providers/Microsoft.Management/managementGroups/{managementGroup}
    • 订阅:/subscriptions/{subscriptionId}Subscription: /subscriptions/{subscriptionId}
    • 资源组:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}Resource group: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
    • 资源:/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]Resource: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]
  • 说明 - 有关策略用途或将其分配到此范围的原因的更深入说明。description - A deeper explanation of what the policy does or why it's assigned to this scope.

分配创建:Assignment creation:

  • 作用域 - 此作用域确定保存策略分配的位置。Scope - This scope determines where the policy assignment gets saved. 分配详细信息中设置的作用域必须存在于此作用域内。The scope set in the assignment details must exist within this scope.
  • 名称 - 分配的实际名称。Name - The actual name of the assignment. 对于此示例,使用 audit-vm-manageddisksFor this example, audit-vm-manageddisks was used.
  • 策略分配 - 在上一步中创建的 Python PolicyAssignment 对象。Policy assignment - The Python PolicyAssignment object created in the previous step.

你现已准备好识别不合规的资源,了解环境的符合性状态。You're now ready to identify non-compliant resources to understand the compliance state of your environment.

识别不合规的资源Identify non-compliant resources

使用以下信息来识别不符合所创建的策略分配的资源。Use the following information to identify resources that aren't compliant with the policy assignment you created. 运行以下代码:Run the following code:

# Import specific methods and models from other libraries
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.policyinsights._policy_insights_client import PolicyInsightsClient
from azure.mgmt.policyinsights.models import QueryOptions

# Get your credentials from Azure CLI (development only!) and get your subscription list
policyInsightsClient = get_client_from_cli_profile(PolicyInsightsClient)

# Set the query options
queryOptions = QueryOptions(filter="IsCompliant eq false and PolicyAssignmentId eq 'audit-vm-manageddisks'",apply="groupby((ResourceId))")

# Fetch 'latest' results for the subscription
results = policyInsightsClient.policy_states.list_query_results_for_subscription(policy_states_resource="latest", subscription_id="{subscriptionId}", query_options=queryOptions)

# Show results
print(results)

{subscriptionId} 替换为要查看此策略分配的符合性结果的订阅。Replace {subscriptionId} with the subscription you want to see the compliance results for this policy assignment. 有关其他作用域和汇总数据的方法的列表,请参阅策略状态方法For a list of other scopes and ways to summarize the data, see Policy State methods.

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

{
    'additional_properties': {
        '@odata.nextLink': None
    },
    'odatacontext': 'https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/$metadata#latest',
    'odatacount': 12,
    'value': [{data}]
}

结果与 Azure 门户视图中策略分配的“资源符合性” 选项卡中显示的内容相匹配。The results match what you see in the Resource compliance tab of a policy assignment in the Azure portal view.

清理资源Clean up resources

要删除创建的分配,请使用以下命令:To remove the assignment created, use the following command:

# Import specific methods and models from other libraries
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.resource.policy import PolicyClient

# Get your credentials from Azure CLI (development only!) and get your subscription list
policyClient = get_client_from_cli_profile(PolicyClient)

# Delete the policy assignment
policyAssignment = policyClient.policy_assignments.delete("{scope}", "audit-vm-manageddisks")

# Show results
print(policyAssignment)

{scope} 替换为创建策略分配时使用的相同作用域。Replace {scope} with the same scope you used to create the policy assignment.

后续步骤Next steps

本快速入门已分配一个策略定义用于识别 Azure 环境中的不合规资源。In this quickstart, you assigned a policy definition to identify non-compliant resources in your Azure environment.

要了解有关分配策略定义以验证新资源是否符合要求的详细信息,请继续以下教程:To learn more about assigning policy definitions to validate that new resources are compliant, continue to the tutorial for: