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

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

可以将标记应用到 Azure 资源,以逻辑方式按类别对其进行组织。You apply tags to your Azure resources to logically organize them by categories. 每个标记包含一个名称和一个值。Each tag consists of a name and a value. 例如,可以对生产中的所有资源应用名称“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.

以下限制适用于标记: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.
  • 应用于资源组的标记不会被该资源组中的资源继承。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: <, >, %, &, \, ?, /

PowerShellPowerShell

本文中的示例需要版本 3.0 或更高版本的 Azure PowerShell。The examples in this article require version 3.0 or later of Azure PowerShell. 如果未安装 3.0 或更高版本,请先使用 PowerShell 库或 Web 平台安装程序更新版本If you do not have version 3.0 or later, update your version by using PowerShell Gallery or Web Platform Installer.

若要查看资源组的现有标记,请使用: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 {resource-id}).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:

(Find-AzureRmResourceGroup -Tag @{ Dept="Finance" }).Name

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

(Find-AzureRmResource -TagName Dept -TagValue Finance).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 += @{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 += @{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)
{
    Find-AzureRmResource -ResourceGroupNameEquals $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 = $group | Find-AzureRmResource
    foreach ($r in $resources)
    {
        $resourcetags = (Get-AzureRmResource -ResourceId $r.ResourceId).Tags
        foreach ($key in $group.Tags.Keys)
        {
            if (($resourcetags) -AND ($resourcetags.ContainsKey($key))) { $resourcetags.Remove($key) }
        }
        $resourcetags += $group.Tags
        Set-AzureRmResource -Tag $resourcetags -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, select the Tags icon.

    在资源和资源组边栏选项卡上选择标记

  2. 此时会显示资源的现有标记。You see the existing tags for the resource. 如果以前未应用标记,则该列表为空。If you have not previously applied tags, the list is empty.

    在资源和资源组边栏选项卡上显示现有标记

  3. 若要添加标记,请键入名称和值,或者从下拉菜单中选择一个现有的名称和值。To add a tag, type a name and value, or select an existing one from the drop-down menu. 选择“保存”。Select Save.

    添加新标记

  4. 若要查看具有某个标记值的所有资源,请选择 >(“更多服务”),并在筛选文本框中输入“标记”字样。To view all the resources that have a tag value, select > (More services), and enter the word Tags into the filter text box. 从可用选项中选择“标记”。Select Tags from the available options.

    通过“浏览”中心查找标记

  5. 此时会显示订阅中标记的摘要。You see a summary of the tags in your subscriptions.

    显示所有标记

  6. 选择任一标记会显示带有该标记的资源和资源组。Select any of the tags to display the resources and resource groups with that tag.

    显示带标记的资源

  7. 选择“将边栏选项卡固定到仪表板”以方便访问。Select Pin blade to dashboard for quick access.

    将标记固定到仪表板

  8. 可以从仪表板中选择固定的标记,查看包含该标记的资源。You can select the pinned tag from the dashboard to see the resources with that tag.

    将标记固定到仪表板

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