

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon SNS 主題標記
<a name="sns-tags"></a>

Amazon SNS 支援 Amazon SNS 主題的標記功能。這可協助您追蹤和管理與主題相關的成本、在 AWS Identity and Access Management (IAM) 政策中提供增強的安全性，並讓您輕鬆搜尋或篩選數千個主題。標記可讓您使用 AWS 資源群組管理 Amazon SNS 主題。如需 Resource Groups 的詳細資訊，請參閱《[AWS Resource Groups 使用者指南](https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html)》。

## 為分配成本加上標籤
<a name="tagging-for-cost-allocation"></a>

若要整理並識別 Amazon SNS 主題以分配成本，您可新增標籤來識別主題的用途。擁有許多主題時特別實用。您可以使用成本分配標籤來整理 AWS 帳單，以反映您自己的成本結構。若要這樣做，請註冊以取得 AWS 您的帳戶帳單，以包含標籤索引鍵和值。如需詳細資訊，請參閱《[AWS 帳單與成本管理使用者指南](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-what-is.html)》中的「[設定每月成本分配報告](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/configurecostallocreport.html#allocation-report)」。

例如，您可以新增代表成本中心和 Amazon SNS 主題之用途的標籤，如下所示：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sns/latest/dg/sns-tags.html)

這種標記機制可讓您將同一個成本中心內執行相關任務的兩個主題歸為同一組，並且使用不同的成本分配標籤來標記不相關的活動。

## 為存取控制加上標籤
<a name="sns-tagging-for-access-control"></a>

AWS Identity and Access Management 支援根據標籤控制對 資源的存取。標記資源後，請在 IAM 政策的條件元素中提供有關資源標籤的資訊來管理標籤型存取。如需有關如何使用 [Amazon SNS 主控台](sns-tags-configuring.md#list-add-update-remove-tags-for-topic-aws-console)或 [AWS SDK](sns-tags-configuring.md#tag-resource-aws-sdks) 來標記資源的資訊，請參閱[設定標籤](sns-tags-configuring.md)。

您可以限制 IAM 身分的存取。例如，您可以限制 `Publish` 和 `PublishBatch` 對所有包含索引鍵 `environment` 和 值 `production` 的 Amazon SNS 主題的存取，同時卻也可以允許對所有其他 Amazon SNS 主題的存取。在下方範例中，政策會限制發布訊息到標記為 `production` 之主題的能力，同時卻也會允許將消息發布到標記為 `development` 之主題。如需詳細資訊，請參閱《IAM 使用者指南》中的「[使用標籤控制存取](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html)」。

**注意**  
設定 IAM 許可以供 `Publish` 設定 `Publish` 和 `PublishBatch` 這兩者的許可。

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [{
    "Effect": "Deny",
    "Action": [
	"sns:Publish"
    ],
    "Resource": "arn:aws:sns:*:*:*",
    "Condition": {
      "StringEquals": {
        "aws:ResourceTag/environment": "production"
      }
    }
  },
  {
    "Effect": "Allow",
    "Action": [
      "sns:Publish"
    ],
    "Resource": "arn:aws:sns:*:*:*",
    "Condition": {
      "StringEquals": {
        "aws:ResourceTag/environment": "development"
      }
    }
  }]
}
```

------

## 為資源搜尋和過濾加上標籤
<a name="sns-tagging-for-searching-filtering"></a>

 AWS 帳戶可以有數萬個 Amazon SNS 主題 （如需詳細資訊，請參閱 [Amazon SNS 配額](https://docs.aws.amazon.com/general/latest/gr/sns.html))。標記主題後，您就可以簡化搜尋或篩選主題的過程。

例如，您可能會有數以百計個與生產環境關聯的主題。您可以查詢具有指定標籤的所有主題，而不必手動搜尋這些主題：

```
import com.amazonaws.services.resourcegroups.AWSResourceGroups;
import com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder;
import com.amazonaws.services.resourcegroups.model.QueryType;
import com.amazonaws.services.resourcegroups.model.ResourceQuery;
import com.amazonaws.services.resourcegroups.model.SearchResourcesRequest;
import com.amazonaws.services.resourcegroups.model.SearchResourcesResult;

public class Example {
    public static void main(String[] args) {
        // Query Amazon SNS Topics with tag "keyA" as "valueA"
        final String QUERY = "{\"ResourceTypeFilters\":[\"AWS::SNS::Topic\"],\"TagFilters\":[{\"Key\":\"keyA\", \"Values\":[\"valueA\"]}]}";

        // Initialize ResourceGroup client
        AWSResourceGroups awsResourceGroups = AWSResourceGroupsClientBuilder
            .standard()
            .build();

        // Query all resources with certain tags from ResourceGroups 
        SearchResourcesResult result = awsResourceGroups.searchResources(
            new SearchResourcesRequest().withResourceQuery(
                new ResourceQuery()
                .withType(QueryType.TAG_FILTERS_1_0)
                .withQuery(QUERY)
            ));
        System.out.println("SNS Topics with certain tags are " + result.getResourceIdentifiers());
    }
}
```

# 設定 Amazon SNS 主題標籤
<a name="sns-tags-configuring"></a>

本主題說明如何使用 、 AWS SDK 或 設定 [Amazon SNS 主題](sns-tags.md) AWS 管理主控台的標籤 AWS CLI。

**重要**  
請勿在標籤中加入個人身分識別資訊 (PII) 或其他機密或敏感資訊。其他 Amazon Web Services 可以存取標籤，包括帳單。標籤不適用於私有或敏感資料。

## 使用 列出、新增和移除 Amazon SNS 主題的標籤 AWS 管理主控台
<a name="list-add-update-remove-tags-for-topic-aws-console"></a>

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在導覽面板上，選擇 **Topics (主題)**。

1. 在 **Topics (主題)** 頁面上，選擇主題，然後選擇 **Delete (刪除)**。

1. 展開 **Tags (標籤)** 區段。

   隨即列出已新增到主題的標籤。

1. 修改主題標籤：
   + 若要新增標籤，請選擇 **Add tag** (新增標籤)，然後輸入 **Key** (索引鍵) 和 **Value** (值) (選用)。
   + 若要移除標籤，請選擇鍵/值對旁邊的 **Remove tag (移除標籤)**。

1. 選擇**儲存變更**。

## 使用 AWS SDK 將標籤新增至主題
<a name="tag-resource-aws-sdks"></a>

若要使用 AWS SDK，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS SDK和工具參考指南*中的[共享的配置和認證文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

下列程式碼範例示範如何使用 `TagResource`。

------
#### [ CLI ]

**AWS CLI**  
**將標籤新增至主題**  
下列 `tag-resource` 範例會將中繼資料標籤新增到指定的 Amazon SNS 主題。  

```
aws sns tag-resource \
    --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --tags Key=Team,Value=Alpha
