示例 - 在资源组强制执行标记及其值Sample - Enforce tag and its value on resource groups

此策略要求资源组有标记和值。This policy requires a tag and value on a resource group. 由你指定标记名称和值。You specify the required tag name and value.

可以使用以下方法部署此示例策略:You can deploy this sample policy using:

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

示例策略Sample policy

策略定义Policy definition

结构完整的 JSON 策略定义,可以通过 REST API、“部署到 Azure”按钮以及手动在门户中使用。The complete composed JSON policy definition, used by the REST API, 'Deploy to Azure' buttons, and manually in the portal.

{
   "properties": {
      "displayName": "Enforce tag and its value on resource groups",
      "description": "Enforces a required tag and its value on resource groups.",
      "mode": "All",
      "parameters": {
         "tagName": {
            "type": "String",
            "metadata": {
               "description": "Name of the tag, such as costCenter"
            }
         },
         "tagValue": {
            "type": "String",
            "metadata": {
               "description": "Value of the tag, such as headquarter"
            }
         }
      },
      "policyRule": {
         "if": {
            "allOf": [
               {
                  "field": "type",
                  "equals": "Microsoft.Resources/subscriptions/resourceGroups"
               },
               {
                  "not": {
                     "field": "[concat('tags[',parameters('tagName'), ']')]",
                     "equals": "[parameters('tagValue')]"
                  }
               }
            ]
         },
         "then": {
            "effect": "deny"
         }
      }
   }
}

Note

如果手动在门户中创建策略,请使用上面的 properties.parametersproperties.policyRule 部分。If manually creating a policy in the portal, use the properties.parameters and properties.policyRule portions of the above. 使用大括号 {} 将这两部分括在一起,使其成为有效的 JSON。Wrap the two sections together with curly braces {} to make it valid JSON.

策略规则Policy rules

定义了策略规则的 JSON,由 Azure CLI 和 Azure PowerShell 使用。The JSON defining the rules of the policy, used by Azure CLI and Azure PowerShell.

{
   "if": {
      "allOf": [
         {
            "field": "type",
            "equals": "Microsoft.Resources/subscriptions/resourceGroups"
         },
         {
            "not": {
               "field": "[concat('tags[',parameters('tagName'), ']')]",
               "equals": "[parameters('tagValue')]"
            }
         }
      ]
   },
   "then": {
      "effect": "deny"
   }
}

策略参数Policy parameters

定义了策略参数的 JSON,由 Azure CLI 和 Azure PowerShell 使用。The JSON defining the policy parameters, used by Azure CLI and Azure PowerShell.

{
    "tagName": {
        "type": "String",
        "metadata": {
            "description": "Name of the tag, such as costCenter"
        }
    },
    "tagValue": {
        "type": "String",
        "metadata": {
            "description": "Value of the tag, such as headquarter"
        }
    }
}
NameName 类型Type 字段Field 说明Description
tagNametagName StringString 标记tags 标记的名称,如 costCenterName of the tag, such as costCenter
tagValuetagValue StringString 标记tags 标记的值,如 headquarterValue of the tag, such as headquarter

通过 PowerShell 或 Azure CLI 创建分配时,可以使用 -PolicyParameter (PowerShell) 或 --params (Azure CLI) 通过字符串或文件将参数值传递为 JSON。When creating an assignment via PowerShell or Azure CLI, the parameter values can be passed as JSON in either a string or via a file using -PolicyParameter (PowerShell) or --params (Azure CLI). PowerShell 还支持 -PolicyParameterObject,这要求向该 cmdlet 传递一个 Name/Value 哈希表,其中,Name 是参数名称,Value 是在赋值期间传递的单个值或值数组。PowerShell also supports -PolicyParameterObject which requires passing the cmdlet a Name/Value hashtable where Name is the parameter name and Value is the single value or array of values being passed during assignment.

在此示例参数中,定义的 tagNamecostCentertagValueheadquarterIn this example parameter, a tagName of costCenter and tagValue of headquarter is defined.

{
    "tagName": {
        "value": "costCenter"
    },
    "tagValue": {
        "value": "headquarter"
    }
}

Azure 门户Azure portal

将策略示例部署到 AzureDeploy the Policy sample to Azure

Azure PowerShellAzure PowerShell

