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

可将标记应用于 Azure 资源,以便按逻辑将这些资源组织到分类中。You apply tags to your Azure resources 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 autotagging strategy to reduce the burden on users and increase accuracy.

备注

本文介绍如何删除设备或服务中的个人数据,并且可为 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.

限制Limitations

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

  • 并非所有资源类型都支持标记。Not all resource types support tags. 若要确定是否可以将标记应用到资源类型,请参阅 Azure 资源的标记支持To determine if you can apply a tag to a resource type, see Tag support for Azure resources.

  • 每个资源或资源组最多可以有 50 个标记名称/值对。Each resource or resource group can have a maximum of 50 tag name/value pairs. 如果需要应用的标记超过最大允许数量,请使用 JSON 字符串作为标记值。If you need to apply more tags than the maximum allowed number, use a JSON string for the tag value. JSON 字符串可以包含多个应用于单个标记名称的值。The JSON string can contain many values that are applied to a single tag name. 一个资源组可以包含多个资源,这些资源每个都有 50 个标记名称/值对。A resource group can contain many resources that each have 50 tag name/value pairs.

  • 标记名称不能超过 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.

  • 通用化 VM 不支持标记。Generalized VMs don't support tags.

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

    备注

    目前 Azure DNS 区域和流量管理器服务也不允许在标记中使用空格。Currently Azure DNS zones and Traffic Manger services also don't allow the use of spaces in the tag.

所需访问权限Required access

要向资源应用标记,用户必须具有对该资源类型的写权限。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.

策略Policies

可以使用 Azure Policy 来强制实施标记规则和约定。You can use Azure Policy to enforce tagging rules and conventions. 通过创建策略,可以避免将与预期的组织标记不相符的资源部署到订阅。By creating a policy, you avoid the scenario of resources being deployed to your subscription that don't comply with the expected tags for your organization. 无需手动应用标记或搜索不符合的资源,可以创建一个策略,在部署期间自动应用所需标记。Instead of manually applying tags or searching for resources that aren't compliant, you can create a policy that automatically applies the needed tags during deployment. 现在,还可以通过新的 Modify 效果和修正任务将标记应用于现有资源。Tags can also now be applied to existing resources with the new Modify effect and a remediation task. 以下部分展示标记策略示例。The following section shows example policies for tags.

