以程式設計方式建立原則Programmatically create policies

本文會逐步引導您以程式設計方式建立及管理原則。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.

PrerequisitesPrerequisites

開始之前,請確定您已符合下列必要條件:Before you begin, make sure that the following prerequisites are met:

  1. 請安裝 ARMClient (如果尚未安裝)。If you haven't already, install the ARMClient. 此工具會將 HTTP 要求傳送至以 Azure Resource Manager 為基礎的 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 PowerShell 來註冊 Azure 原則見解資源提供者,以驗證您的訂用帳戶可與資源提供者搭配使用。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 原則定義結構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'
    

    此命令會建立名為_對公用網路開放的稽核儲存體帳戶_的原則定義。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
    

    以您想要的資源群組名稱取代 ContosoRGReplace ContosoRG with the name of your intended resource group.

    New-AzPolicyAssignment 上的 Scope 參數可與管理群組、訂用帳戶、資源群組或單一資源搭配使用。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. 以下是每個容器的 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}

如需使用 Resource Manager PowerShell 模組來管理資源原則的詳細資訊,請參閱Az. ResourcesFor more information about managing resource policies using the 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=2019-09-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=2019-09-01" @<path to policy definition JSON file>
    

    使用您訂用帳戶的 ID 來取代上述 {subscriptionId},或使用管理群組的 ID 來取代 {managementGroupId}。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=2019-09-01" @<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 原則定義結構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
    

    此命令會建立名為_對公用網路開放的稽核儲存體帳戶_的原則定義。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. 需要一個 GUID 值來用於訂用帳戶 ID,或需要一個「字串」值來用於訂用帳戶名稱。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 原則定義識別碼: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'

針對您所建立的原則定義,其原則定義識別碼應該類似下列範例: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.