本示例需要 Azure PowerShell。This sample requires Azure PowerShell. 运行 Get-Module -ListAvailable Az 即可查找版本。Run Get-Module -ListAvailable Az to find the version. 如果需要进行安装或升级,请参阅安装 Azure PowerShell 模块If you need to install or upgrade, see Install Azure PowerShell module.

运行 Connect-AzAccount -Environment AzureChinaCloud,创建与 Azure 的连接。Run Connect-AzAccount -Environment AzureChinaCloud to create a connection with Azure.

使用 Azure PowerShell 部署Deploy with Azure PowerShell

# Create the Policy Definition (Subscription scope)
$definition = New-AzPolicyDefinition -Name 'enforce-resourceGroup-tags' -DisplayName 'Enforce tag and its value on resource groups' -description 'Enforces a required tag and its value on resource groups.' -Policy 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/ResourceGroup/enforce-resourceGroup-tags/azurepolicy.rules.json' -Parameter 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/ResourceGroup/enforce-resourceGroup-tags/azurepolicy.parameters.json' -Mode All

# Set the scope to a resource group; may also be a resource, subscription, or management group
$scope = Get-AzResourceGroup -Name 'YourResourceGroup'

# Set the Policy Parameter (JSON format)
$policyParam = '{ "tagName": { "value": "costCenter" }, "tagValue": { "value": "headquarter" } }'

# Create the Policy Assignment
$assignment = New-AzPolicyAssignment -Name 'enforce-resourceGroup-tags-assignment' -Scope $scope.ResourceId -PolicyDefinition $definition -PolicyParameter $policyParam

使用 Azure PowerShell 删除Remove with Azure PowerShell

运行以下命令来删除以前的分配和定义:Run the following commands to remove the previous assignment and definition:

# Remove the Policy Assignment
Remove-AzPolicyAssignment -Id $assignment.ResourceId

# Remove the Policy Definition
Remove-AzPolicyDefinition -Id $definition.ResourceId

Azure PowerShell 说明Azure PowerShell explanation

部署和删除脚本使用以下命令。The deploy and remove scripts use the following commands. 下表中的每条命令均链接到特定于命令的文档:Each command in the following table links to command-specific documentation:

命令Command 注释Notes
New-AzPolicyDefinitionNew-AzPolicyDefinition 创建新的 Azure Policy 定义。Creates a new Azure Policy definition.
Get-AzResourceGroupGet-AzResourceGroup 获取单个资源组。Gets a single resource group.
New-AzPolicyAssignmentNew-AzPolicyAssignment 创建新的 Azure Policy 分配。Creates a new Azure Policy assignment. 在此示例中,我们向其提供了一个定义,但它也可以接受计划。In this example, we provide it a definition, but it can also take an initiative.
Remove-AzPolicyAssignmentRemove-AzPolicyAssignment 删除现有的 Azure Policy 分配。Removes an existing Azure Policy assignment.
Remove-AzPolicyDefinitionRemove-AzPolicyDefinition 删除现有的 Azure Policy 定义。Removes an existing Azure Policy definition.

Azure CLIAzure CLI

若要运行此示例,请确保已安装最新版本的 Azure CLITo run this sample, make sure you have installed the latest version of the Azure CLI. 若要开始,请运行 az login 以创建与 Azure 的连接。To start, run az login to create a connection with Azure.

此示例在 Bash shell 中正常工作。This sample works in a Bash shell. 有关在 Windows 客户端上运行 Azure CLI 脚本的选项,请参阅在 Windows 上安装 Azure CLIFor options on running Azure CLI scripts on Windows client, see Install the Azure CLI on Windows.

使用 Azure CLI 进行部署Deploy with Azure CLI