名称Name 说明Description 效果Effect(s) 版本Version SourceSource
追加标记及其默认值Append tag and its default value 创建或更新任何缺少此标记的资源时追加指定的标记和值。Appends the specified tag and value when any resource which is missing this tag is created or updated. 在更改这些资源之前,请不要修改应用此策略之前创建的资源的标记。Does not modify the tags of resources created before this policy was applied until those resources are changed. 不要应用到资源组。Does not apply to resource groups. 可以使用新的“modify”效果策略来支持对现有资源中的标记进行修正 (请参阅 https://aka.ms/modifydoc) 。New 'modify' effect policies are available that support remediation of tags on existing resources (see https://aka.ms/modifydoc). appendappend 1.0.01.0.0 GitHubGitHub
将标记及其默认值追加到资源组Append tag and its default value to resource groups 创建或更新任何缺少此标记的资源组时追加指定的标记和值。Appends the specified tag and value when any resource group which is missing this tag is created or updated. 在更改这些资源组之前,请不要修改应用此策略之前创建的资源组的标记。Does not modify the tags of resource groups created before this policy was applied until those resource groups are changed. 可以使用新的“modify”效果策略来支持对现有资源中的标记进行修正 (请参阅 https://aka.ms/modifydoc) 。New 'modify' effect policies are available that support remediation of tags on existing resources (see https://aka.ms/modifydoc). appendappend 1.0.01.0.0 GitHubGitHub
从资源组追加标记及其值Append tag and its value from the resource group 创建或更新任何缺少此标记的资源时,从资源组追加指定的标记及其值。Appends the specified tag with its value from the resource group when any resource which is missing this tag is created or updated. 在更改这些资源之前,请不要修改应用此策略之前创建的资源的标记。Does not modify the tags of resources created before this policy was applied until those resources are changed. 可以使用新的“modify”效果策略来支持对现有资源中的标记进行修正 (请参阅 https://aka.ms/modifydoc) 。New 'modify' effect policies are available that support remediation of tags on existing resources (see https://aka.ms/modifydoc). appendappend 1.0.01.0.0 GitHubGitHub
需要指定的标记Require specified tag 强制要求存在某个标记。Enforces existence of a tag. 不要应用到资源组。Does not apply to resource groups. denydeny 1.0.01.0.0 GitHubGitHub
要求资源组中存在指定的标记Require specified tag on resource groups 强制要求资源组中存在某个标记。Enforces existence of a tag on resource groups. denydeny 1.0.01.0.0 GitHubGitHub
需要标记及其值Require tag and its value 强制执行所需的标记及其值。Enforces a required tag and its value. 不要应用到资源组。Does not apply to resource groups. denydeny 1.0.01.0.0 GitHubGitHub
要求资源组中存在标记及其值Require tag and its value on resource groups 强制要求资源组中存在所需的标记及其值。Enforces a required tag and its value on resource groups. denydeny 1.0.01.0.0 GitHubGitHub

PowerShellPowerShell

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

(Get-AzResourceGroup -Name examplegroup).Tags

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

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

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

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

或者,如果有资源的资源 ID,可以传递该资源 ID 以获取标记。Or, if you have the resource ID for a resource, you can pass that resource ID to get the tags.

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

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

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

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

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

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

(Get-AzResource -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-AzResourceGroup -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-AzResourceGroup -Name examplegroup).Tags
$tags.Add("Status", "Approved")
Set-AzResourceGroup -Tag $tags -Name examplegroup

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

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

一个资源组中可能有多个同名资源。You may have more than one resource with the same name in a resource group. 在这种情况下,可以通过以下命令设置每个资源:In that case, you can set each resource with the following commands:

$resource = Get-AzResource -ResourceName sqlDatabase1 -ResourceGroupName examplegroup
$resource | ForEach-Object { Set-AzResource -Tag @{ "Dept"="IT"; "Environment"="Test" } -ResourceId $_.ResourceId -Force }

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

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

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

$group = Get-AzResourceGroup -Name examplegroup
Get-AzResource -ResourceGroupName $group.ResourceGroupName | ForEach-Object {Set-AzResource -ResourceId $_.ResourceId -Tag $group.Tags -Force }

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

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

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

Set-AzResourceGroup -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

将标记添加到资源组或资源时,可以覆盖现有的标记,或将新标记追加到现有标记之后。When adding tags to a resource group or resource, you can either overwrite the existing tags or append new tags to existing tags.

若要覆盖资源组的现有标记,请使用:To overwrite the existing tags on a resource group, use:

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

若要将标记追加到资源组的现有标记之后,请使用:To append a tag to the existing tags on a resource group, use:

az group update -n examplegroup --set tags.'Status'='Approved'

若要覆盖资源的标记,请使用:To overwrite the tags on a resource, use:

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

若将标记追加到资源的现有标记之后,请使用:To append a tag to the existing tags on a resource, use:

az resource update --set tags.'Status'='Approved' -g examplegroup -n examplevnet --resource-type "Microsoft.Network/virtualNetworks"

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

jsontags=$(az group show --name examplegroup --query tags -o json)
tags=$(echo $jsontags | tr -d '"{},' | sed 's/: /=/g')
resourceids=$(az resource list -g examplegroup --query [].id --output tsv)
for id in $resourceids
do
  az resource tag --tags $tags --id $id
done

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

jsontags=$(az group show --name examplegroup --query tags -o json)
tags=$(echo $jsontags | tr -d '"{},' | sed 's/: /=/g')

resourceids=$(az resource list -g examplegroup --query [].id --output tsv)
for id in $resourceids
do
  resourcejsontags=$(az resource show --id $id --query tags -o json)
  resourcetags=$(echo $resourcejsontags | tr -d '"{},' | sed 's/: /=/g')
  az resource tag --tags $tags$resourcetags --id $id
done

如果标记名称或值包含空格,则必须执行几个额外的步骤。If your tag names or values include spaces, you must take a couple of extra steps. 下面的示例在标记可能包含空格时将资源组中的所有标记应用于其资源。The following example applies all tags from a resource group to its resources when the tags may contain spaces.

jsontags=$(az group show --name examplegroup --query tags -o json)
tags=$(echo $jsontags | tr -d '{}"' | sed 's/: /=/g' | sed "s/\"/'/g" | sed 's/, /,/g' | sed 's/ *$//g' | sed 's/^ *//g')
origIFS=$IFS
IFS=','
read -a tagarr <<< "$tags"
resourceids=$(az resource list -g examplegroup --query [].id --output tsv)
for id in $resourceids
do
  az resource tag --tags "${tagarr[@]}" --id $id
done
IFS=$origIFS

模板Templates

若要在部署过程中标记资源,请将 tags 元素添加到要部署的资源。To tag a resource during deployment, add the tags element to the resource you're 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",
    "parameters": {
        "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]"
        }
    },
    "resources": [
        {
            "apiVersion": "2019-04-01",
            "type": "Microsoft.Storage/storageAccounts",
            "name": "[concat('storage', uniqueString(resourceGroup().id))]",
            "location": "[parameters('location')]",
            "tags": {
                "Dept": "Finance",
                "Environment": "Production"
            },
            "sku": {
                "name": "Standard_LRS"
            },
            "kind": "Storage",
            "properties": {}
        }
    ]
}

若要设置日期/时间值的标记,请使用 utcNow 函数To set a tag to a datetime value, use the utcNow function.

将对象应用到标记元素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": {
        "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]"
        },
        "tagValues": {
            "type": "object",
            "defaultValue": {
                "Dept": "Finance",
                "Environment": "Production"
            }
        }
    },
    "resources": [
        {
            "apiVersion": "2019-04-01",
            "type": "Microsoft.Storage/storageAccounts",
            "name": "[concat('storage', uniqueString(resourceGroup().id))]",
            "location": "[parameters('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 can't 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",
    "parameters": {
        "location": {
            "type": "string",
            "defaultValue": "[resourceGroup().location]"
        }
    },
    "resources": [
        {
            "apiVersion": "2019-04-01",
            "type": "Microsoft.Storage/storageAccounts",
            "name": "[concat('storage', uniqueString(resourceGroup().id))]",
            "location": "[parameters('location')]",
            "tags": {
                "CostCenter": "{\"Dept\":\"Finance\",\"Environment\":\"Production\"}"
            },
            "sku": {
                "name": "Standard_LRS"
            },
            "kind": "Storage",
            "properties": {}
        }
    ]
}

应用资源组中的标记Apply tags from resource group

若要将资源组中的标记应用于资源,请使用 resourceGroup 函数。To apply tags from a resource group to a resource, use the resourceGroup function. 获取标记值时,请使用 tags[tag-name] 语法而不是 tags.tag-name 语法,因为有些字符在点表示法中无法正确解析。When getting the tag value, use the tags[tag-name] syntax instead of the tags.tag-name syntax, because some characters aren't parsed correctly in the dot notation.

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

门户Portal

  1. 若要查看资源或资源组的标记,请在概述中查找现有标记。To view the tags for a resource or a resource group, look 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. 在 Azure 门户菜单中,选择“所有服务” 。On the Azure portal menu, select All services. 选择“常规” ,然后选择“标记” 。Select General, then 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. 例如,如果针对不同组织运行多个 VM,可以使用标记根据成本中心对使用情况进行分组。For example, if you're running multiple VMs for different organizations, use the tags to group usage by cost center. 还可使用标记根据运行时环境(例如,在生产环境中运行的 VM 的计费使用情况)对成本进行分类。You can also use tags to categorize costs by runtime environment, such as the billing usage for VMs running in the production environment.

可以通过使用情况逗号分隔值 (CSV) 文件检索有关标记的信息。You can retrieve information about tags through the usage comma-separated values (CSV) file. 可以从 Azure 帐户门户下载使用情况文件。You download the usage file from the Azure account portal.

有关 REST API 操作,请参阅 Azure 计费 REST API 参考For REST API operations, see Azure Billing REST API Reference.

后续步骤Next steps