您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

以编程方式创建策略和查看符合性数据Programmatically create policies and view compliance data

本文逐步讲解如何以编程方式创建和管理策略。This article walks you through programmatically creating and managing policies. Azure 策略定义不同的规则和效果对资源强制实施。Azure Policy definitions enforce different rules and effects over your resources. 强制实施可确保资源始终符合企业标准和服务级别协议。Enforcement makes sure that resources stay compliant with your corporate standards and service level agreements.

有关符合性的信息,请参阅获取符合性数据For information about compliance, see getting compliance data.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

必备组件Prerequisites

在开始之前,请确保满足以下先决条件:Before you begin, make sure that the following prerequisites are met:

  1. 安装 ARMClient(如果尚未安装)。If you haven't already, install the ARMClient. 该工具可将 HTTP 请求发送到基于 Azure 资源管理器的 API。It's a tool that sends HTTP requests to Azure Resource Manager-based APIs.

  2. 将 Azure PowerShell 模块更新到最新版本。Update your Azure PowerShell module to the latest version. 有关详细信息,请参阅安装 Azure PowerShell 模块See Install Azure PowerShell module for detailed information. 有关最新版本的详细信息,请参阅 Azure PowerShellFor more information about the latest version, see Azure PowerShell.

  3. 注册 Azure 策略见解资源提供程序使用 Azure PowerShell 来验证你的订阅,适用于资源提供程序。Register the Azure Policy Insights resource provider using Azure PowerShell to validate that your subscription works with the resource provider. 若要注册资源提供程序,必须具有为资源提供程序运行注册操作所需的权限。To register a resource provider, you must have permission to run the register action operation for the resource provider. 此操作包含在“参与者”和“所有者”角色中。This operation is included in the Contributor and Owner roles. 运行以下命令,注册资源提供程序:Run the following command to register the resource provider:

    Register-AzResourceProvider -ProviderNamespace 'Microsoft.PolicyInsights'
    

    有关注册和查看资源提供程序的详细信息,请参阅资源提供程序和类型For more information about registering and viewing resource providers, see Resource Providers and Types.

  4. 安装 Azure CLI(如果尚未安装)。If you haven't already, install Azure CLI. 可以通过在 Windows 上安装 Azure CLI 获取最新版本。You can get the latest version at Install Azure CLI on Windows.

创建并分配策略定义Create and assign a policy definition

更清晰地洞察资源的第一步是针对资源创建并分配策略。The first step toward better visibility of your resources is to create and assign policies over your resources. 下一步是了解如何以编程方式创建和分配策略。The next step is to learn how to programmatically create and assign a policy. 示例策略使用 PowerShell、Azure CLI 和 HTTP 请求来审核向所有公共网络开放的存储帐户。The example policy audits storage accounts that are open to all public networks using PowerShell, Azure CLI, and HTTP requests.

使用 PowerShell 创建并分配策略定义Create and assign a policy definition with PowerShell

  1. 使用以下 JSON 代码片段创建名为 AuditStorageAccounts.json 的 JSON 文件。Use the following JSON snippet to create a JSON file with the name AuditStorageAccounts.json.

    {
        "if": {
            "allOf": [{
                    "field": "type",
                    "equals": "Microsoft.Storage/storageAccounts"
                },
                {
                    "field": "Microsoft.Storage/storageAccounts/networkAcls.defaultAction",
                    "equals": "Allow"
                }
            ]
        },
        "then": {
            "effect": "audit"
        }
    }
    

    有关编写策略定义的详细信息,请参阅 Azure Policy 定义结构For more information about authoring a policy definition, see Azure Policy Definition Structure.

  2. 运行以下命令,使用 AuditStorageAccounts.json 文件创建策略定义。Run the following command to create a policy definition using the AuditStorageAccounts.json file.

    New-AzPolicyDefinition -Name 'AuditStorageAccounts' -DisplayName 'Audit Storage Accounts Open to Public Networks' -Policy 'AuditStorageAccounts.json'
    

    该命令创建名为 Audit Storage Accounts Open to Public Networks 的策略定义。The command creates a policy definition named Audit Storage Accounts Open to Public Networks. 有关可用的其他参数的详细信息,请参阅 New-AzPolicyDefinitionFor more information about other parameters that you can use, see New-AzPolicyDefinition.

    在没有位置参数的情况下调用时,New-AzPolicyDefinition 默认将策略定义保存在会话上下文的选定订阅中。When called without location parameters, New-AzPolicyDefinition defaults to saving the policy definition in the selected subscription of the sessions context. 若要将定义保存到其他位置,请使用以下参数:To save the definition to a different location, use the following parameters:

    • SubscriptionId - 保存到其他订阅。SubscriptionId - Save to a different subscription. 需要 GUID 值。Requires a GUID value.
    • ManagementGroupName - 保存到管理组。ManagementGroupName - Save to a management group. 需要_字符串_值。Requires a string value.
  3. 创建策略定义后,可运行以下命令创建策略分配:After you create your policy definition, you can create a policy assignment by running the following commands:

    $rg = Get-AzResourceGroup -Name 'ContosoRG'
    $Policy = Get-AzPolicyDefinition -Name 'AuditStorageAccounts'
    New-AzPolicyAssignment -Name 'AuditStorageAccounts' -PolicyDefinition $Policy -Scope $rg.ResourceId
    

    ContosoRG 替换为所需资源组的名称。Replace ContosoRG with the name of your intended resource group.

    New-AzPolicyAssignmentscope 参数适用于管理组、订阅、资源组或单个资源。The Scope parameter on New-AzPolicyAssignment works with management group, subscription, resource group, or a single resource. 该参数使用完整资源路径,它将返回 Get-AzResourceGroupResourceId 属性。The parameter uses a full resource path, which the ResourceId property on Get-AzResourceGroup returns. 每个容器的范围模式如下所示。The pattern for Scope for each container is as follows. {rName}{rgName}{subId}{mgName} 分别替换为你的资源名称、资源组名称、订阅 ID 和管理组名称。Replace {rName}, {rgName}, {subId}, and {mgName} with your resource name, resource group name, subscription ID, and management group name, respectively. {rType} 将替换为资源的资源类型,例如 VM 的 Microsoft.Compute/virtualMachines{rType} would be replaced with the resource type of the resource, such as Microsoft.Compute/virtualMachines for a VM.

    • 资源 - /subscriptions/{subID}/resourceGroups/{rgName}/providers/{rType}/{rName}Resource - /subscriptions/{subID}/resourceGroups/{rgName}/providers/{rType}/{rName}
    • 资源组 - /subscriptions/{subId}/resourceGroups/{rgName}Resource group - /subscriptions/{subId}/resourceGroups/{rgName}
    • 订阅 - /subscriptions/{subId}/Subscription - /subscriptions/{subId}/
    • 管理组 - /providers/Microsoft.Management/managementGroups/{mgName}Management group - /providers/Microsoft.Management/managementGroups/{mgName}

