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

使用标记整理 Azure 资源Use tags to organize your Azure resources

可以将标记应用于 Azure 资源,从而将元数据按逻辑组织到分类中。You apply tags to your Azure resources giving metadata to logically organize them into a taxonomy. 每个标记由名称和值对组成。Each tag consists of a name and a value pair. 例如,可以对生产中的所有资源应用名称“Environment”和值“Production”。For example, you can apply the name "Environment" and the value "Production" to all the resources in production.

应用标记以后,即可使用该标记名称和值检索订阅中的所有资源。After you apply tags, you can retrieve all the resources in your subscription with that tag name and value. 使用标记可以从不同资源组中检索相关资源。Tags enable you to retrieve related resources from different resource groups. 需要为计费或管理目的组织资源时,此方法十分有用。This approach is helpful when you need to organize resources for billing or management.

除了自动标记策略之外,你的分类还应考虑自助式元数据标记策略,以减轻用户负担并提高准确性。Your taxonomy should consider a self-service metadata tagging strategy in addition to an auto-tagging strategy to reduce the burden on users and increase accuracy.

以下限制适用于标记:The following limitations apply to tags:

  • 每个资源或资源组最多可以有 15 个标记名称值对。Each resource or resource group can have a maximum of 15 tag name/value pairs. 此限制仅适用于直接应用到资源组或资源的标记。This limitation applies only to tags directly applied to the resource group or resource. 资源组可以包含多个资源,这些资源每个都有 15 个标记名称值对。A resource group can contain many resources that each have 15 tag name/value pairs. 如果有超过 15 个需要与资源关联的值,请将 JSON 字符串用于标记值。If you have more than 15 values that you need to associate with a resource, use a JSON string for the tag value. JSON 字符串可以包含多个应用于单个标记名称的值。The JSON string can contain many values that are applied to a single tag name. 本文介绍了一个将 JSON 字符串分配给标记的示例。This article shows an example of assigning a JSON string to the tag.
  • 标记名称不能超过 512 个字符,标记值不能超过 256 个字符。The tag name is limited to 512 characters, and the tag value is limited to 256 characters. 对于存储帐户,标记名称不能超过 128 个字符,标记值不能超过 256 个字符。For storage accounts, the tag name is limited to 128 characters, and the tag value is limited to 256 characters.
  • 对于所有标记名称和值,虚拟机限制总共为 2048 个字符。Virtual Machines are limited to a total of 2048 characters for all tag names and values.
  • 应用于资源组的标记不会被该资源组中的资源继承。Tags applied to the resource group are not inherited by the resources in that resource group.
  • 不能将标记应用到云服务等经典资源。Tags can't be applied to classic resources such as Cloud Services.
  • 标记名称不能包含以下字符:<>%&\?/Tag names can't contain these characters: <, >, %, &, \, ?, /

要向资源应用标记,用户必须具有对该资源类型的写权限。To apply tags to resources, the user must have write access to that resource type. 要将标记应用于所有资源类型,请使用参与者角色。To apply tags to all resource types, use the Contributor role. 要将标记仅应用于一种资源类型,请使用该资源的参与者角色。To apply tags to only one resource type, use the contributor role for that resource. 例如,要将标记应用到虚拟机,请使用虚拟机参与者For example, to apply tags to virtual machines, use the Virtual Machine Contributor.

备注

本文介绍如何删除设备或服务中的个人数据,并且可为 GDPR 下的任务提供支持。This article provides steps for how to delete personal data from the device or service and can be used to support your obligations under the GDPR. 如需关于 GDPR 的常规信息,请参阅服务信任门户的 GDPR 部分If you’re looking for general info about GDPR, see the GDPR section of the Service Trust portal.

PowerShellPowerShell

本文中的示例需要版本 6.0 或更高版本的 Azure PowerShell。The examples in this article require version 6.0 or later of Azure PowerShell. 如果没有版本 6.0 或更高版本,请更新版本If you do not have version 6.0 or later, update your version.

若要查看资源组的现有标记,请使用:To see the existing tags for a resource group, use:

(Get-AzureRmResourceGroup -Name examplegroup).Tags

该脚本返回以下格式:That script returns the following format:

Name                           Value
----                           -----
Dept                           IT
Environment                    Test

若要查看具有指定资源 ID 的资源的现有标记,请使用:To see the existing tags for a resource that has a specified resource ID, use:

(Get-AzureRmResource -ResourceId /subscriptions/<subscription-id>/resourceGroups/<rg-name>/providers/Microsoft.Storage/storageAccounts/<storage-name>).Tags

或者,若要查看具有指定名称和资源组的资源的现有标记,请使用:Or, to see the existing tags for a resource that has a specified name and resource group, use:

(Get-AzureRmResource -ResourceName examplevnet -ResourceGroupName examplegroup).Tags

若要获取具有特定标记的资源组,请使用:To get resource groups that have a specific tag, use:

(Get-AzureRmResourceGroup -Tag @{ Dept="Finance" }).ResourceGroupName

若要获取具有特定标记的资源,请使用:To get resources that have a specific tag, use:

(Get-AzureRmResource -Tag @{ Dept="Finance"}).Name

若要获取具有特定标记名称的资源,请使用:To get resources that have a specific tag name, use:

(Get-AzureRmResource -TagName Dept).Name

每次将标记应用到某个资源或资源组时,都会覆盖该资源或资源组中的现有标记。Every time you apply tags to a resource or a resource group, you overwrite the existing tags on that resource or resource group. 因此,必须根据该资源或资源组是否包含现有标记来使用不同的方法。Therefore, you must use a different approach based on whether the resource or resource group has existing tags.

若要将标记添加到不包含现有标记的资源组,请使用:To add tags to a resource group without existing tags, use:

Set-AzureRmResourceGroup -Name examplegroup -Tag @{ Dept="IT"; Environment="Test" }

若要将标记添加到包含现有标记的资源组,请检索现有标记,添加新标记,然后重新应用标记:To add tags to a resource group that has existing tags, retrieve the existing tags, add the new tag, and reapply the tags:

$tags = (Get-AzureRmResourceGroup -Name examplegroup).Tags
$tags.Add("Status", "Approved")
Set-AzureRmResourceGroup -Tag $tags -Name examplegroup

若要将标记添加到不包含现有标记的资源,请使用:To add tags to a resource without existing tags, use:

$r = Get-AzureRmResource -ResourceName examplevnet -ResourceGroupName examplegroup
Set-AzureRmResource -Tag @{ Dept="IT"; Environment="Test" } -ResourceId $r.ResourceId -Force

若要将标记添加到包含现有标记的资源,请使用:To add tags to a resource that has existing tags, use:

$r = Get-AzureRmResource -ResourceName examplevnet -ResourceGroupName examplegroup
$r.Tags.Add("Status", "Approved") 
Set-AzureRmResource -Tag $r.Tags -ResourceId $r.ResourceId -Force

要将资源组中的所有标记应用于其资源,并且不保留资源上的现有标记,请使用以下脚本:To apply all tags from a resource group to its resources, and not retain existing tags on the resources, use the following script:

$groups = Get-AzureRmResourceGroup
foreach ($g in $groups)
{
    Get-AzureRmResource -ResourceGroupName $g.ResourceGroupName | ForEach-Object {Set-AzureRmResource -ResourceId $_.ResourceId -Tag $g.Tags -Force }
}

要将资源组中的所有标记应用于其资源,并且保留资源上不重复的现有标记,请使用以下脚本:To apply all tags from a resource group to its resources, and retain existing tags on resources that are not duplicates, use the following script:

$group = Get-AzureRmResourceGroup "examplegroup"
if ($group.Tags -ne $null) {
    $resources = Get-AzureRmResource -ResourceGroupName $group.ResourceGroupName
    foreach ($r in $resources)
    {
        $resourcetags = (Get-AzureRmResource -ResourceId $r.ResourceId).Tags
        if ($resourcetags)
        {
            foreach ($key in $group.Tags.Keys)
            {
                if (-not($resourcetags.ContainsKey($key)))
                {
                    $resourcetags.Add($key, $group.Tags[$key])
                }
            }
            Set-AzureRmResource -Tag $resourcetags -ResourceId $r.ResourceId -Force
        }
        else
        {
            Set-AzureRmResource -Tag $group.Tags -ResourceId $r.ResourceId -Force
        }
    }
}

若要删除所有标记,请传递一个空哈希表:To remove all tags, pass an empty hash table:

Set-AzureRmResourceGroup -Tag @{} -Name examplegroup

Azure CLIAzure CLI

若要查看资源组的现有标记,请使用:To see the existing tags for a resource group, use:

az group show -n examplegroup --query tags

该脚本返回以下格式:That script returns the following format:

{
  "Dept"        : "IT",
  "Environment" : "Test"
}

若要查看具有指定名称、类型和资源组的资源的现有标记,请使用:Or, to see the existing tags for a resource that has a specified name, type, and resource group, use:

az resource show -n examplevnet -g examplegroup --resource-type "Microsoft.Network/virtualNetworks" --query tags

循环访问资源集合时,可能想要按资源 ID 显示资源。When looping through a collection of resources, you might want to show the resource by resource ID. 本文稍后介绍一个完整的示例。A complete example is shown later in this article. 若要查看具有指定资源 ID 的资源的现有标记,请使用:To see the existing tags for a resource that has a specified resource ID, use:

az resource show --id <resource-id> --query tags

若要获取具有特定标记的资源组,请使用 az group listTo get resource groups that have a specific tag, use az group list:

az group list --tag Dept=IT

若要获取具有特定标记和值的所有资源,请使用 az resource listTo get all the resources that have a particular tag and value, use az resource list:

az resource list --tag Dept=Finance

每次将标记应用到某个资源或资源组时,都会覆盖该资源或资源组中的现有标记。Every time you apply tags to a resource or a resource group, you overwrite the existing tags on that resource or resource group. 因此,必须根据该资源或资源组是否包含现有标记来使用不同的方法。Therefore, you must use a different approach based on whether the resource or resource group has existing tags.

若要将标记添加到不包含现有标记的资源组,请使用:To add tags to a resource group without existing tags, use:

az group update -n examplegroup --set tags.Environment=Test tags.Dept=IT

若要将标记添加到不包含现有标记的资源,请使用:To add tags to a resource without existing tags, use:

az resource tag --tags Dept=IT Environment=Test -g examplegroup -n examplevnet --resource-type "Microsoft.Network/virtualNetworks"

若要将标记添加到已带标记的资源,请检索现有标记,重新格式化该值,然后重新应用现有标记和新标记:To add tags to a resource that already has tags, retrieve the existing tags, reformat that value, and reapply the existing and new tags:

jsonrtag=$(az resource show -g examplegroup -n examplevnet --resource-type "Microsoft.Network/virtualNetworks" --query tags)
rt=$(echo $jsonrtag | tr -d '"{},' | sed 's/: /=/g')
az resource tag --tags $rt Project=Redesign -g examplegroup -n examplevnet --resource-type "Microsoft.Network/virtualNetworks"

要将资源组中的所有标记应用于其资源,并且不保留资源上的现有标记,请使用以下脚本:To apply all tags from a resource group to its resources, and not retain existing tags on the resources, use the following script:

groups=$(az group list --query [].name --output tsv)
for rg in $groups
do
  jsontag=$(az group show -n $rg --query tags)
  t=$(echo $jsontag | tr -d '"{},' | sed 's/: /=/g')
  r=$(az resource list -g $rg --query [].id --output tsv)
  for resid in $r
  do
    az resource tag --tags $t --id $resid
  done
done

若要将资源组中的所有标记应用于其资源,并且保留资源上的现有标记,请使用以下脚本:To apply all tags from a resource group to its resources, and retain existing tags on resources, use the following script:

groups=$(az group list --query [].name --output tsv)
for rg in $groups
do
  jsontag=$(az group show -n $rg --query tags)
  t=$(echo $jsontag | tr -d '"{},' | sed 's/: /=/g')
  r=$(az resource list -g $rg --query [].id --output tsv)
  for resid in $r
  do
    jsonrtag=$(az resource show --id $resid --query tags)
    rt=$(echo $jsonrtag | tr -d '"{},' | sed 's/: /=/g')
    az resource tag --tags $t$rt --id $resid
  done
done

模板Templates

要在部署过程中标记资源,可将 tags 元素添加到正在部署的资源。To tag a resource during deployment, add the tags element to the resource you are deploying. 提供标记名称和值。Provide the tag name and value.

将文本值应用到标记名称Apply a literal value to the tag name

以下示例显示了一个带两个标记(DeptEnvironment)的存储帐户,这两个标记设置为文本值:The following example shows a storage account with two tags (Dept and Environment) that are set to literal values:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
    {
      "apiVersion": "2016-01-01",
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[concat('storage', uniqueString(resourceGroup().id))]",
      "location": "[resourceGroup().location]",
      "tags": {
        "Dept": "Finance",
        "Environment": "Production"
      },
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "properties": { }
    }
    ]
}

将对象应用到标记元素Apply an object to the tag element

可以定义一个对象参数,用于存储多个标记,并将该对象应用于标记元素。You can define an object parameter that stores several tags, and apply that object to the tag element. 对象中的每个属性将成为该资源的单独标记。Each property in the object becomes a separate tag for the resource. 以下示例有一个名为 tagValues 的参数,应用于标记元素。The following example has a parameter named tagValues that is applied to the tag element.

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "tagValues": {
      "type": "object",
      "defaultValue": {
        "Dept": "Finance",
        "Environment": "Production"
      }
    }
  },
  "resources": [
    {
      "apiVersion": "2016-01-01",
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[concat('storage', uniqueString(resourceGroup().id))]",
      "location": "[resourceGroup().location]",
      "tags": "[parameters('tagValues')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "properties": {}
    }
  ]
}

将 JSON 字符串应用到标记名称Apply a JSON string to the tag name

