

# 标记 Athena 资源
<a name="tags"></a>

标签包含您定义的一个键和一个值。您在标记 Athena 资源时，将为该资源分配自定义元数据。您可以使用标签按照不同方式（例如按用途、所有者或环境）对 AWS 资源进行分类。在 Athena 中，工作组、数据目录和容量预留等资源是可标记的资源。例如，您可以在账户中为工作组创建一组标签，以帮助您跟踪工作组所有者，或按用途识别工作组。如果您还在 Billing and Cost Management（账单和成本管理）控制台中启用标签作为成本分配标签，则与运行查询相关的费用将显示在“成本和使用情况报告”中，并带有该成本分配标签。我们建议您使用 AWS [标记最佳实践](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html) 来创建一组一致的标签，以满足您组织的要求。

您可以通过 Athena 控制台或 API 操作来使用标签。

**Topics**
+ [标签基本知识](#tag-basics)
+ [标签限制](#tag-restrictions)
+ [使用工作组的标签](tags-console.md)
+ [使用 API 和 AWS CLI 标签操作](tags-operations.md)
+ [使用基于标签的 IAM 访问控制策略](tags-access-control.md)

## 标签基本知识
<a name="tag-basics"></a>

标签是为 Athena 资源分配的标记。每个标签都包含定义的一个键和一个可选值。

标签可让您按不同方式对 AWS 资源进行分类。例如，您可以为账户的工作组定义一组标签，以帮助您跟踪每个工作组所有者或用途。

您可以在创建新的 Athena 工作组或数据目录时添加标签，也可以在其中添加、编辑或删除标签。您可以在控制台中编辑标签。要使用 API 操作编辑标签，请删除旧标签并添加新标签。如果删除资源，资源的所有标签也会被删除。

Athena 不会自动向您的资源分配标签。您可以修改标签的密钥和值，还可以随时删除资源的标签。您可以将标签的值设为空的字符串，但是不能将其设为空值。请不要将重复的标签键添加到同一资源中。如果这样操作，Athena 会发布一条错误消息。如果通过 **TagResource** 操作用现有标签键标记资源，则新的标签值将覆盖旧值。

在 IAM 中，您可以控制 Amazon Web Services 账户中的哪些用户有权创建、编辑、删除或列出标签。有关更多信息，请参阅 [使用基于标签的 IAM 访问控制策略](tags-access-control.md)。

有关 Amazon Athena 标记操作的完整列表，请参阅 [Amazon Athena API 参考](https://docs.aws.amazon.com/athena/latest/APIReference/)中的 API 操作名称。

您可以使用标签记账。有关更多信息，请参阅《AWS 账单与成本管理 用户指南**》中的 [使用账单标签](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/custom-tags.html)。

有关更多信息，请参阅 [标签限制](#tag-restrictions)。

## 标签限制
<a name="tag-restrictions"></a>

标签具有以下限制：
+ 在 Athena 中，您可以标记工作组、数据目录和容量预留。但不能标记查询。
+ 每个资源的最大标签数是 50。要不超出限制，请检查并删除未使用的标签。
+ 对于每个资源，每个标签键都必须是唯一的，每个标签键只能有一个值。请不要同时将重复的标签键添加到同一资源中。如果这样操作，Athena 会发布一条错误消息。如果在单独的 `TagResource` 操作中使用现有标签键标记工作组，则新的标签值将覆盖旧值。
+ 标签键长度为 1-128 个 Unicode 字符（UTF-8 格式）。
+ 标签值长度为 0-256 个 Unicode 字符（UTF-8 格式）。

  标记操作（如添加、编辑、删除或列出标签），需要您为工作组资源指定一个 ARN。
+ Athena 允许使用 UTF-8 格式的字母、数字和空格，以及以下字符：\$1 - = . \$1 : / @。
+ 标签键和值区分大小写。
+ 标记键中的 `"aws:"` 前缀将保留以供 AWS 使用。不能编辑或删除带此前缀的标签键。具有此前缀的标签不计入每个资源的标签数限制。
+ 您分配的标签仅可用于您的 Amazon Web Services 账户。

# 使用工作组的标签
<a name="tags-console"></a>

通过 Athena 控制台，您可以查看您账户中每个工作组所使用的标签。您只能按工作组查看标签。您还可以通过 Athena 控制台，每次在一个工作组中应用、编辑或删除标签。

您可以使用创建的标签搜索工作组。

**Topics**
+ [显示单个工作组的标签](#tags-display)
+ [对单个工作组添加和删除标签](#tags-add-delete)

## 显示单个工作组的标签
<a name="tags-display"></a>

**在 Athena 控制台中显示单个工作组的标签**

1. 从 [https://console.aws.amazon.com/athena/](https://console.aws.amazon.com/athena/home) 打开 Athena 控制台。

1. 如果控制台导航窗格不可见，请选择左侧的扩展菜单。  
![\[选择扩展菜单。\]](http://docs.aws.amazon.com/zh_cn/athena/latest/ug/images/nav-pane-expansion.png)

1. 在导航菜单上，选择 **Workgroups**（工作组），然后选择您希望使用的工作组。

1. 请执行以下操作之一：
   + 选择**标签**选项卡。如果标签列表太长，请使用搜索框。
   + 选择 **Edit**（编辑），然后向下滚动到 **Tags**（标签）部分。

## 对单个工作组添加和删除标签
<a name="tags-add-delete"></a>

您可以从 **Workgroups (工作组)** 选项卡直接管理单个工作组的标签。

**注意**  
如果您希望用户在控制台中创建工作组时添加标签，或者在使用 **CreateWorkGroup** 操作时传入标签，请确保向用户授予 IAM 权限以执行 **TagResource** 和 **CreateWorkGroup** 操作。

**在创建新工作组时添加标签**

1. 从 [https://console.aws.amazon.com/athena/](https://console.aws.amazon.com/athena/home) 打开 Athena 控制台。

1. 在导航菜单上，选择 **Workgroups**（工作组）。

1. 选择 **Create workgroup**（创建工作组）并根据需要填入值。有关详细步骤，请参阅[创建工作组](creating-workgroups.md)。

1. 在 **Tags**（标签）部分，通过指定密钥和值，添加一个或多个标签。请勿同时将重复的标签键添加到同一个工作组。如果这样操作，Athena 会发布一条错误消息。有关更多信息，请参阅 [标签限制](tags.md#tag-restrictions)。

1. 完成后，选择 **Create workgroup**（创建工作组）。

**对现有工作组添加或编辑标签**

1. 从 [https://console.aws.amazon.com/athena/](https://console.aws.amazon.com/athena/home) 打开 Athena 控制台。

1. 在导航窗格中，选择 **Workgroups**（工作组）。

1. 选择您想要修改的工作组。

1. 请执行以下操作之一：
   + 选择**标签**选项卡，然后选择**管理标签**。
   + 选择 **Edit**（编辑），然后向下滚动到 **Tags**（标签）部分。

1. 为每个标签指定密钥和值。有关更多信息，请参阅 [标签限制](tags.md#tag-restrictions)。

1. 选择 **Save**。

**删除单个工作组的标签**

1. 从 [https://console.aws.amazon.com/athena/](https://console.aws.amazon.com/athena/home) 打开 Athena 控制台。

1. 在导航窗格中，选择 **Workgroups**（工作组）。

1. 选择您想要修改的工作组。

1. 请执行以下操作之一：
   + 选择**标签**选项卡，然后选择**管理标签**。
   + 选择 **Edit**（编辑），然后向下滚动到 **Tags**（标签）部分。

1. 在标签列表中，为要删除的标签选择 **Remove**（删除），然后选择 **Save**（保存）。

# 使用 API 和 AWS CLI 标签操作
<a name="tags-operations"></a>

使用以下标签操作在资源中添加、删除或列出标签。


****  

| API | CLI | 操作描述 | 
| --- | --- | --- | 
| TagResource | tag-resource | 在具有指定 ARN 的资源上添加或覆盖一个或多个标签。 | 
| UntagResource | untag-resource | 从具有指定 ARN 的资源中删除一个或多个标签。 | 
| ListTagsForResource | list‑tags‑for‑resource | 列出具有指定 ARN 的资源的一个或多个标签。 | 

**在创建资源时添加标签**  
要在创建工作组或数据目录时添加标签，请将 `tags` 参数与 `CreateWorkGroup` 或 `CreateDataCatalog` API 操作结合使用，或者将该参数与 AWS CLI `create-work-group` 或 `create-data-catalog` 命令结合使用。

## 使用 API 操作管理标签
<a name="tags-operations-examples-java"></a>

以下示例说明如何使用标签 API 操作来管理工作组和数据目录上的标签。这些示例采用的是 Java 编程语言。

### 示例：TagResource
<a name="tags-operations-examples-java-tag-resource"></a>

以下示例将两个标签添加到工作组 `workgroupA` 中：

```
List<Tag> tags = new ArrayList<>();
tags.add(new Tag().withKey("tagKey1").withValue("tagValue1"));
tags.add(new Tag().withKey("tagKey2").withValue("tagValue2"));

TagResourceRequest request = new TagResourceRequest()
    .withResourceARN("arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA")
    .withTags(tags);

client.tagResource(request);
```

以下示例将两个标签添加到数据目录 `datacatalogA` 中：

```
List<Tag> tags = new ArrayList<>();
tags.add(new Tag().withKey("tagKey1").withValue("tagValue1"));
tags.add(new Tag().withKey("tagKey2").withValue("tagValue2"));

TagResourceRequest request = new TagResourceRequest()
    .withResourceARN("arn:aws:athena:us-east-1:123456789012:datacatalog/datacatalogA")
    .withTags(tags);

client.tagResource(request);
```

**注意**  
请不要将重复的标签键添加到同一资源中。如果这样操作，Athena 会发布一条错误消息。如果在单独的 `TagResource` 操作中使用现有标签键标记工作组，则新的标签值将覆盖旧值。

### 示例：UntagResource
<a name="tags-operations-examples-java-untag-resource"></a>

以下示例从工作组 `workgroupA` 中删除 `tagKey2`：

```
List<String> tagKeys = new ArrayList<>();
tagKeys.add("tagKey2");

UntagResourceRequest request = new UntagResourceRequest()
    .withResourceARN("arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA")
    .withTagKeys(tagKeys);

client.untagResource(request);
```

以下示例从数据目录 `datacatalogA` 中删除 `tagKey2`：

```
List<String> tagKeys = new ArrayList<>();
tagKeys.add("tagKey2");

UntagResourceRequest request = new UntagResourceRequest()
    .withResourceARN("arn:aws:athena:us-east-1:123456789012:datacatalog/datacatalogA")
    .withTagKeys(tagKeys);

client.untagResource(request);
```

### 示例：ListTagsForResource
<a name="tags-operations-examples-java-list-tags-for-resource"></a>

以下示例列出了工作组 `workgroupA` 的标签：

```
ListTagsForResourceRequest request = new ListTagsForResourceRequest()
    .withResourceARN("arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA");

ListTagsForResourceResult result = client.listTagsForResource(request);

List<Tag> resultTags = result.getTags();
```

以下示例列出了数据目录 `datacatalogA` 的标签：

```
ListTagsForResourceRequest request = new ListTagsForResourceRequest()
    .withResourceARN("arn:aws:athena:us-east-1:123456789012:datacatalog/datacatalogA");

ListTagsForResourceResult result = client.listTagsForResource(request);

List<Tag> resultTags = result.getTags();
```

## 使用 AWS CLI 管理标签
<a name="tags-operations-examples-cli"></a>

以下示例说明如何使用 AWS CLI 创建和管理数据目录上的标签。

### 将标签添加到资源：tag-resource
<a name="tags-operations-examples-cli-tag-resource"></a>

`tag-resource` 命令可向指定资源添加一个或多个标签。

**语法**  
`aws athena tag-resource --resource-arn arn:aws:athena:region:account_id:datacatalog/catalog_name --tags Key=string,Value=string Key=string,Value=string`

`--resource-arn` 参数指定要将标签添加到的资源。`--tags` 参数指定要作为标签添加到资源的用空格分隔的键/值对列表。

**Example**  
以下示例将标签添加到 `mydatacatalog` 数据目录中。  

```
aws athena tag-resource --resource-arn arn:aws:athena:us-east-1:111122223333:datacatalog/mydatacatalog --tags Key=Color,Value=Orange Key=Time,Value=Now
```
要显示结果，请使用 `list-tags-for-resource` 命令。  
有关在使用 `create-data-catalog` 命令时添加标签的信息，请参阅 [注册目录：Create-data-catalog](datastores-hive-cli.md#datastores-hive-cli-registering-a-catalog)。

### 列出资源的标签：list-tags-for-resource
<a name="tags-operations-examples-cli-list-tags-for-resource"></a>

`list-tags-for-resource` 命令将列出指定资源的标签。

**语法**  
`aws athena list-tags-for-resource --resource-arn arn:aws:athena:region:account_id:datacatalog/catalog_name`

`--resource-arn` 参数指定将列出其标签的资源。

以下示例列出了 `mydatacatalog` 数据目录的标签。

```
aws athena list-tags-for-resource --resource-arn arn:aws:athena:us-east-1:111122223333:datacatalog/mydatacatalog
```

以下示例结果采用 JSON 格式。

```
{
    "Tags": [
        {
            "Key": "Time",
            "Value": "Now"
        },
        {
            "Key": "Color",
            "Value": "Orange"
        }
    ]
}
```

### 从资源中移除标签：untag-resource
<a name="tags-operations-examples-cli-untag-resource"></a>

`untag-resource` 命令将从指定资源中删除指定的标签键及其关联的值。

**语法**  
`aws athena untag-resource --resource-arn arn:aws:athena:region:account_id:datacatalog/catalog_name --tag-keys key_name [key_name ...]` 

`--resource-arn` 参数指定从中删除标签的资源。`--tag-keys` 参数采用一组用空格分隔的键名称。对于指定的每个键名称，`untag-resource` 命令将同时删除键及其值。

以下示例从 `mydatacatalog` 目录资源中删除 `Color` 和 `Time` 键及其值。

```
aws athena untag-resource --resource-arn arn:aws:athena:us-east-1:111122223333:datacatalog/mydatacatalog --tag-keys Color Time
```

# 使用基于标签的 IAM 访问控制策略
<a name="tags-access-control"></a>

拥有标签后，您可以编写包含 `Condition` 块的 IAM policy，以便基于其标签来控制对资源的访问。本部分包括工作组和数据目录资源的标签策略示例。

## 工作组的标签策略示例
<a name="tag-policy-examples-workgroups"></a>

### 示例：基本标记策略
<a name="tag-policy-examples-workgroups-basic"></a>

以下 IAM policy 允许您运行查询并与名为 `workgroupA` 的工作组的标签进行交互：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
       {
            "Effect": "Allow",
            "Action": [
                "athena:ListWorkGroups",
                "athena:ListEngineVersions",
                "athena:ListDataCatalogs",
                "athena:ListDatabases",
                "athena:GetDatabase",
                "athena:ListTableMetadata",
                "athena:GetTableMetadata"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:GetWorkGroup",
                "athena:TagResource",
                "athena:UntagResource",
                "athena:ListTagsForResource",
                "athena:StartQueryExecution",
                "athena:GetQueryExecution",
                "athena:BatchGetQueryExecution",
                "athena:ListQueryExecutions",
                "athena:StopQueryExecution",
                "athena:GetQueryResults",
                "athena:GetQueryResultsStream",
                "athena:CreateNamedQuery",
                "athena:GetNamedQuery",
                "athena:BatchGetNamedQuery",
                "athena:ListNamedQueries",
                "athena:DeleteNamedQuery",
                "athena:CreatePreparedStatement",
                "athena:GetPreparedStatement",
                "athena:ListPreparedStatements",
                "athena:UpdatePreparedStatement",
                "athena:DeletePreparedStatement"
            ],
            "Resource": "arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA"
        }
    ]
}
```

------

### 示例：基于标签键和标签值对拒绝对工作组的操作的策略块
<a name="tag-policy-examples-workgroups-basic"></a>

与资源（如工作组）关联的标签称作资源标签。利用资源标签，您可以编写如下所示的策略块，以拒绝对使用键-值对（如 `stack`、`production`）标记的任何工作组执行列出的操作。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "athena:GetWorkGroup",
                "athena:UpdateWorkGroup",
                "athena:DeleteWorkGroup",
                "athena:TagResource",
                "athena:UntagResource",
                "athena:ListTagsForResource",
                "athena:StartQueryExecution",
                "athena:GetQueryExecution",
                "athena:BatchGetQueryExecution",
                "athena:ListQueryExecutions",
                "athena:StopQueryExecution",
                "athena:GetQueryResults",
                "athena:GetQueryResultsStream",
                "athena:CreateNamedQuery",
                "athena:GetNamedQuery",
                "athena:BatchGetNamedQuery",
                "athena:ListNamedQueries",
                "athena:DeleteNamedQuery",
                "athena:CreatePreparedStatement",
                "athena:GetPreparedStatement",
                "athena:ListPreparedStatements",
                "athena:UpdatePreparedStatement",
                "athena:DeletePreparedStatement"
            ],
            "Resource": "arn:aws:athena:us-east-1:123456789012:workgroup/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/stack": "production"
                }
            }
        }
    ]
}
```

------

### 示例：限制对指定标签执行标签更改操作请求的策略块
<a name="tag-policy-examples-workgroups-restricted-specific"></a>

作为参数传入将更改标签的操作（例如，带标签的 `TagResource`、`UntagResource` 或 `CreateWorkGroup`）的标签称作请求标签。仅在传递的某个标签的键为 `costcenter` 且值为 `1`、`2` 或 `3` 时，以下示例策略块才允许 `CreateWorkGroup` 操作。

**注意**  
如果要允许 IAM 角色将标签作为 `CreateWorkGroup` 操作的一部分传入，请确保向角色授予执行 `TagResource` 和 `CreateWorkGroup` 操作的权限。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:CreateWorkGroup",
                "athena:TagResource"
            ],
            "Resource": "arn:aws:athena:us-east-1:123456789012:workgroup/*",
            "Condition": {
                "StringEquals": {
                    "aws:RequestTag/costcenter": [
                        "1",
                        "2",
                        "3"
                    ]
                }
            }
        }
    ]
}
```

------

## 数据目录的标签策略示例
<a name="tag-policy-examples-data-catalogs"></a>

### 示例：基本标记策略
<a name="tag-policy-examples-data-catalogs-basic"></a>

以下 IAM policy 允许您与名为 `datacatalogA` 的数据目录的标签进行交互：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:ListWorkGroups",
                "athena:ListEngineVersions",
                "athena:ListDataCatalogs",
                "athena:ListDatabases",
                "athena:GetDatabase",
                "athena:ListTableMetadata",
                "athena:GetTableMetadata"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:GetWorkGroup",
                "athena:TagResource",
                "athena:UntagResource",
                "athena:ListTagsForResource",
                "athena:StartQueryExecution",
                "athena:GetQueryExecution",
                "athena:BatchGetQueryExecution",
                "athena:ListQueryExecutions",
                "athena:StopQueryExecution",
                "athena:GetQueryResults",
                "athena:GetQueryResultsStream",
                "athena:CreateNamedQuery",
                "athena:GetNamedQuery",
                "athena:BatchGetNamedQuery",
                "athena:ListNamedQueries",
                "athena:DeleteNamedQuery"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:CreateDataCatalog",
                "athena:GetDataCatalog",
                "athena:UpdateDataCatalog",
                "athena:DeleteDataCatalog",
                "athena:ListDatabases",
                "athena:GetDatabase",
                "athena:ListTableMetadata",
                "athena:GetTableMetadata",
                "athena:TagResource",
                "athena:UntagResource",
                "athena:ListTagsForResource"
            ],
            "Resource": "arn:aws:athena:us-east-1:123456789012:datacatalog/datacatalogA"
        }
    ]
}
```

------

### 示例：基于标签键和标签值对拒绝对数据目录的操作的策略块
<a name="tag-policy-examples-data-catalogs-deny-actions"></a>

您可以使用资源标签编写策略块，以拒绝对使用特定标签键/值对标记的数据目录执行特定操作。以下示例策略拒绝对具有标签键/值对 `stack` `production` 的数据目录执行操作。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "athena:CreateDataCatalog",
                "athena:GetDataCatalog",
                "athena:UpdateDataCatalog",
                "athena:DeleteDataCatalog",
                "athena:GetDatabase",
                "athena:ListDatabases",
                "athena:GetTableMetadata",
                "athena:ListTableMetadata",
                "athena:StartQueryExecution",
                "athena:TagResource",
                "athena:UntagResource",
                "athena:ListTagsForResource"
            ],
            "Resource": "arn:aws:athena:us-east-1:123456789012:datacatalog/*",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/stack": "production"
                }
            }
        }
    ]
}
```

------

### 示例：限制对指定标签执行标签更改操作请求的策略块
<a name="tag-policy-examples-data-catalogs-action-specific-tags"></a>

作为参数传入将更改标签的操作（例如，带标签的 `TagResource`、`UntagResource` 或 `CreateDataCatalog`）的标签称作请求标签。仅在传递的某个标签的键为 `costcenter` 且值为 `1`、`2` 或 `3` 时，以下示例策略块才允许 `CreateDataCatalog` 操作。

**注意**  
如果要允许 IAM 角色将标签作为 `CreateDataCatalog` 操作的一部分传入，请确保向角色授予执行 `TagResource` 和 `CreateDataCatalog` 操作的权限。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:CreateDataCatalog",
                "athena:TagResource"
            ],
            "Resource": "arn:aws:athena:us-east-1:123456789012:datacatalog/*",
            "Condition": {
                "StringEquals": {
                    "aws:RequestTag/costcenter": [
                        "1",
                        "2",
                        "3"
                    ]
                }
            }
        }
    ]
}
```

------