有关使用 Azure 资源管理器 PowerShell 模块管理资源策略的详细信息,请参阅 Az.ResourcesFor more information about managing resource policies using the Azure Resource Manager PowerShell module, see Az.Resources.

使用 ARMClient 创建并分配策略定义Create and assign a policy definition using ARMClient

使用以下过程创建策略定义。Use the following procedure to create a policy definition.

  1. 复制以下 JSON 代码片段以创建 JSON 文件。Copy the following JSON snippet to create a JSON file. 在下一步骤中将会调用该文件。You'll call the file in the next step.

    "properties": {
        "displayName": "Audit Storage Accounts Open to Public Networks",
        "policyType": "Custom",
        "mode": "Indexed",
        "description": "This policy ensures that storage accounts with exposure to Public Networks are audited.",
        "parameters": {},
        "policyRule": {
            "if": {
                "allOf": [{
                        "field": "type",
                        "equals": "Microsoft.Storage/storageAccounts"
                    },
                    {
                        "field": "Microsoft.Storage/storageAccounts/networkAcls.defaultAction",
                        "equals": "Allow"
                    }
                ]
            },
            "then": {
                "effect": "audit"
            }
        }
    }
    
  2. 使用以下调用之一创建策略定义:Create the policy definition using one of the following calls:

    # For defining a policy in a subscription
    armclient PUT "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/AuditStorageAccounts?api-version=2016-12-01" @<path to policy definition JSON file>
    
    # For defining a policy in a management group
    armclient PUT "/providers/Microsoft.Management/managementgroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/AuditStorageAccounts?api-version=2016-12-01" @<path to policy definition JSON file>
    

    将前面的 {subscriptionId} 替换为你的订阅的 ID,或将 {managementGroupId} 替换为你的管理组的 ID。Replace the preceding {subscriptionId} with the ID of your subscription or {managementGroupId} with the ID of your management group.

    有关查询的结构的详细信息,请参阅Azure 策略定义 – 创建或更新策略定义 – 创建或更新在管理组For more information about the structure of the query, see Azure Policy Definitions – Create or Update and Policy Definitions – Create or Update At Management Group

使用以下过程创建策略分配,并在资源组级别分配策略定义。Use the following procedure to create a policy assignment and assign the policy definition at the resource group level.

  1. 复制以下 JSON 代码片段以创建 JSON 策略分配文件。Copy the following JSON snippet to create a JSON policy assignment file. 请将 <> 符号中的示例信息替换为自己的值。Replace example information in <> symbols with your own values.

    {
        "properties": {
            "description": "This policy assignment makes sure that storage accounts with exposure to Public Networks are audited.",
            "displayName": "Audit Storage Accounts Open to Public Networks Assignment",
            "parameters": {},
            "policyDefinitionId": "/subscriptions/<subscriptionId>/providers/Microsoft.Authorization/policyDefinitions/Audit Storage Accounts Open to Public Networks",
            "scope": "/subscriptions/<subscriptionId>/resourceGroups/<resourceGroupName>"
        }
    }
    
  2. 使用以下调用创建策略分配:Create the policy assignment using the following call:

    armclient PUT "/subscriptions/<subscriptionID>/resourceGroups/<resourceGroupName>/providers/Microsoft.Authorization/policyAssignments/Audit Storage Accounts Open to Public Networks?api-version=2017-06-01-preview" @<path to Assignment JSON file>
    

    请将 <> 符号中的示例信息替换为自己的值。Replace example information in <> symbols with your own values.

    有关向 REST API 发出 HTTP 调用的详细信息,请参阅 Azure REST API 资源For more information about making HTTP calls to the REST API, see Azure REST API Resources.