要将多个值存储在单个标记中,请应用表示值的 JSON 字符串。To store many values in a single tag, apply a JSON string that represents the values. 整个 JSON 字符串将存储为一个标记,不能超过 256 个字符。The entire JSON string is stored as one tag that cannot exceed 256 characters. 以下示例有一个名为 CostCenter 的标记,其中包含 JSON 字符串中的几个值:The following example has a single tag named CostCenter that contains several values from a JSON string:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
    {
      "apiVersion": "2016-01-01",
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[concat('storage', uniqueString(resourceGroup().id))]",
      "location": "[resourceGroup().location]",
      "tags": {
        "CostCenter": "{\"Dept\":\"Finance\",\"Environment\":\"Production\"}"
      },
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "properties": { }
    }
    ]
}

门户Portal

  1. 若要查看资源或资源组的标记,请在概述中查找现有标记。To view the tags for a resource or a resource group, looks for existing tags in the overview. 如果以前未应用标记,则该列表为空。If you have not previously applied tags, the list is empty.

    查看资源或资源组的标记

  2. 若要添加标记,请选择“单击此处以添加标记”。To add a tag, select Click here to add tags.

  3. 提供名称和值。Provide a name and value. 选择“+”以添加标记。Select + to add the tag.

    添加标记

  4. 根据需要继续添加标记。Continue adding tags as needed. 完成后,选择“保存”。When done, select Save.

    保存标记

  5. 标记现已显示在概述中。The tags are now displayed in the overview.

    显示标记

  6. 若要添加或删除标记,请选择“更改”。To add or delete a tag, select change.

  7. 若要删除标记,请选择回收站图标。To delete a tag, select the trash icon. 然后选择“保存”。Then, select Save.

    删除标记

将标记批量分配到多个资源:To bulk assign tags to multiple resources:

  1. 从任意资源列表中,选中想要分配标记的资源的复选框。From any list of resources, select the checkbox for the resources you want to assign the tag.

    选择多个资源

  2. 选择“分配标记”Select Assign tags

    分配标记

  3. 在每个名称和值后,选择“+”。After each name and value, select +. 完成后,选择“分配”。When done, select Assign.

    选择“分配”

查看所有具有标记的资源:To view all resources with a tag:

  1. 选择“所有服务”和“标记”。Select All services and Tags.

    按标记查找

  2. 选择用于查看资源的标记。Select the tag for viewing resources.

    选择标记

  3. 此时会显示所有具有该标记的资源。All resources with that tag are displayed.

    按标记查看资源

  4. 将视图固定到仪表板可实现快速访问。For quick access, pin the view to the dashboard.

    固定到仪表板

  5. 仪表板中提供该视图。The view is available from the dashboard.

    仪表板

REST APIREST API

Azure 门户和 PowerShell 均在后台使用资源管理器 REST APIThe Azure portal and PowerShell both use the Resource Manager REST API behind the scenes. 如果需要将标记集成到其他环境中,可对资源 ID 使用 GET 以获取标记,并使用 PATCH 调用更新标记集。If you need to integrate tagging into another environment, you can get tags by using GET on the resource ID and update the set of tags by using a PATCH call.

标记和计费Tags and billing

可使用标记对计费数据进行分组。You can use tags to group your billing data. 例如,如果针对不同组织运行多个虚拟机,可以使用标记根据成本中心对使用情况进行分组。For example, if you are running multiple VMs for different organizations, use the tags to group usage by cost center. 还可使用标记根据运行时环境对成本进行分类;例如,在生产环境中运行的虚拟机的计费使用情况。You can also use tags to categorize costs by runtime environment, such as the billing usage for VMs running in the production environment.

可以通过 Azure 资源使用情况与费率卡 API 或者使用情况逗号分隔值 (CSV) 文件检索有关标记的信息。You can retrieve information about tags through the Azure Resource Usage and RateCard APIs or the usage comma-separated values (CSV) file. 可从 Azure 帐户门户EA 门户下载使用情况文件。You download the usage file from the Azure account portal or EA portal. 有关以编程方式访问计费信息的详细信息,请参阅深入了解 Microsoft Azure 资源消耗For more information about programmatic access to billing information, see Gain insights into your Microsoft Azure resource consumption. 有关 REST API 操作,请参阅 Azure 计费 REST API 参考For REST API operations, see Azure Billing REST API Reference.

在为支持标记和计费的服务下载使用情况 CSV 时,标记会显示在“标记”列中。When you download the usage CSV for services that support tags with billing, the tags appear in the Tags column. 有关详细信息,请参阅了解 Microsoft Azure 帐单For more information, see Understand your bill for Microsoft Azure.

在计费中查看标记

后续步骤Next steps