# Create the Policy Definition (Subscription scope)
definition=$(az policy definition create --name 'enforce-resourceGroup-tags' --display-name 'Enforce tag and its value on resource groups' --description 'Enforces a required tag and its value on resource groups.' --rules 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/ResourceGroup/enforce-resourceGroup-tags/azurepolicy.rules.json' --params 'https://raw.githubusercontent.com/Azure/azure-policy/master/samples/ResourceGroup/enforce-resourceGroup-tags/azurepolicy.parameters.json' --mode All)

# Set the scope to a resource group; may also be a resource, subscription, or management group
scope=$(az group show --name 'YourResourceGroup')

# Set the Policy Parameter (JSON format)
policyParam='{ "tagName": { "value": "costCenter" }, "tagValue": { "value": "headquarter" } }'

# Create the Policy Assignment
assignment=$(
az policy assignment create --name 'enforce-resourceGroup-tags-assignment' --display-name 'Enforce tag and its value on resource groups'  --scope `echo $scope | jq '.id' -r` --policy `echo $definition | jq '.name' -r` --params "$policyparam")

使用 Azure CLI 进行删除Remove with Azure CLI

运行以下命令来删除以前的分配和定义:Run the following commands to remove the previous assignment and definition:

# Remove the Policy Assignment
az policy assignment delete --name `echo $assignment | jq '.name' -r`

# Remove the Policy Definition
az policy definition delete --name `echo $definition | jq '.name' -r`

Azure CLI 说明Azure CLI explanation

命令Command 注释Notes
az policy definition createaz policy definition create 创建新的 Azure Policy 定义。Creates a new Azure Policy definition.
az group showaz group show 获取单个资源组。Gets a single resource group.
az policy assignment createaz policy assignment create 创建新的 Azure Policy 分配。Creates a new Azure Policy assignment. 在此示例中,我们向其提供了一个定义,但它也可以接受计划。In this example, we provide it a definition, but it can also take an initiative.
az policy assignment deleteaz policy assignment delete 删除现有的 Azure Policy 分配。Removes an existing Azure Policy assignment.
az policy definition deleteaz policy definition delete 删除现有的 Azure Policy 定义。Removes an existing Azure Policy definition.

有多个工具可以用来与资源管理器 REST API 进行交互,例如 ARMClient 或 PowerShell。There are several tools that can be used to interact with the Resource Manager REST API such as ARMClient or PowerShell. 可以在策略定义结构别名部分中找到通过 PowerShell 调用 REST API 的示例。An example of calling REST API from PowerShell can be found in the Aliases section of Policy definition structure.

REST APIREST API

使用 REST API 进行部署Deploy with REST API

  • 创建策略定义(订阅范围)。Create the Policy Definition (Subscription scope). 策略定义 JSON 用于请求正文。Use the policy definition JSON for the Request Body.

    PUT https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/enforce-resourceGroup-tags?api-version=2016-12-01
    
  • 创建策略分配(资源组范围)Create the Policy Assignment (Resource Group scope)

    PUT https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/resourceGroups/YourResourceGroup/providers/Microsoft.Authorization/policyAssignments/enforce-resourceGroup-tags-assignment?api-version=2017-06-01-preview
    

    将以下 JSON 示例用于请求正文:Use the following JSON example for the Request Body:

  {
      "properties": {
          "displayName": "Enforce tag and its value Assignment",
          "policyDefinitionId": "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/enforce-resourceGroup-tags",
          "parameters": {
              "tagName": {
                  "value": "costCenter"
              },
              "tagValue": {
                  "value": "headquarter"
              }
          }
      }
  }

使用 REST API 进行删除Remove with REST API

  • 删除策略分配Remove the Policy Assignment

    DELETE https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments/enforce-resourceGroup-tags-assignment?api-version=2017-06-01-preview
    
  • 删除策略定义Remove the Policy Definition

    DELETE https://management.chinacloudapi.cn/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/enforce-resourceGroup-tags?api-version=2016-12-01
    

REST API 说明REST API explanation

服务Service Group 操作Operation 注释Notes
资源管理Resource Management 策略定义Policy Definitions 创建Create 在订阅中创建新的 Azure Policy 定义。Creates a new Azure Policy definition at a subscription. 替换项:在管理组中创建Alternative: Create at management group
资源管理Resource Management 策略分配Policy Assignments 创建Create 创建新的 Azure Policy 分配。Creates a new Azure Policy assignment. 在此示例中,我们向其提供了一个定义,但它也可以接受计划。In this example, we provide it a definition, but it can also take an initiative.
资源管理Resource Management 策略分配Policy Assignments 删除Delete 删除现有的 Azure Policy 分配。Removes an existing Azure Policy assignment.
资源管理Resource Management 策略定义Policy Definitions 删除Delete 删除现有的 Azure Policy 定义。Removes an existing Azure Policy definition. 替换项:在管理组中删除Alternative: Delete at management group

后续步骤Next steps