使用 Azure CLI 创建并分配策略定义Create and assign a policy definition with Azure CLI

若要创建策略定义,请使用以下过程:To create a policy definition, use the following procedure:

  1. 复制以下 JSON 代码片段以创建 JSON 策略分配文件。Copy the following JSON snippet to create a JSON policy assignment file.

    {
        "if": {
            "allOf": [{
                    "field": "type",
                    "equals": "Microsoft.Storage/storageAccounts"
                },
                {
                    "field": "Microsoft.Storage/storageAccounts/networkAcls.defaultAction",
                    "equals": "Allow"
                }
            ]
        },
        "then": {
            "effect": "audit"
        }
    }
    

    有关编写策略定义的详细信息,请参阅 Azure Policy 定义结构For more information about authoring a policy definition, see Azure Policy Definition Structure.

  2. 运行以下命令创建策略定义:Run the following command to create a policy definition:

    az policy definition create --name 'audit-storage-accounts-open-to-public-networks' --display-name 'Audit Storage Accounts Open to Public Networks' --description 'This policy ensures that storage accounts with exposures to public networks are audited.' --rules '<path to json file>' --mode All
    

    该命令创建名为 Audit Storage Accounts Open to Public Networks 的策略定义。The command creates a policy definition named Audit Storage Accounts Open to Public Networks. 有关其他可用的参数的详细信息,请参阅 az policy definition createFor more information about other parameters that you can use, see az policy definition create.

    在没有位置参数的情况下调用时,az policy definition creation 默认将策略定义保存在会话上下文的选定订阅中。When called without location parameters, az policy definition creation defaults to saving the policy definition in the selected subscription of the sessions context. 若要将定义保存到其他位置,请使用以下参数:To save the definition to a different location, use the following parameters:

    • --subscription - 保存到其他订阅。--subscription - Save to a different subscription. 订阅 ID 需要 GUID 值,订阅名称需要_字符串_值。Requires a GUID value for the subscription ID or a string value for the subscription name.
    • --management-group - 保存到管理组。--management-group - Save to a management group. 需要_字符串_值。Requires a string value.
  3. 使用以下命令创建策略分配。Use the following command to create a policy assignment. 请将 <> 符号中的示例信息替换为自己的值。Replace example information in <> symbols with your own values.

    az policy assignment create --name '<name>' --scope '<scope>' --policy '<policy definition ID>'
    

    az policy assignment create--scope 参数适用于管理组、订阅、资源组或单个资源。The --scope parameter on az policy assignment create works with management group, subscription, resource group, or a single resource. 该参数使用完整资源路径。The parameter uses a full resource path. 每个容器的 --scope 模式如下所示。The pattern for --scope for each container is as follows. {rName}{rgName}{subId}{mgName} 分别替换为你的资源名称、资源组名称、订阅 ID 和管理组名称。Replace {rName}, {rgName}, {subId}, and {mgName} with your resource name, resource group name, subscription ID, and management group name, respectively. {rType} 将替换为资源的资源类型,例如 VM 的 Microsoft.Compute/virtualMachines{rType} would be replaced with the resource type of the resource, such as Microsoft.Compute/virtualMachines for a VM.

    • 资源 - /subscriptions/{subID}/resourceGroups/{rgName}/providers/{rType}/{rName}Resource - /subscriptions/{subID}/resourceGroups/{rgName}/providers/{rType}/{rName}
    • 资源组 - /subscriptions/{subID}/resourceGroups/{rgName}Resource group - /subscriptions/{subID}/resourceGroups/{rgName}
    • 订阅 - /subscriptions/{subID}Subscription - /subscriptions/{subID}
    • 管理组 - /providers/Microsoft.Management/managementGroups/{mgName}Management group - /providers/Microsoft.Management/managementGroups/{mgName}

可以使用以下命令使用 PowerShell 获取 Azure 策略定义 ID:You can get the Azure Policy Definition ID by using PowerShell with the following command:

az policy definition show --name 'Audit Storage Accounts with Open Public Networks'

创建的策略定义的策略定义 ID 应如以下示例所示:The policy definition ID for the policy definition that you created should resemble the following example:

"/subscription/<subscriptionId>/providers/Microsoft.Authorization/policyDefinitions/Audit Storage Accounts Open to Public Networks"

有关如何使用 Azure CLI 管理资源策略的详细信息,请参阅 Azure CLI 资源策略For more information about how you can manage resource policies with Azure CLI, see Azure CLI Resource Policies.

后续步骤Next steps

查看以下文章,详细了解本文中所示的命令和查询。Review the following articles for more information about the commands and queries in this article.