使用标记整理 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:

  • 并非所有资源类型都支持标记。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: <, >, %, &, \, ?, /

    Note

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

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

Note

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

策略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. 现在,还可以通过新的修正任务将标记应用于现有资源。Tags can also now be applied to existing resources with the new remediation task. 以下部分展示标记策略示例。The following section shows example policies for tags.

TagsTags

应用标记及其默认值Apply tag and its default value 如果未提供标记,追加指定的标记名称和值。Appends a specified tag name and value, if that tag is not provided. 由你指定要应用的标记名称和值。You specify the tag name and value to apply.
计费标记策略计划Billing Tags Policy Initiative 要求成本中心和产品名称有指定的标记值。Requires specified tag values for cost center and product name. 使用内置策略来应用并强制执行所需标记。Uses built-in policies to apply and enforce required tags. 指定所需的标记值。You specify the required values for the tags.
强制实施标记和值Enforce tag and its value 需要指定的标记名称和值。Requires a specified tag name and value. 指定要强制实施的标记名称和值。You specify the tag name and value to enforce.
在资源组强制执行标记及其值Enforce tag and its value on resource groups 要求资源组有标记和值。Requires a tag and value on a resource group. 由你指定标记名称和值。You specify the required tag name and value.

PowerShellPowerShell

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

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

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

(Get-AzResource -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-AzResource -ResourceName examplevnet -ResourceGroupName examplegroup).Tags

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

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

若要获取具有特定标记的资源,请使用: To get resources that have a specific tag, 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:

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

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

$r = Get-AzResource -ResourceName examplevnet -ResourceGroupName examplegroup
$r.Tags.Add("Status", "Approved")
Set-AzResource -Tag $r.Tags -ResourceId $r.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:

$groups = Get-AzResourceGroup
foreach ($g in $groups)
{
    Get-AzResource -ResourceGroupName $g.ResourceGroupName | ForEach-Object {Set-AzResource -ResourceId $_.ResourceId -Tag $g.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 "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

每次将标记应用到某个资源或资源组时,都会覆盖该资源或资源组中的现有标记。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 -o json)
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 keep 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 -o json)
  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 keep 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 -o json)
  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 -o json)
    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'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, 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. 例如,如果针对不同组织运行多个 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