

# Resource management and optimization in Amazon SNS
<a name="sns-resource-management-optimization"></a>

This topic provides guidance on how to leverage the full potential of Amazon SNS by ensuring optimal performance, reducing unnecessary costs, and maintaining well-organized resources.

**Topics**
+ [Tagging](sns-tags.md)

# Amazon SNS topic tagging
<a name="sns-tags"></a>

Amazon SNS supports tagging of Amazon SNS topics. This can help you track and manage the costs associated with your topics, provide enhanced security in your Amazon Identity and Access Management (IAM) policies, and lets you easily search or filter through thousands of topics. Tagging enables you to manage your Amazon SNS topics using Amazon Resource Groups. For more information on Resource Groups, see the [Amazon Resource Groups User Guide](https://docs.amazonaws.cn/ARG/latest/userguide/resource-groups.html).

## Tagging for cost allocation
<a name="tagging-for-cost-allocation"></a>

To organize and identify your Amazon SNS topics for cost allocation, you can add tags that identify the purpose of a topic. This is especially useful when you have many topics. You can use cost allocation tags to organize your Amazon bill to reflect your own cost structure. To do this, sign up to get your Amazon account bill to include the tag keys and values. For more information, see [Setting Up a Monthly Cost Allocation Report](https://docs.amazonaws.cn/awsaccountbilling/latest/aboutv2/configurecostallocreport.html#allocation-report) in the [Amazon Billing and Cost Management User Guide](https://docs.amazonaws.cn/awsaccountbilling/latest/aboutv2/billing-what-is.html).

For example, you can add tags that represent the cost center and purpose of your Amazon SNS topics, as follows:

[\[See the AWS documentation website for more details\]](http://docs.amazonaws.cn/en_us/sns/latest/dg/sns-tags.html)

This tagging scheme lets you to group two topics performing related tasks in the same cost center, while tagging an unrelated activity with a different cost allocation tag.

## Tagging for access control
<a name="sns-tagging-for-access-control"></a>

Amazon Identity and Access Management supports controlling access to resources based on tags. After tagging your resources, provide information about your resource tags in the condition element of an IAM policy to manage tag-based access. For information on how to tag your resources using the [Amazon SNS console](sns-tags-configuring.md#list-add-update-remove-tags-for-topic-aws-console) or the [Amazon SDK](sns-tags-configuring.md#tag-resource-aws-sdks), see [Configuring tags](sns-tags-configuring.md).

You can restrict access for an IAM identity. For example, you can restrict `Publish` and `PublishBatch` access to all Amazon SNS topics that include a tag with the key `environment` and the value `production`, while allowing access to all other Amazon SNS topics. In the example below, the policy restricts the ability to publish messages to topics tagged with `production`, while allowing messages to be published to topics tagged with `development`. For more information, see [Controlling Access Using Tags](https://docs.amazonaws.cn/IAM/latest/UserGuide/access_tags.html) in the IAM User Guide.

**Note**  
Setting the IAM permission for `Publish` sets permission for both `Publish` and `PublishBatch`.

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

****  

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

------

## Tagging for resource searching and filtering
<a name="sns-tagging-for-searching-filtering"></a>

An Amazon account can have tens of thousands of Amazon SNS topics (see [Amazon SNS Quotas](https://docs.amazonaws.cn/general/latest/gr/sns.html) for details). By tagging your topics, you can simplify the process of searching through or filtering out topics.

For example, you may have hundreds of topics associated with your production environment. Rather than having to manually search for these topics, you can query for all topics with a given tag:

```
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());
    }
}
```

# Configuring Amazon SNS topic tags
<a name="sns-tags-configuring"></a>

This topic explains how to configure tags for an [Amazon SNS topic](sns-tags.md) using the Amazon Web Services Management Console, an Amazon SDK, or the Amazon CLI.

**Important**  
Do not add personally identifiable information (PII) or other confidential or sensitive information in tags. Tags are accessible to other Amazon Web Services, including billing. Tags are not intended to be used for private or sensitive data.

## Listing, adding, and removing tags for an Amazon SNS topic using the Amazon Web Services Management Console
<a name="list-add-update-remove-tags-for-topic-aws-console"></a>

1. Sign in to the [Amazon SNS console](https://console.amazonaws.cn/sns/home).

1. On the navigation panel, choose **Topics**.

1. On the **Topics** page, choose a topic and then choose **Edit**.

1. Expand the **Tags** section.

   The tags added to the topic are listed.

1. Modify topic tags:
   + To add a tag, choose **Add tag** and enter a **Key** and **Value** (optional).
   + To remove a tag, choose **Remove tag** next to a key-value pair.

1. Choose **Save changes**.

## Adding tags to a topic using an Amazon SDK
<a name="tag-resource-aws-sdks"></a>

To use an Amazon SDK, you must configure it with your credentials. For more information, see [The shared config and credentials files](https://docs.amazonaws.cn/sdkref/latest/guide/creds-config-files.html) in the *Amazon SDKs and Tools Reference Guide*.

The following code examples show how to use `TagResource`.

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

**Amazon CLI**  
**To add a tag to a topic**  
The following `tag-resource` example adds a metadata tag to the specified Amazon SNS topic.  

```
aws sns tag-resource \
    --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --tags Key=Team,Value=Alpha
```
This command produces no output.  
+  For API details, see [TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/tag-resource.html) in *Amazon CLI Command Reference*. 

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

**SDK for Java 2.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](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);
        }
    }
}
```
+  For API details, see [TagResource](https://docs.amazonaws.cn/goto/SdkForJavaV2/sns-2010-03-31/TagResource) in *Amazon SDK for Java 2.x API Reference*. 

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

**SDK for Kotlin**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [Amazon Code Examples Repository](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")
    }
}
```
+  For API details, see [TagResource](https://sdk.amazonaws.com/kotlin/api/latest/index.html) in *Amazon SDK for Kotlin API reference*. 

------

## Managing tags with Amazon SNS API actions
<a name="manage-tags-with-sns-api-actions"></a>

To manage tags using the Amazon SNS API, use the following API actions:
+ [https://docs.amazonaws.cn/sns/latest/api/API_ListTagsForResource.html](https://docs.amazonaws.cn/sns/latest/api/API_ListTagsForResource.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_TagResource.html](https://docs.amazonaws.cn/sns/latest/api/API_TagResource.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_UntagResource.html](https://docs.amazonaws.cn/sns/latest/api/API_UntagResource.html)

## API actions that support ABAC
<a name="api-actions-that-support-abac"></a>

The following is a list of API actions that support attribute-based access control (ABAC). For more details about ABAC, see [What is ABAC for Amazon?](https://docs.amazonaws.cn/IAM/latest/UserGuide/introduction_attribute-based-access-control.html) in the *IAM User Guide*.
+ [https://docs.amazonaws.cn/sns/latest/api/API_AddPermission.html](https://docs.amazonaws.cn/sns/latest/api/API_AddPermission.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_ConfirmSubscription.html](https://docs.amazonaws.cn/sns/latest/api/API_ConfirmSubscription.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_DeleteTopic.html](https://docs.amazonaws.cn/sns/latest/api/API_DeleteTopic.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_GetDataProtectionPolicy.html](https://docs.amazonaws.cn/sns/latest/api/API_GetDataProtectionPolicy.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_GetSubscriptionAttributes.html](https://docs.amazonaws.cn/sns/latest/api/API_GetSubscriptionAttributes.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_GetTopicAttributes.html](https://docs.amazonaws.cn/sns/latest/api/API_GetTopicAttributes.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_ListSubscriptionsByTopic.html](https://docs.amazonaws.cn/sns/latest/api/API_ListSubscriptionsByTopic.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_ListTagsForResource.html](https://docs.amazonaws.cn/sns/latest/api/API_ListTagsForResource.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_Publish.html](https://docs.amazonaws.cn/sns/latest/api/API_Publish.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_PublishBatch.html](https://docs.amazonaws.cn/sns/latest/api/API_PublishBatch.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_PutDataProtectionPolicy.html](https://docs.amazonaws.cn/sns/latest/api/API_PutDataProtectionPolicy.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_RemovePermission.html](https://docs.amazonaws.cn/sns/latest/api/API_RemovePermission.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_SetSubscriptionAttributes.html](https://docs.amazonaws.cn/sns/latest/api/API_SetSubscriptionAttributes.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_SetTopicAttributes.html](https://docs.amazonaws.cn/sns/latest/api/API_SetTopicAttributes.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_Subscribe.html](https://docs.amazonaws.cn/sns/latest/api/API_Subscribe.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_TagResource.html](https://docs.amazonaws.cn/sns/latest/api/API_TagResource.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_Unsubscribe.html](https://docs.amazonaws.cn/sns/latest/api/API_Unsubscribe.html)
+ [https://docs.amazonaws.cn/sns/latest/api/API_UntagResource.html](https://docs.amazonaws.cn/sns/latest/api/API_UntagResource.html)