```
此命令不會產生輸出。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/tag-resource.html)。

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中設定和執行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.Tag;
import software.amazon.awssdk.services.sns.model.TagResourceRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class AddTags {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn>

                Where:
                   topicArn - The ARN of the topic to which tags are added.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        addTopicTags(snsClient, topicArn);
        snsClient.close();
    }

    public static void addTopicTags(SnsClient snsClient, String topicArn) {
        try {
            Tag tag = Tag.builder()
                    .key("Team")
                    .value("Development")
                    .build();

            Tag tag2 = Tag.builder()
                    .key("Environment")
                    .value("Gamma")
                    .build();

            List<Tag> tagList = new ArrayList<>();
            tagList.add(tag);
            tagList.add(tag2);

            TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
                    .resourceArn(topicArn)
                    .tags(tagList)
                    .build();

            snsClient.tagResource(tagResourceRequest);
            System.out.println("Tags have been added to " + topicArn);

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  如需 API 詳細資訊，請參閱 *AWS SDK for Java 2.x API 參考*中的 [TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/TagResource)。

------
#### [ Kotlin ]

**適用於 Kotlin 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中設定和執行。

```
suspend fun addTopicTags(topicArn: String) {
    val tag =
        Tag {
            key = "Team"
            value = "Development"
        }

    val tag2 =
        Tag {
            key = "Environment"
            value = "Gamma"
        }

    val tagList = mutableListOf<Tag>()
    tagList.add(tag)
    tagList.add(tag2)

    val request =
        TagResourceRequest {
            resourceArn = topicArn
            tags = tagList
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.tagResource(request)
        println("Tags have been added to $topicArn")
    }
}
```
+  如需 API 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》**中的 [TagResource](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------

## 以 Amazon SNS API 動作管理標籤
<a name="manage-tags-with-sns-api-actions"></a>

若要使用 Amazon SNS API 管理標籤，請使用下列 API 動作：
+ [https://docs.aws.amazon.com/sns/latest/api/API_ListTagsForResource.html](https://docs.aws.amazon.com/sns/latest/api/API_ListTagsForResource.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_TagResource.html](https://docs.aws.amazon.com/sns/latest/api/API_TagResource.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_UntagResource.html](https://docs.aws.amazon.com/sns/latest/api/API_UntagResource.html)

## 支援 ABAC 的 API 動作
<a name="api-actions-that-support-abac"></a>

以下是支援屬性型存取控制 (ABAC) 的 API 動作列表。如需 ABAC 的詳細資訊，請參閱《*IAM 使用者指南*》中的[什麼是 ABAC AWS？](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_attribute-based-access-control.html)。
+ [https://docs.aws.amazon.com/sns/latest/api/API_AddPermission.html](https://docs.aws.amazon.com/sns/latest/api/API_AddPermission.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html](https://docs.aws.amazon.com/sns/latest/api/API_ConfirmSubscription.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_DeleteTopic.html](https://docs.aws.amazon.com/sns/latest/api/API_DeleteTopic.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_GetDataProtectionPolicy.html](https://docs.aws.amazon.com/sns/latest/api/API_GetDataProtectionPolicy.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_GetSubscriptionAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_GetSubscriptionAttributes.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_GetTopicAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_GetTopicAttributes.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptionsByTopic.html](https://docs.aws.amazon.com/sns/latest/api/API_ListSubscriptionsByTopic.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_ListTagsForResource.html](https://docs.aws.amazon.com/sns/latest/api/API_ListTagsForResource.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_Publish.html](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_PublishBatch.html](https://docs.aws.amazon.com/sns/latest/api/API_PublishBatch.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_PutDataProtectionPolicy.html](https://docs.aws.amazon.com/sns/latest/api/API_PutDataProtectionPolicy.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_RemovePermission.html](https://docs.aws.amazon.com/sns/latest/api/API_RemovePermission.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_SetTopicAttributes.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_TagResource.html](https://docs.aws.amazon.com/sns/latest/api/API_TagResource.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_Unsubscribe.html](https://docs.aws.amazon.com/sns/latest/api/API_Unsubscribe.html)
+ [https://docs.aws.amazon.com/sns/latest/api/API_UntagResource.html](https://docs.aws.amazon.com/sns/latest/api/API_UntagResource.html)