id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
sns-dg-021
|
sns-dg.pdf
| 21 |
"DataType": "String", "StringValue": "347c11c4-a22c-42e4-a6a2-9b5af5b76587", } }, ) print("\nPublished using Topic Resource:") fetch_and_print_from_sqs(sqs, demo_queue_url,topic) Large message payloads 68 Amazon Simple Notification Service Developer Guide # Below is the example to publish message using the SNS.PlatformEndpoint resource sns_extended_client_resource = SNSExtendedClientSession().resource( "sns", region_name="us-east-1" ) platform_endpoint = sns_extended_client_resource.PlatformEndpoint(sns_topic_arn) platform_endpoint.large_payload_support = s3_extended_payload_bucket # Change default s3_client attribute of platform_endpoint to use 'us-east-1' region platform_endpoint.s3_client = boto3.client("s3", region_name="us-east-1") platform_endpoint.always_through_s3 = True # Can Set custom S3 Keys to be used to store objects in S3 platform_endpoint.publish( Message="This message should be published to S3 using the PlatformEndpoint resource", MessageAttributes={ "S3Key": { "DataType": "String", "StringValue": "247c11c4-a22c-42e4-a6a2-9b5af5b76587", } }, ) print("\nPublished using PlatformEndpoint Resource:") fetch_and_print_from_sqs(sqs, demo_queue_url,platform_endpoint) Output Published using SNS extended client: Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx"}] Message Stored in S3 Bucket is: This message should be published to S3 Using decreased message size threshold: Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx"}] Message Stored in S3 Bucket is: This message should be published to S3 as it exceeds the limit of the 32 bytes Published using Topic Resource: Large message payloads 69 Amazon Simple Notification Service Developer Guide Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx"}] Message Stored in S3 Bucket is: This message should be published to S3 using the topic resource Published using PlatformEndpoint Resource: Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx"}] Message Stored in S3 Bucket is: This message should be published to S3 using the PlatformEndpoint resource Amazon SNS message attributes Amazon SNS supports delivery of message attributes, which let you provide structured metadata items (such as timestamps, geospatial data, signatures, and identifiers) about the message. For SQS subscriptions, a maximum of 10 message attributes can be sent when Raw Message Delivery is enabled. To send more than 10 message attributes, Raw Message Delivery must be disabled. Messages with more than 10 message attributes directed towards Raw Message Delivery enabled Amazon SQS subscriptions will be discarded as client side errors. Message attributes are optional and separate from—but are sent together with—the message body. The receiver can use this information to decide how to handle the message without having to process the message body first. For information about sending messages with attributes using the AWS Management Console or the AWS SDK for Java, see the To publish messages to Amazon SNS topics using the AWS Management Console tutorial. Note Message attributes are sent only when the message structure is String, not JSON. You can also use message attributes to help structure the push notification message for mobile endpoints. In this scenario, the message attributes are used only to help structure the push notification message. The attributes are not delivered to the endpoint as they are when sending messages with message attributes to Amazon SQS endpoints. Message attributes 70 Amazon Simple Notification Service Developer Guide You can also use message attributes to make your messages filterable using subscription filter policies. You can apply filter policies to topic subscriptions. When a filter policy is applied with filter policy scope set to MessageAttributes (default), a subscription receives only those messages that have attributes that the policy accepts. For more information, see Amazon SNS message filtering. Note When message attributes are used for filtering, the value must be a valid JSON string. Doing this ensures that the message is delivered to a subscription with message attributes filtering enabled. Message attribute items and validation Each message attribute consists of the following items: • Name – The message attribute name can contain the following characters: A-Z, a-z, 0-9, underscore(_), hyphen(-), and period (.). The name must not start or end with a period, and it should not have successive periods. The name is case-sensitive and must be unique among all attribute names for the message. The name can be up to 256 characters long. The name cannot start with AWS. or Amazon. (or any variations in casing) because these prefixes are reserved for use by Amazon Web Services. • Type – The supported message attribute data types are String, String.Array, Number, and Binary. The data type has the same restrictions on the content as the message body. For more information, see the Message attribute data types and validation section. • Value – The user-specified message attribute value. For string data types, the value attribute must follow the same content restrictions as the message body. However, if the message attribute is used for filtering, the value must be a valid JSON string to ensure compatibility with Amazon SNS subscription filter policies. For more information, see the Publish action in the Amazon Simple Notification Service API Reference. Name, type, and value must not be empty or null. In addition, the message body should not be empty or null. All parts of the message attribute, including name, type, and value, are included in the message size restriction, which is 256
|
sns-dg-022
|
sns-dg.pdf
| 22 |
For string data types, the value attribute must follow the same content restrictions as the message body. However, if the message attribute is used for filtering, the value must be a valid JSON string to ensure compatibility with Amazon SNS subscription filter policies. For more information, see the Publish action in the Amazon Simple Notification Service API Reference. Name, type, and value must not be empty or null. In addition, the message body should not be empty or null. All parts of the message attribute, including name, type, and value, are included in the message size restriction, which is 256 KB. Message attributes 71 Amazon Simple Notification Service Developer Guide Message attribute data types and validation Message attribute data types identify how the message attribute values are handled by Amazon SNS. For example, if the type is a number, Amazon SNS validates that it's a number. Amazon SNS supports the following logical data types for all endpoints except as noted: • String – Strings are Unicode with UTF-8 binary encoding. For a list of code values, see http:// en.wikipedia.org/wiki/ASCII#ASCII_printable_characters. Note Surrogate values are not supported in the message attributes. For example, using a surrogate value to represent an emoji will give you the following error: Invalid attribute value was passed in for message attribute. • String.Array – An array, formatted as a string, that can contain multiple values. The values can be strings, numbers, or the keywords true, false, and null. A String.Array of number or boolean type does not require quotes. Multiple String.Array values are separated by commas. This data type isn't supported for AWS Lambda subscriptions. If you specify this data type for Lambda endpoints, it's passed as the String data type in the JSON payload that Amazon SNS delivers to Lambda. • Number – Numbers are positive or negative integers or floating-point numbers. Numbers have sufficient range and precision to encompass most of the possible values that integers, floats, and doubles typically support. A number can have a value from -109 to 109, with 5 digits of accuracy after the decimal point. Leading and trailing zeroes are trimmed. This data type isn't supported for AWS Lambda subscriptions. If you specify this data type for Lambda endpoints, it's passed as the String data type in the JSON payload that Amazon SNS delivers to Lambda. • Binary – Binary type attributes can store any binary data; for example, compressed data, encrypted data, or images. Reserved message attributes for mobile push notifications The following table lists the reserved message attributes for mobile push notification services that you can use to structure your push notification message: Message attributes 72 Amazon Simple Notification Service Developer Guide Push notification service Reserved message attribute ADM APNs1 AWS.SNS.MOBILE.ADM.TTL AWS.SNS.MOBILE.APNS_MDM.TTL AWS.SNS.MOBILE.APNS_MDM_SANDBOX.TTL AWS.SNS.MOBILE.APNS_PASSBOOK.TTL AWS.SNS.MOBILE.APNS_PASSBOOK_SANDBOX.TTL AWS.SNS.MOBILE.APNS_SANDBOX.TTL AWS.SNS.MOBILE.APNS_VOIP.TTL AWS.SNS.MOBILE.APNS_VOIP_SANDBOX.TTL AWS.SNS.MOBILE.APNS.COLLAPSE_ID AWS.SNS.MOBILE.APNS.PRIORITY AWS.SNS.MOBILE.APNS.PUSH_TYPE AWS.SNS.MOBILE.APNS.TOPIC AWS.SNS.MOBILE.APNS.TTL Baidu AWS.SNS.MOBILE.BAIDU.DeployStatus AWS.SNS.MOBILE.BAIDU.MessageKey AWS.SNS.MOBILE.BAIDU.MessageType AWS.SNS.MOBILE.BAIDU.TTL FCM AWS.SNS.MOBILE.FCM.TTL AWS.SNS.MOBILE.GCM.TTL macOS AWS.SNS.MOBILE.MACOS_SANDBOX.TTL Message attributes 73 Amazon Simple Notification Service Developer Guide Push notification service Reserved message attribute AWS.SNS.MOBILE.MACOS.TTL MPNS AWS.SNS.MOBILE.MPNS.NotificationClass AWS.SNS.MOBILE.MPNS.TTL AWS.SNS.MOBILE.MPNS.Type WNS AWS.SNS.MOBILE.WNS.CachePolicy AWS.SNS.MOBILE.WNS.Group AWS.SNS.MOBILE.WNS.Match AWS.SNS.MOBILE.WNS.SuppressPopup AWS.SNS.MOBILE.WNS.Tag AWS.SNS.MOBILE.WNS.TTL AWS.SNS.MOBILE.WNS.Type 1 Apple will reject Amazon SNS notifications if message attributes do not meet their requirements. For additional details, see Sending Notification Requests to APNs on the Apple Developer website. Amazon SNS message batching What is message batching? An alternative to publishing messages to either Standard or FIFO topics in individual Publish API requests, is using the Amazon SNS PublishBatch API to publish up to 10 messages in a single API request. Sending messages in batches can help you reduce the costs associated with connecting distributed applications (A2A messaging) or sending notifications to people (A2P messaging) with Amazon SNS by a factor of up to 10. Amazon SNS has quotas on how many messages you can publish to a topic per second based on the region in which you operate. See the Amazon SNS endpoints and quotas page in the AWS General Reference guide for more information on API quotas. Message batching 74 Amazon Simple Notification Service Developer Guide Note The total aggregate size of all messages that you send in a single PublishBatch API request can’t exceed 262,144 bytes (256 KiB). The PublishBatch API uses the same Publish API action for IAM policies. How does message batching work? Publishing messages with the PublishBatch API is similar to publishing messages with the Publish API. The main difference is that each message within a PublishBatch API request needs to be assigned a unique batch ID (up to 80 characters). This way, Amazon SNS can return individual API responses for every message within a batch to confirm that each message was either published or that a failure occurred. For messages being published to FIFO topics, in addition to including assigning a unique batch ID, you still need to include a MessageDeduplicationID and MessageGroupId for each individual message. Examples Publishing a
|
sns-dg-023
|
sns-dg.pdf
| 23 |
work? Publishing messages with the PublishBatch API is similar to publishing messages with the Publish API. The main difference is that each message within a PublishBatch API request needs to be assigned a unique batch ID (up to 80 characters). This way, Amazon SNS can return individual API responses for every message within a batch to confirm that each message was either published or that a failure occurred. For messages being published to FIFO topics, in addition to including assigning a unique batch ID, you still need to include a MessageDeduplicationID and MessageGroupId for each individual message. Examples Publishing a batch of 10 messages to a Standard topic // Imports import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishBatchRequest; import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry; import software.amazon.awssdk.services.sns.model.PublishBatchResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; // Code private static final int MAX_BATCH_SIZE = 10; public static void publishBatchToTopic(SnsClient snsClient, String topicArn, int batchSize) { try { // Validate the batch size if (batchSize > MAX_BATCH_SIZE) { Message batching 75 Amazon Simple Notification Service Developer Guide throw new IllegalArgumentException("Batch size cannot exceed " + MAX_BATCH_SIZE); } // Create the batch entries List<PublishBatchRequestEntry> entries = IntStream.range(0, batchSize) .mapToObj(i -> PublishBatchRequestEntry.builder() .id("id" + i) .message("message" + i) .build()) .collect(Collectors.toList()); // Build the batch request PublishBatchRequest request = PublishBatchRequest.builder() .topicArn(topicArn) .publishBatchRequestEntries(entries) .build(); // Publish the batch request PublishBatchResponse response = snsClient.publishBatch(request); // Handle successful messages response.successful().forEach(success -> { System.out.println("Successful Batch Id: " + success.id()); System.out.println("Message Id: " + success.messageId()); }); // Handle failed messages response.failed().forEach(failure -> { System.err.println("Failed Batch Id: " + failure.id()); System.err.println("Error Code: " + failure.code()); System.err.println("Sender Fault: " + failure.senderFault()); System.err.println("Error Message: " + failure.message()); }); } catch (SnsException e) { // Log and handle exceptions System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage()); } catch (IllegalArgumentException e) { System.err.println("Validation Error: " + e.getMessage()); } } Message batching 76 Amazon Simple Notification Service Developer Guide Publishing a batch of 10 messages to a FIFO topic // Imports import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishBatchRequest; import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry; import software.amazon.awssdk.services.sns.model.PublishBatchResponse; import software.amazon.awssdk.services.sns.model.BatchResultErrorEntry; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; // Code private static final int MAX_BATCH_SIZE = 10; public static void publishBatchToFifoTopic(SnsClient snsClient, String topicArn) { try { // Create the batch entries to send List<PublishBatchRequestEntry> entries = IntStream.range(0, MAX_BATCH_SIZE) .mapToObj(i -> PublishBatchRequestEntry.builder() .id("id" + i) .message("message" + i) .messageGroupId("groupId") .messageDeduplicationId("deduplicationId" + i) .build()) .collect(Collectors.toList()); // Create the batch request PublishBatchRequest request = PublishBatchRequest.builder() .topicArn(topicArn) .publishBatchRequestEntries(entries) .build(); // Publish the batch request PublishBatchResponse response = snsClient.publishBatch(request); // Handle the successfully sent messages response.successful().forEach(success -> { System.out.println("Batch Id for successful message: " + success.id()); System.out.println("Message Id for successful message: " + success.messageId()); Message batching 77 Amazon Simple Notification Service Developer Guide System.out.println("Sequence Number for successful message: " + success.sequenceNumber()); }); // Handle the failed messages response.failed().forEach(failure -> { System.err.println("Batch Id for failed message: " + failure.id()); System.err.println("Error Code for failed message: " + failure.code()); System.err.println("Sender Fault for failed message: " + failure.senderFault()); System.err.println("Failure Message for failed message: " + failure.message()); }); } catch (SnsException e) { // Handle any exceptions from the request System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage()); } } Deleting an Amazon SNS topic and subscription When a topic is deleted, its associated subscriptions are deleted asynchronously. While customers can still access these subscriptions, the subscriptions are no longer associated with the topic–even if you recreate the topic using the same name. If a publisher attempts to publish a message to the deleted topic, the publisher will receive an error message indicating that the topic doesn't exist. Similarly, any attempt to subscribe to the deleted topic will also result in an error message. You can't delete a subscription that's pending confirmation. Amazon SNS automatically deletes unconfirmed subscriptions after 48 hours. To delete an Amazon SNS topic or subscription using the AWS Management Console Deleting an Amazon SNS topic or subscription ensures efficient resource management, preventing unnecessary usage and keeping the Amazon SNS console organized. This step helps avoid potential costs from idle resources and streamlines administration by removing topics or subscriptions that are no longer needed. Step 4: Deleting a subscription and topic 78 Amazon Simple Notification Service Developer Guide To delete a topic using the AWS Management Console 1. 2. Sign in to the Amazon SNS console. In the left navigation pane, choose Topics. 3. On the Topics page, select a topic, and then choose Delete. 4. In the Delete topic dialog box, enter delete me, and then choose Delete. The console deletes the topic. To delete a subscription using the AWS Management Console 1. 2. Sign in to the Amazon SNS console. In the left navigation pane, choose Subscriptions. 3. On the Subscriptions page, select a subscription with a status of Confirmed, and then choose Delete. 4. In the Delete subscription dialog box, choose Delete. The console deletes the subscription. To delete a subscription and topic using an AWS SDK To use an AWS SDK,
|
sns-dg-024
|
sns-dg.pdf
| 24 |
the Topics page, select a topic, and then choose Delete. 4. In the Delete topic dialog box, enter delete me, and then choose Delete. The console deletes the topic. To delete a subscription using the AWS Management Console 1. 2. Sign in to the Amazon SNS console. In the left navigation pane, choose Subscriptions. 3. On the Subscriptions page, select a subscription with a status of Confirmed, and then choose Delete. 4. In the Delete subscription dialog box, choose Delete. The console deletes the subscription. To delete a subscription and topic using an AWS SDK To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide. The following code examples show how to use DeleteTopic. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Delete a topic by its topic ARN. AWS SDKs 79 Amazon Simple Notification Service Developer Guide /// <summary> /// Delete a topic by its topic ARN. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteTopicByArn(string topicArn) { var deleteResponse = await _amazonSNSClient.DeleteTopicAsync( new DeleteTopicRequest() { TopicArn = topicArn }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteTopic in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Delete an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::deleteTopic(const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::DeleteTopicRequest request; request.SetTopicArn(topicARN); AWS SDKs 80 Amazon Simple Notification Service Developer Guide const Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted the Amazon SNS topic " << topicARN << std::endl; } else { std::cerr << "Error deleting topic " << topicARN << ":" << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see DeleteTopic in AWS SDK for C++ API Reference. CLI AWS CLI To delete an SNS topic The following delete-topic example deletes the specified SNS topic. aws sns delete-topic \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" This command produces no output. • For API details, see DeleteTopic in AWS CLI Command Reference. AWS SDKs 81 Amazon Simple Notification Service Developer Guide Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // DeleteTopic delete an Amazon SNS topic. func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error { _, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{ TopicArn: aws.String(topicArn)}) if err != nil { log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err) } return err } AWS SDKs 82 Amazon Simple Notification Service Developer Guide • For API details, see DeleteTopic in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * 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 DeleteTopic { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to delete. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } AWS SDKs 83 Amazon Simple Notification Service Developer Guide String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Deleting a topic with name: " + topicArn); deleteSNSTopic(snsClient, topicArn); snsClient.close(); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see DeleteTopic in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. AWS SDKs 84 Amazon Simple Notification Service Developer Guide import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it
|
sns-dg-025
|
sns-dg.pdf
| 25 |
= snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see DeleteTopic in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. AWS SDKs 84 Amazon Simple Notification Service Developer Guide import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { DeleteTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to delete. */ export const deleteTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new DeleteTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'a10e2886-5a8f-5114-af36-75bd39498332', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteTopic in AWS SDK for JavaScript API Reference. AWS SDKs 85 Amazon Simple Notification Service Developer Guide Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteSNSTopic(topicArnVal: String) { val request = DeleteTopicRequest { topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.deleteTopic(request) println("$topicArnVal was successfully deleted.") } } • For API details, see DeleteTopic in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; AWS SDKs 86 Amazon Simple Notification Service Developer Guide /** * Deletes an SNS topic and all its subscriptions. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->deleteTopic([ 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see DeleteTopic in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: AWS SDKs 87 Amazon Simple Notification Service Developer Guide """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def delete_topic(topic): """ Deletes a topic. All subscriptions to the topic are also deleted. """ try: topic.delete() logger.info("Deleted topic %s.", topic.arn) except ClientError: logger.exception("Couldn't delete topic %s.", topic.arn) raise • For API details, see DeleteTopic in AWS SDK for Python (Boto3) API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->deletetopic( iv_topicarn = iv_topic_arn ). MESSAGE 'SNS topic deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. AWS SDKs 88 Amazon Simple Notification Service Developer Guide • For API details, see DeleteTopic in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) _ = try await snsClient.deleteTopic( input: DeleteTopicInput(topicArn: arn) ) • For API details, see DeleteTopic in AWS SDK for Swift API reference. Next steps Now that you've created a topic with a subscription and sent messages to the topic, you might want to try the following: • Explore the AWS Developer Center. • Learn about protecting your data in the Security section. • Enable server-side encryption for a topic. • Enable server-side encryption for a topic with an encrypted Amazon Simple Queue Service (Amazon SQS) queue subscribed. • Subscribe AWS Event Fork Pipelines to a topic. Next steps 89 Amazon Simple Notification Service Developer Guide Message ordering and deduplication strategies using Amazon SNS FIFO topics This topic provides information of the features and functionalities of Amazon SNS FIFO (First- In-First-Out) topics and how they integrate with Amazon SQS FIFO queues. You'll learn how to use these services together to
|
sns-dg-026
|
sns-dg.pdf
| 26 |
AWS Developer Center. • Learn about protecting your data in the Security section. • Enable server-side encryption for a topic. • Enable server-side encryption for a topic with an encrypted Amazon Simple Queue Service (Amazon SQS) queue subscribed. • Subscribe AWS Event Fork Pipelines to a topic. Next steps 89 Amazon Simple Notification Service Developer Guide Message ordering and deduplication strategies using Amazon SNS FIFO topics This topic provides information of the features and functionalities of Amazon SNS FIFO (First- In-First-Out) topics and how they integrate with Amazon SQS FIFO queues. You'll learn how to use these services together to ensure strict message ordering and deduplication, essential for applications that require data consistency. This content covers the specific use cases where Amazon SNS FIFO topics are beneficial, providing insight into scenarios where message order and uniqueness are critical. You'll also learn about the technical details of message ordering, message grouping, and how these affect message delivery. The message deduplication topic explains the mechanisms that prevent duplicate messages, ensuring that each message is processed only once. Additionally, you'll learn about message filtering, security, and durability, which are important for maintaining the integrity and reliability of your messaging system. This content also includes information on message archiving and replay, offering strategies for managing message histories. Practical code examples are also provided to help you implement these features in your own applications, giving you hands- on experience with Amazon SNS FIFO topics and their integration with Amazon SQS FIFO queues. High throughput FIFO topics in Amazon SNS High throughput FIFO topics in Amazon SNS efficiently manage high message throughput while maintaining strict message order, ensuring reliability and scalability for applications processing numerous messages. This solution is ideal for scenarios demanding both high throughput and ordered message delivery. To improve message throughput using high throughput FIFO topics, increasing the number of message groups is recommended. For more information on high throughput message quotas, see Amazon SNS service quotas in the Amazon Web Services General Reference. Use cases for high throughput for Amazon SNS FIFO topics The following use cases highlight the diverse applications of high throughput FIFO topics, showcasing their effectiveness across industries and scenarios: • Real-time data processing: Applications dealing with real-time data streams, such as event processing or telemetry data ingestion, can benefit from high throughput FIFO topics to handle the continuous influx of messages while preserving their order for accurate analysis. High throughput FIFO topics 90 Amazon Simple Notification Service Developer Guide • E-commerce order processing: In e-commerce platforms where maintaining the order of customer transactions is critical, high throughput FIFO topics ensure that orders are delivered sequentially and without delays, even during peak shopping seasons. • Financial services: Financial institutions handling high-frequency trading or transactional data rely on high throughput FIFO topics to process market data and transactions with minimal latency while adhering to strict regulatory requirements for message ordering. • Media streaming: Streaming platforms and media distribution services utilize high throughput FIFO topics to manage the delivery of media files and streaming content, ensuring smooth playback experiences for users while maintaining the correct order of content delivery Partitions and data distribution for high throughput for Amazon SNS FIFO topics With high throughput topics, Amazon SNS distributes FIFO topic data across partitions. A partition is an allocation of capacity for a topic that is automatically replicated across multiple Availability Zones within an AWS Region. You don't manage partitions. Instead, Amazon SNS automatically manages partitions on your behalf, based on the ingress rate. For FIFO topics, Amazon SNS modifies the number of partitions in a topic in the following situations: • If the current publish rate approaches or exceeds what the existing partitions can support, additional partitions are allocated until the topic reaches the regional quota. For information on quotas, see Amazon SNS service quotas in the Amazon Web Services General Reference. • If the current partitions have low utilization, the number of partitions may be reduced. Partition management occurs automatically in the background and is transparent to your applications. Your topic and messages are available at all times. Note Temporary Publish API throttling may occur if you suddenly and significantly increase traffic to your topic while sending multiple times the usual volume. This throttling can last up to the duration of the deduplication window while the topic scales up to accommodate the increased traffic. Partitions and data distribution 91 Amazon Simple Notification Service Developer Guide Distributing data by message group IDs When publishing a message to a FIFO topic, Amazon SNS uses the value of each message’s message group ID as input to an internal hash function. The output value from the hash function determines which partition processes the message, one or more message group IDs may be handled by a given partition. Note Amazon SNS is optimized for uniform
|
sns-dg-027
|
sns-dg.pdf
| 27 |
usual volume. This throttling can last up to the duration of the deduplication window while the topic scales up to accommodate the increased traffic. Partitions and data distribution 91 Amazon Simple Notification Service Developer Guide Distributing data by message group IDs When publishing a message to a FIFO topic, Amazon SNS uses the value of each message’s message group ID as input to an internal hash function. The output value from the hash function determines which partition processes the message, one or more message group IDs may be handled by a given partition. Note Amazon SNS is optimized for uniform distribution of items across a FIFO topic's partitions, regardless of the number of partitions. AWS recommends that you use message group IDs that can have a large number of distinct values. Enable high throughput on your Amazon SNS FIFO topic By default Amazon SNS FIFO topics are configured for topic-level deduplication, this is controlled by the topic attribute FifoThroughputScope set to Topic and have more restricted throughput quotas, see Amazon SNS service quotas in the Amazon Web Services General Reference. To enable high throughput for your Amazon SNS FIFO topic, update the FifoThroughputScope attribute to MessageGroup. This change can be done through the console or using the AWS CLI and SDK, and can also be set during topic creation, which Amazon SNS recommends for the best customer experience and to reduce the chances of your topic being throttled. Important Once you've enabled a topic's FifoThroughputScope to MessageGroup, it cannot be reverted back to the Topic throughput. Enable high throughput mode for any subscribed Amazon SQS FIFO queue When publishing to your Amazon SNS FIFO topic with high throughput enabled, and one or more Amazon SQS FIFO queues are subscribed, it is recommended that you enable high throughput on your Amazon SQS FIFO queues to enable your Amazon SNS FIFO high throughput topic to deliver Partitions and data distribution 92 Amazon Simple Notification Service Developer Guide smoothly. For more see High throughput for FIFO queues in the Amazon Simple Queue Service Developer Guide. Amazon SNS FIFO topic example use case The following example describes an ecommerce platform built by an auto parts manufacturer using Amazon SNS FIFO topics and Amazon SQS queues. The platform is composed of four serverless applications: • Inventory managers use a price management application to set the price for each item in stock. At this company, product prices can change based on currency exchange fluctuation, market demand, and shifts in sales strategy. The price management application uses an AWS Lambda function that publishes price updates to an Amazon SNS FIFO topic whenever prices change. • A wholesale application provides the backend for a website where auto body shops and car manufacturers can buy the company's auto parts in bulk. To get price change notifications, the wholesale application subscribes its Amazon SQS FIFO queue to the price management application's Amazon SNS FIFO topic. • A retail application provides the backend for another website where car owners and car tuning enthusiasts can purchase individual auto parts for their vehicles. To get price change notifications, the retail application also subscribes its Amazon SQS FIFO queue to the price management application's Amazon SNS FIFO topic. • An analytics application that aggregates price updates and stores them into an Amazon S3 bucket, enabling Amazon Athena to query the bucket for business intelligence (BI) purposes. To get price change notifications, the analytics application subscribes its Amazon SQS standard queue to the price management application's Amazon SNS FIFO topic. Unlike the other applications, the analytics one doesn't require the price updates to be strictly ordered. FIFO topic use case 93 Amazon Simple Notification Service Developer Guide For the wholesale and retail applications to receive price updates in the correct order, the price management application must use a strictly ordered message distribution system. Using Amazon SNS FIFO topics and Amazon SQS FIFO queues enables the processing of messages in order and with no duplication. For more information, see Amazon SNS message ordering details for FIFO topics. For code snippets that implement this use case, see Amazon SNS code examples for FIFO topics. Amazon SNS message ordering details for FIFO topics An Amazon SNS FIFO topic always delivers messages to subscribed Amazon SQS queues in the exact order in which the messages are published to the topic, and only once. With an Amazon SQS FIFO queue subscribed, the consumer of the queue receives the messages in the exact order in which the messages are delivered to the queue, and no duplicates. With an Amazon SQS standard queue subscribed, however, the consumer of the queue may receive messages out of order, and more than once. This enables further decoupling of subscribers from publishers, giving subscribers more flexibility in terms of message consumption and cost optimization, as shown
|
sns-dg-028
|
sns-dg.pdf
| 28 |
always delivers messages to subscribed Amazon SQS queues in the exact order in which the messages are published to the topic, and only once. With an Amazon SQS FIFO queue subscribed, the consumer of the queue receives the messages in the exact order in which the messages are delivered to the queue, and no duplicates. With an Amazon SQS standard queue subscribed, however, the consumer of the queue may receive messages out of order, and more than once. This enables further decoupling of subscribers from publishers, giving subscribers more flexibility in terms of message consumption and cost optimization, as shown in the following diagram, based on the Amazon SNS FIFO topic example use case. Message ordering details 94 Amazon Simple Notification Service Developer Guide Note that there is no implied ordering of the subscribers. The following example shows that message m1 is delivered first to the wholesale subscriber and then to the retail subscriber and then to the analytics subscriber. Message m2 is delivered first to the retail subscriber and then to the wholesale subscriber and finally to the analytics subscriber. Though the two messages are delivered to the subscribers in a different order, message ordering is preserved for each Amazon SQS FIFO subscriber. Each subscriber is perceived in isolation from any other subscribers. Message ordering details 95 Amazon Simple Notification Service Developer Guide If an Amazon SQS queue subscriber becomes unreachable, it can get out of sync. For example, say the wholesale application queue owner mistakenly changes the Amazon SQS queue policy in a way that prevents the Amazon SNS service principal from delivering messages to the queue. In this case, price update deliveries to the wholesale queue fail, while the ones to the retail and analytics queues succeed, causing the subscribers to be out of sync. When the wholesale application queue owner corrects its queue policy, Amazon SNS resumes delivering messages to the subscribed queue. Any messages published to the topic that target the incorrectly configured queue are dropped, unless the corresponding subscription has a dead-letter queue configured. Message ordering details 96 Amazon Simple Notification Service Developer Guide You can have multiple applications (or multiple threads within the same application) publishing messages to an SNS FIFO topic in parallel. When you do this, you effectively delegate message sequencing to the Amazon SNS service. To determine the established sequence of messages, you can check the sequence number. The sequence number is a large, non-consecutive number that Amazon SNS assigns to each message. The length of the sequence number is 128-bits, and continues to increase for each Message Group. The sequence number is passed to the subscribed Amazon SQS queues as part of the message body. However, if you enable raw message delivery, the message that's delivered to the Amazon SQS queue doesn't include the sequence number or any other Amazon SNS message metadata. Message ordering details 97 Amazon Simple Notification Service Developer Guide Amazon SNS FIFO topics define ordering in the context of a message group. For more information, see Amazon SNS message grouping for FIFO topics. Amazon SNS message grouping for FIFO topics Messages that belong to the same group are processed one by one, in a strict order relative to the group. When you publish messages to an Amazon SNS FIFO topic, you set the message group ID. The group ID is a mandatory token that specifies that a message belongs to a specific message group. The SNS FIFO topic passes the group ID to the subscribed Amazon SQS FIFO queues. There is no limit to the number of group IDs in SNS FIFO topics or SQS FIFO queues. Message group ID is not passed to Amazon SQS standard queues. There's no affinity between a message group and a subscription. Therefore, messages that are published to any message group are delivered to all subscribed queues, subject to any filter policies attached to subscriptions. For more information, see Amazon SNS message delivery for FIFO topics and Amazon SNS message filtering for FIFO topics. In the auto parts price management example use case, there's a dedicated message group for each product sold in the platform. The same Amazon SNS FIFO topic is used for processing all price updates. The sequence of price updates is preserved within the context of a single auto parts product, but not across multiple products. The following diagram shows how this works. Notice that, for the product whose message group ID is product-214, message m1 is processed before Message grouping 98 Amazon Simple Notification Service Developer Guide m4. This sequence is preserved throughout the workflows that use Amazon SNS FIFO to Amazon SQS FIFO. Likewise, for the product whose message group ID is product-799, message m2 is processed before m3. However, when using Amazon SQS standard queues, the message order is no longer guaranteed, and
|
sns-dg-029
|
sns-dg.pdf
| 29 |
sequence of price updates is preserved within the context of a single auto parts product, but not across multiple products. The following diagram shows how this works. Notice that, for the product whose message group ID is product-214, message m1 is processed before Message grouping 98 Amazon Simple Notification Service Developer Guide m4. This sequence is preserved throughout the workflows that use Amazon SNS FIFO to Amazon SQS FIFO. Likewise, for the product whose message group ID is product-799, message m2 is processed before m3. However, when using Amazon SQS standard queues, the message order is no longer guaranteed, and message groups do not exist. The product-214 and product-799 message groups are independent of each other, so there is no relationship between how their messages are sequenced. Distributing data by message group IDs for improved performance To optimize delivery throughput, Amazon SNS FIFO topics deliver messages from different message groups in parallel, while message order is strictly maintained within each message group. Each individual message group can deliver a maximum of 300 messages per second. Therefore, to achieve high throughput for a single topic, use a large number of distinct message group IDs. By utilizing a diverse set of message groups, Amazon SNS FIFO topics automatically distributes messages across a larger number of parallel partitions. Distributing data by message group IDs for improved performance 99 Amazon Simple Notification Service Developer Guide Note Amazon SNS FIFO topics are optimized for uniform distribution of messages across message group IDs, regardless of the number of groups. AWS recommends that you use a large number of distinct message group IDs for optimized performance. When publishing to your Amazon SNS FIFO topic with high throughput and one or more Amazon SQS FIFO queues are subscribed, it is recommended that you enable high throughput on your queues. For more see High throughput for FIFO queues in the Amazon Simple Queue Service Developer Guide. Amazon SNS message delivery for FIFO topics Amazon SNS FIFO (first in, first out) topics support delivery to both Amazon SQS standard and FIFO queues to provide customers with flexibility and control when integrating distributed applications that require data consistency in near real-time. For workloads that need to preserve strict message ordering or de-duplication, the combination of Amazon SNS FIFO topics with Amazon SQS FIFO queues subscribed as the delivery endpoint provides enhance messaging between applications when the order of operations and events is critical, or where duplicates can’t be tolerated. For workloads that tolerate best-effort ordering and at-least-once delivery, subscribing Amazon SQS standard queues to Amazon SNS FIFO topics provides the ability to lower costs, in addition to sharing queues across workloads that don't utilize FIFO. Note To fan out messages from Amazon SNS FIFO topics to AWS Lambda functions, extra steps are required. First, subscribe Amazon SQS FIFO or standard queues to the topic. Then configure the queues to trigger the functions. For more information, see the SQS FIFO as an event source post on the AWS Compute Blog. SNS FIFO topics can't deliver messages to customer managed endpoints, such as email addresses, mobile apps, phone numbers for text messaging (SMS), or HTTP(S) endpoints. These endpoint Message delivery 100 Amazon Simple Notification Service Developer Guide types aren't guaranteed to preserve strict message ordering. Attempts to subscribe customer managed endpoints to SNS FIFO topics result in errors. SNS FIFO topics support the same message filtering capabilities as standard topics. For more information, see Amazon SNS message filtering for FIFO topics and the Simplify Your Pub/Sub Messaging with Amazon SNS Message Filtering post on the AWS Compute Blog. Amazon SNS message filtering for FIFO topics Amazon SNS FIFO topics support message filtering. Using message filtering simplifies your architecture by offloading the message routing logic from your publisher systems and the message filtering logic from your subscriber systems. When you subscribe an Amazon SQS FIFO or standard queue to an SNS FIFO topic, you can use message filtering to specify that the subscriber receives a subset of messages, rather than all of them. Each subscriber can set its own filter policy as subscription attributes. Based on the filter policy scope, filter policy is matched against incoming message-attributes or message-body. If the filter policy matches, the topic delivers a copy of the message to the subscriber. If there's no match, the topic doesn't deliver a copy of the message. In the auto parts price management example use case, assume that the following Amazon SNS filter policies are set and filter policy scope is MessageBody: • For the wholesale queue, the filter policy {"business":["wholesale"]} matches every message which contains a key named business and with wholesale in the set of values. In the following diagram, one of the keys in message m1 is business with the value of wholesale. One of the keys in message m3
|
sns-dg-030
|
sns-dg.pdf
| 30 |
the topic delivers a copy of the message to the subscriber. If there's no match, the topic doesn't deliver a copy of the message. In the auto parts price management example use case, assume that the following Amazon SNS filter policies are set and filter policy scope is MessageBody: • For the wholesale queue, the filter policy {"business":["wholesale"]} matches every message which contains a key named business and with wholesale in the set of values. In the following diagram, one of the keys in message m1 is business with the value of wholesale. One of the keys in message m3 is business with a value of ["wholesale,retail"]. Thus, both m1 and m3 match the filter policy's criteria, and both messages are delivered to the wholesale queue. • For the retail queue, the filter policy {"business":["retail"]} matches every message which contains a key named business and with retail in the set of values. In the diagram, one of the keys in message m2 is business with the value of retail. One of the keys in message m3 is business with the value of ["wholesale,retail"]. Thus, both m2 and m3 match the filter policy's criteria, and both messages are delivered to the retail queue. • For the analytics queue, we want Amazon Athena to receive all records, so no filter policy is applied. Message filtering 101 Amazon Simple Notification Service Developer Guide SNS FIFO topics support a variety of matching operators, including attribute string values, attribute numeric values, and attribute keys. For more information, see Amazon SNS message filtering. SNS FIFO topics don't deliver duplicate messages to subscribed endpoints. For more information, see Amazon SNS message deduplication for FIFO topics. Amazon SNS message deduplication for FIFO topics Amazon SNS FIFO topics and Amazon SQS FIFO queues support message deduplication, which provides exactly-once message delivery and processing as long as the following conditions are met: • The subscribed Amazon SQS FIFO queue exists and has permissions that allow the Amazon SNS service principal to deliver messages to the queue. • The Amazon SQS FIFO queue consumer processes the message and deletes it from the queue before the visibility timeout expires. • The Amazon SNS subscription topic has no message filtering. When you configure message filtering, Amazon SNS FIFO topics support at-most-once delivery, as messages can be filtered out based on your subscription filter policies. • There are no network disruptions that prevent acknowledgment of the message delivery. Message deduplication 102 Amazon Simple Notification Service Developer Guide Note Message deduplication applies to an entire Amazon SNS FIFO topic when the topic attribute FifoThroughputScope is set to Topic. When the topic attribute FifoThroughputScope is set to MessageGroup, message deduplication applies to each individual message group. When you publish a message to an Amazon SNS FIFO topic, the message must include a deduplication ID. This ID is included in the message that the Amazon SNS FIFO topic delivers to the subscribed Amazon SQS FIFO queues. If a message with a particular deduplication ID is successfully published to an Amazon SNS FIFO topic, any message published with the same deduplication ID, within the five minute deduplication interval, is accepted but not delivered. The Amazon SNS FIFO topic continues to track the message deduplication ID, at the deduplication scope configured by the topic attribute FifoThroughputScope, even after the message is delivered to subscribed endpoints. If the message body is guaranteed to be unique for each published message, you can enable content-based deduplication for an Amazon SNS FIFO topic and the subscribed Amazon SQS FIFO queues. Amazon SNS uses the message body to generate a unique hash value to use as the deduplication ID for each message, so you don't need to set a deduplication ID when you send each message. Note Message attributes are not included in the hash calculation. When content-based deduplication is enabled for an Amazon SNS FIFO topic, and a message is published with a deduplication ID, the published deduplication ID overrides the generated content- based deduplication ID. In the auto parts price management example use case, the company must set a universally unique deduplication ID for each price update. This is because the message body can be identical even when the message attribute is different for wholesale and retail. However, if the company added the business type (wholesale or retail) to the message body alongside the product ID and product price, they could enable content-based duplication in the Amazon SNS FIFO topic and the subscribed Amazon SQS FIFO queues. Message deduplication 103 Amazon Simple Notification Service Developer Guide In addition to message ordering and deduplication, Amazon SNS FIFO topics support message server-side encryption (SSE) with AWS KMS keys, and message privacy via VPC endpoints with AWS PrivateLink. For more information, see Amazon SNS message security for FIFO topics. Amazon SNS message security for FIFO
|
sns-dg-031
|
sns-dg.pdf
| 31 |
different for wholesale and retail. However, if the company added the business type (wholesale or retail) to the message body alongside the product ID and product price, they could enable content-based duplication in the Amazon SNS FIFO topic and the subscribed Amazon SQS FIFO queues. Message deduplication 103 Amazon Simple Notification Service Developer Guide In addition to message ordering and deduplication, Amazon SNS FIFO topics support message server-side encryption (SSE) with AWS KMS keys, and message privacy via VPC endpoints with AWS PrivateLink. For more information, see Amazon SNS message security for FIFO topics. Amazon SNS message security for FIFO topics You can enable encryption for Amazon SNS FIFO topics and Amazon SQS FIFO queues using AWS Key Management Service (AWS KMS) customer master keys (CMKs). • You can create new encrypted FIFO topics and queues or enable encryption for existing ones. • Only the message body is encrypted. Message attributes, resource metadata, and resource metrics remain unencrypted. Message security 104 Amazon Simple Notification Service Developer Guide Note Adding encryption to an existing FIFO topic or queue doesn't encrypt any backlogged messages, and removing encryption from a topic or queue leaves backlogged messages encrypted. SNS FIFO topics decrypt the messages immediately before delivering them to subscribed endpoints. SQS FIFO queues decrypt the message just before returning them to the consumer application. For more information, see Amazon SNS data encryption and the Encrypting messages published to Amazon SNS with AWS KMS post on the AWS Compute Blog. In addition, SNS FIFO topics and SQS FIFO queues support message privacy with interface VPC endpoints powered by AWS PrivateLink. Using interface endpoints, you can send messages from Amazon Virtual Private Cloud (Amazon VPC) subnets to FIFO topics and queues without traversing the public internet. This model keeps your messaging within the AWS infrastructure and network, which enhances the overall security of your application. When you use AWS PrivateLink, you don't need to set up an internet gateway, network address translation (NAT), or virtual private network (VPN). For more information, see Securing Amazon SNS traffic with VPC endpoints and the Securing messages published to Amazon SNS with AWS PrivateLink post on the AWS Security Blog. SNS FIFO topics also support dead-letter queues and message storage across Availability Zones. For more information, see Amazon SNS message durability for FIFO topics. Amazon SNS message durability for FIFO topics Amazon SNS FIFO topics and Amazon SQS queues are durable. Both resource types store messages redundantly across multiple Availability Zones, and provide dead-letter queues to handle exceptional cases. In Amazon SNS, message delivery fails when the Amazon SNS topic can't access a subscribed Amazon SQS queue due to a client-side or server-side error: • Client-side errors occur when the Amazon SNS FIFO topic has stale subscription metadata. Two common causes of client-side errors are when the Amazon SQS queue owner does one of the following: • Deletes the queue. Message durability 105 Amazon Simple Notification Service Developer Guide • Changes the queue policy in a way that prevents the Amazon SNS service principal from delivering messages to it. Amazon SNS doesn't retry delivering messages that failed due to client-side errors. • Server-side errors can occur in these situations: • The Amazon SQS service is unavailable. • Amazon SQS fails to process a valid request from the Amazon SNS service. When server-side errors occur, Amazon SNS FIFO topics retry the failed deliveries up to 100,015 times over 23 days. For more information, see Amazon SNS message delivery retries. For any type of error, Amazon SNS can sideline messages to Amazon SQS dead-letter queues so data isn't lost. In Amazon SQS, message processing fails when the consumer application fails to receive the message, process it, and delete it from the queue. When the maximum number of receive requests fail, Amazon SQS can sideline messages to dead-letter queues so data isn't lost. In the auto parts price management example use case, the company can assign an Amazon SQS dead-letter queue (DLQ) to each Amazon SNS FIFO topic subscription, as well as to each subscribed Amazon SQS queue. This protects the company from any price update loss. Message durability 106 Amazon Simple Notification Service Developer Guide The dead-letter queue associated with an Amazon SNS subscription must be an Amazon SQS queue of the same type as the subscribing queue. For example, the Amazon SNS FIFO subscription for an Amazon SQS FIFO queue must have an Amazon SQS FIFO queue as the dead-letter queue. Similarly, the Amazon SNS FIFO subscription for an Amazon SQS standard queue must have an Amazon SQS standard queue as its dead-letter queue. For more information, see Amazon SNS dead-letter queues and the Designing durable serverless apps with DLQs for Amazon SNS, Amazon SQS, AWS Lambda post on the AWS Compute Blog. For extended durability to assist in recovery
|
sns-dg-032
|
sns-dg.pdf
| 32 |
Amazon SNS subscription must be an Amazon SQS queue of the same type as the subscribing queue. For example, the Amazon SNS FIFO subscription for an Amazon SQS FIFO queue must have an Amazon SQS FIFO queue as the dead-letter queue. Similarly, the Amazon SNS FIFO subscription for an Amazon SQS standard queue must have an Amazon SQS standard queue as its dead-letter queue. For more information, see Amazon SNS dead-letter queues and the Designing durable serverless apps with DLQs for Amazon SNS, Amazon SQS, AWS Lambda post on the AWS Compute Blog. For extended durability to assist in recovery from downstream failures, topic owners can also use FIFO topics to archive messages up to 365 days. Topic subscribers can then replay those messages to a subscribed endpoint to recover messages lost due to a failure in a downstream application, or to replicate a state of an existing application. For more, see Amazon SNS message archiving and replay for FIFO topics. Message durability 107 Amazon Simple Notification Service Developer Guide Amazon SNS message archiving and replay for FIFO topics What is message archiving and replay? Amazon SNS provides a no-code message archiving and replay feature, specifically designed for FIFO (First-In-First-Out) topics. This feature allows topic owners to store messages directly within the topic archive for up to 365 days and replay them to subscribers when needed. Message archiving and replay are essential for recovering lost messages and synchronizing applications across regions or systems by replicating states. This functionality can be accessed through the AWS API, SDK, AWS CloudFormation, and AWS Management Console. Key use cases • Message recovery – Recover messages lost due to downstream application failures by replaying them to the subscriber’s endpoint. • State replication – Replicate the state of an existing system in a new environment by replaying messages starting from a specific timestamp. • Error correction – Resend missed messages during outages to ensure all events are processed correctly. Components of message archiving and replay Manage message archiving and replay for Amazon SNS FIFO topics, including setting retention periods, monitoring archived messages using CloudWatch, initiating replays through subscription attributes, and understanding the permissions required to modify and initiate replays. Message archiving • The topic owner enables the archiving feature and sets the message retention period, which can be up to 365 days. For more, see Amazon SNS message archiving for FIFO topic owners • CloudWatch metrics help monitor the archived messages. Message replay • A subscriber initiates a replay, selecting the time window for the messages to be reprocessed to the subscribed endpoint. For more see, Amazon SNS message replay for FIFO topic subscribers. Message archiving and replay 108 Amazon Simple Notification Service Developer Guide • You manage the replay through subscription attributes using the ReplayPolicy feature. Relevant permissions • SetSubscriptionAttributes – Required to configure or modify replay settings using the ReplayPolicy attribute on a subscription. • Subscribe – Necessary to attach a new subscription and initiate replays. • GetTopicAttributes – Allows viewing the topic's properties, but replay initiation primarily revolves around subscription management. Amazon SNS message archiving for FIFO topic owners Message archiving provides the ability to archive a single copy of all messages published to your topic. You can store published messages within your topic by enabling the message archive policy on the topic, which enables message archiving for all subscriptions linked to that topic. Messages can be archived for a minimum of one day to a maximum of 365 days. Additional charges apply when setting an archive policy. For pricing information, see Amazon SNS pricing. Create a message archive policy using the AWS Management Console Use this option to create a new message archive policy using the AWS Management Console. 1. Sign in to the Amazon SNS console. 2. Choose a topic or create a new one. To learn more about creating topics, see Creating an Amazon SNS topic. Note Amazon SNS message archiving and replay is only available for application-to- application (A2A) FIFO topics. 3. On the Edit topic page, expand the Archive policy section. 4. Enable the Archive policy feature, and enter the number of days for which you want to archive messages in the topic. 5. Choose Save changes. For topic owners 109 Amazon Simple Notification Service Developer Guide To view, edit, and deactivate a message archiving topic policy • On the Topic details page, the Retention policy displays the status of the archive policy, including the number of days for which it is set. Select the Archive policy tab to view the following message archive details: • Status – The archive and replay status appears as active when an archive policy is applied. The archive and replay status appears as inactive when the archive policy is set to an empty JSON object. • Message retention period – The specified
|
sns-dg-033
|
sns-dg.pdf
| 33 |
topic owners 109 Amazon Simple Notification Service Developer Guide To view, edit, and deactivate a message archiving topic policy • On the Topic details page, the Retention policy displays the status of the archive policy, including the number of days for which it is set. Select the Archive policy tab to view the following message archive details: • Status – The archive and replay status appears as active when an archive policy is applied. The archive and replay status appears as inactive when the archive policy is set to an empty JSON object. • Message retention period – The specified number of days for message retention. • Archive start date – The date from which subscribers can replay messages. • JSON preview – The JSON preview of the archive policy. • (Optional) To edit an archive policy, go to the topic summary page and choose Edit. • (Optional) To deactivate an archive policy, go to the topic summary page and choose Edit. Deactivate the Archive Policy and choose Save changes. • (Optional) To delete a topic with an archive policy, you must first deactivate the archive policy as previously described. Important To avoid accidental message deletions, you can not delete a topic with an active message archive policy. The topic's message archive policy must be deactivated before the topic can be deleted. When you deactivate a message archive policy, Amazon SNS deletes all of the archived messages. When deleting a topic, subscriptions are removed, and any messages in transit may not be delivered. Create a message archive policy using the API To create a message archive policy using the API, you need to add the attribute ArchivePolicy to your topic. You can set an ArchivePolicy using the API actions CreateTopic and SetTopicAttributes. ArchivePolicy has a single value, MessageRetentionPeriod, which represents the number of days Amazon SNS retains messages. To activate message archiving for your topic, set the MessageRetentionPeriod to an integer value greater than zero. For example, to retain messages in your archive for 30 days, set the ArchivePolicy to: { For topic owners 110 Amazon Simple Notification Service Developer Guide "ArchivePolicy": { "MessageRetentionPeriod": "30" } } To disable message archiving for your topic, and clear the archive, unset the ArchivePolicy, as follows: {} Create a message archive policy using the SDK To use an AWS SDK, you must configure it with your credentials. For more information, see Shared config and credentials files in the AWS SDKs and Tools Reference Guide. The following code example shows how to set the ArchivePolicy for an Amazon SNS topic to retain all messages published to the topic for 30 days. // Specify the ARN of the Amazon SNS topic to set the ArchivePolicy for. String topicArn = "arn:aws:sns:us-east-2:123456789012:MyArchiveTopic.fifo"; // Set the MessageRetentionPeriod to 30 days for the ArchivePolicy. String archivePolicy = "{\"MessageRetentionPeriod\":\"30\"}"; // Set the ArchivePolicy for the Amazon SNS topic SetTopicAttributesRequest request = new SetTopicAttributesRequest() .withTopicArn(topicArn) .withAttributeName("ArchivePolicy") .withAttributeValue(archivePolicy); sns.setTopicAttributes(request); Create a message archive policy using AWS CloudFormation To create an archive policy using AWS CloudFormation see AWS::SNS::Topic in the AWS CloudFormation User Guide. For topic owners 111 Amazon Simple Notification Service Developer Guide Grant access to an encrypted archive Before a subscriber can begin replaying messages from an encrypted topic, you must complete the following steps. Because past messages are replayed, Amazon SNS needs to be provisioned Decrypt access to the KMS key that was used to encrypt the messages in the archive. 1. When you encrypt messages with a KMS key and store them within the topic, you must grant Amazon SNS the ability to decrypt these messages via Key Policy. For more, see Grant decrypt permissions to Amazon SNS. 2. Enable AWS KMS for Amazon SNS. For more, see Configuring AWS KMS permissions. Important When you add the new sections to your KMS key policy, do not change any existing sections in the policy. If encryption is enabled on a topic, and the KMS key is disabled or deleted, or the KMS key policy is not correctly configured for Amazon SNS, Amazon SNS cannot replay messages to your subscribers. Grant decrypt permissions to Amazon SNS In order for Amazon SNS to access encrypted messages from within your topic’s archive and replay them to subscribed endpoints, you must enable the Amazon SNS service principle to decrypt these messages. The following is an example policy that is required to allow the Amazon SNS service principal to decrypt stored messages during a replay of historical messages from within your topic. { "Sid": "Allow SNS to decrypt archived messages", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "*" For topic owners 112 Amazon Simple Notification Service Developer Guide } Monitor message archive metrics using Amazon CloudWatch You can monitor archived messages using Amazon CloudWatch using the following metrics. To
|
sns-dg-034
|
sns-dg.pdf
| 34 |
replay them to subscribed endpoints, you must enable the Amazon SNS service principle to decrypt these messages. The following is an example policy that is required to allow the Amazon SNS service principal to decrypt stored messages during a replay of historical messages from within your topic. { "Sid": "Allow SNS to decrypt archived messages", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "*" For topic owners 112 Amazon Simple Notification Service Developer Guide } Monitor message archive metrics using Amazon CloudWatch You can monitor archived messages using Amazon CloudWatch using the following metrics. To be notified of anomalies in your workloads and help avoid impact, you can configure Amazon CloudWatch alarms on these metrics. For more details, see Logging and monitoring in Amazon SNS. Metric ApproximateNumberOfMessagesArchived ApproximateNumberOfBytesArchived NumberOfMessagesArchiveProcessing NumberOfBytesArchiveProcessing Description Provides the topic owner with the aggregate number of messages archived in the topic archive, at 60-minute resolution. Provides the topic owner with the aggregate number of bytes archived, across all messages in the topic archive, at 60-minute resolution. Provides the topic owner with the number of messages saved to the topic archive during the interval in 1-minute resolution. Provides the topic owner with the aggregate number of bytes saved to the topic archive during the interval in 1-minute resolution. The GetTopicAttributes API has a BeginningArchiveTime property, which represents the oldest timestamp at which a subscriber can start a replay. The following represents a sample response for this API action: { "ArchivePolicy": { "MessageRetentionPeriod": "<integer>" }, "BeginningArchiveTime": "<timestamp>", ... } For topic owners 113 Amazon Simple Notification Service Developer Guide Amazon SNS message replay for FIFO topic subscribers Amazon SNS replay allows topic subscribers to retrieve and redeliver archived messages from the topic data store to a subscribed endpoint. • Messages can be replayed immediately after the subscription is created. • A replayed message retains the same content, MessageId, and Timestamp as the original. • The message includes a Replayed attribute to indicate that it is a replayed message. • To replay only specific messages, apply a filter policy to your subscription. For more on filtering messages, see Filter replayed messages. Create a message replay policy using the AWS Management Console Use this option to create a new replay policy using the AWS Management Console. 1. Sign in to the Amazon SNS console. 2. Choose a topic subscription or create a new one. To learn more about creating subscriptions, see Creating a subscription to an Amazon SNS topic. 3. 4. 5. 6. To initiate the message replay, go to the Replay drop-down and choose Start replay. From the Replay timeframe modal, make the following selections: a. Choose replay start date and time – Choose the date (YYYY/MM/DD format) and time (24-hour hh:mm:ss format) from which you want to start replaying archived messages. The start time should be later than the beginning of the approximated archive time. b. (Optional) Choose replay end date and time – Choose the date (YYYY/MM/DD format) and time (24-hour hh:mm:ss format) when you want to stop replaying archived messages. c. Choose Start replay. (Optional) To stop a message replay, go to the Subscription details page and choose Stop replay from the Replay drop-down. (Optional) To monitor message replay metrics from within this workflow using CloudWatch, see Monitor message replay metrics using Amazon CloudWatch. To view and edit a message replay policy You can perform the following actions from the Subscription details page: For topic subscribers 114 Amazon Simple Notification Service Developer Guide • To view the message replay status, the Replay status field displays the following values: • Completed – The replay has successfully redelivered all messages, and is now delivering newly published messages. • In progress – The replay is currently replaying the selected messages. • Failed – The replay was unable to complete. • Pending – The default state while the replay initiates. • (Optional) To modify a message replay policy, go to the Subscription details page and choose Start replay from the Replay drop-down. Starting a replay will replace the existing replay. Add a replay policy to the subscription using the API To replay archived messages use the attribute ReplayPolicy. ReplayPolicy can be used with the Subscribe and SetSubscriptionAttributes API actions. This policy has the following values: • StartingPoint (Required) – Signals where to start replaying messages from. • EndingPoint (Optional) – Signals when to stop replaying messages. If EndingPoint is omitted, then the replay will continue until caught up to the current time. • PointType (Required) – Sets the type of starting and ending points. Currently, the supported value for PointType is Timestamp. For example, to recover from a downstream failure and resend all messages for a two hour time period on October 1, 2023, use the SetSubscriptionAttributes API action to set a ReplayPolicy as follows:
|
sns-dg-035
|
sns-dg.pdf
| 35 |
and SetSubscriptionAttributes API actions. This policy has the following values: • StartingPoint (Required) – Signals where to start replaying messages from. • EndingPoint (Optional) – Signals when to stop replaying messages. If EndingPoint is omitted, then the replay will continue until caught up to the current time. • PointType (Required) – Sets the type of starting and ending points. Currently, the supported value for PointType is Timestamp. For example, to recover from a downstream failure and resend all messages for a two hour time period on October 1, 2023, use the SetSubscriptionAttributes API action to set a ReplayPolicy as follows: { "PointType":"Timestamp", "StartingPoint":"2023-10-01T10:00:00.000Z", "EndingPoint":"2023-10-01T12:00:00.000Z" } To replay all messages sent to the topic as of October 1, 2023, and continue receiving all newly published messages to your topic, use the SetSubscriptionAttributes API action to set a ReplayPolicy on your subscription as follows: { For topic subscribers 115 Amazon Simple Notification Service Developer Guide "PointType":"Timestamp", "StartingPoint":"2023-10-01T00:00:00.000Z" } To verify that a message has been replayed, the boolean attribute Replayed is added to each replayed message. Add a replay policy to the subscription using the SDK To use an AWS SDK, you must configure it with your credentials. For more information, see Shared config and credentials files in the AWS SDKs and Tools Reference Guide. The following code example shows how to set the ReplayPolicy on a subscription to redeliver messages from the Amazon SNS FIFO topic's archive for a 2-hour time window on October 1st 2023. // Specify the ARN of the Amazon SNS subscription to initiate the ReplayPolicy on. String subscriptionArn = "arn:aws:sns:us- east-2:123456789012:MyArchiveTopic.fifo:1d2a3e9d-7f2f-447c-88ae-03f1c68294da"; // Set the ReplayPolicy to replay messages from the topic's archive // for a 2 hour time period on October 1st 2023 between 10am and 12pm UTC. String replayPolicy = "{\"PointType\":\"Timestamp\",\"StartingPoint\":\"2023-10-01T10:00:00.000Z\", \"EndingPoint\":\"2023-10-01T12:00:00.000Z\"}"; // Set the ArchivePolicy for the Amazon SNS topic SetSubscriptionAttributesRequest request = new SetSubscriptionAttributesRequest() .withSubscriptionArn(subscriptionArn) .withAttributeName("ReplayPolicy") .withAttributeValue(replayPolicy); sns.setSubscriptionAttributes(request); Understanding the EndingPoint When you apply a ReplayPolicy to an Amazon SNS subscription, the EndingPoint value is optional. If no EndingPoint is provided, the replay will start from the specified StartingPoint and continue until it catches up to the current time, including processing any newly published messages. Once caught up, the subscription will function as a regular subscription, receiving new messages as they are published. For topic subscribers 116 Amazon Simple Notification Service Developer Guide If an EndingPoint is specified, the service will replay messages from the StartingPoint up to the EndingPoint and then stop. This action effectively pauses the subscription. While the subscription is paused, newly published messages will not be delivered to the subscribed endpoint. To resume message delivery, apply a new ReplayPolicy without providing an EndingPoint, and set the StartingPoint to the desired point in time from which to continue receiving messages. For example, to resume a subscription from where a prior replay finished, set the new StartingPoint to the previously provided EndingPoint. Filter replayed messages Amazon SNS message filtering let's you control the replayed messages that Amazon SNS replays to your subscriber endpoint. When message filtering and message archiving are both enabled, Amazon SNS first retrieves the message from the topic’s data store, then applies the message against the subscription’s FilterPolicy. The message is delivered to the subscribed endpoint when there is a match, otherwise message is filtered out. For more information, see Amazon SNS subscription filter policies. Monitor message replay metrics using Amazon CloudWatch You can monitor replay messages using Amazon CloudWatch using the following metrics. To be notified of anomalies in your workloads and help avoid impact, you can configure Amazon CloudWatch alarms on these metrics. For more details, see Logging and monitoring in Amazon SNS. Metric NumberOfReplayedNotificationsDelivered NumberOfReplayedNotificationsFailed Description Provides the subscriber with the aggregate number of messages replayed from the topic archive, at 1-minute resolution. Provides the subscriber with the aggregate number of messages replayed that failed to deliver from the topic archive, at 1-minute resolution. For topic subscribers 117 Amazon Simple Notification Service Developer Guide Amazon SNS code examples for FIFO topics Use the following code examples to integrate the auto parts price management example use case with an Amazon SNS FIFO topic and either an Amazon SQS FIFO queue or a standard queue. Using an AWS SDK Using an AWS SDK, you create an Amazon SNS FIFO topic by setting its FifoTopic attribute to true. You create an Amazon SQS FIFO queue by setting its FifoQueue attribute to true. Also, you must add the .fifo suffix to the name of each FIFO resource. After you create a FIFO topic or queue, you can't convert it into a standard topic or queue. The following code examples create these FIFO and standard queue resources: • The Amazon SNS FIFO topic that distributes the price updates • The Amazon SQS FIFO queues that provide these updates to the wholesale
|
sns-dg-036
|
sns-dg.pdf
| 36 |
SDK Using an AWS SDK, you create an Amazon SNS FIFO topic by setting its FifoTopic attribute to true. You create an Amazon SQS FIFO queue by setting its FifoQueue attribute to true. Also, you must add the .fifo suffix to the name of each FIFO resource. After you create a FIFO topic or queue, you can't convert it into a standard topic or queue. The following code examples create these FIFO and standard queue resources: • The Amazon SNS FIFO topic that distributes the price updates • The Amazon SQS FIFO queues that provide these updates to the wholesale and retail applications • The Amazon SQS standard queue for the analytics application that stores records, which can be queried for business intelligence (BI) • The Amazon SNS FIFO subscriptions that connect the three queues to the topic This example sets filter policies in the subscriptions. If you test the example by publishing a message to the topic, make sure that you publish the message with the business attribute. Specify either retail or wholesale for the attribute value. Otherwise, the message is filtered out and not delivered to the subscribed queues. For more information, see Amazon SNS message filtering for FIFO topics. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. This example Code examples 118 Amazon Simple Notification Service Developer Guide • creates an Amazon SNS FIFO topic, two Amazon SQS FIFO queues, and one Standard queue. • subscribes the queues to the topic and publishes a message to the topic. The test verifies the receipt of the message to each queue. The complete example also shows the addition of access policies and deletes the resources at the end. public class PriceUpdateExample { public final static SnsClient snsClient = SnsClient.create(); public final static SqsClient sqsClient = SqsClient.create(); public static void main(String[] args) { final String usage = "\n" + "Usage: " + " <topicName> <wholesaleQueueFifoName> <retailQueueFifoName> <analyticsQueueName>\n\n" + "Where:\n" + " fifoTopicName - The name of the FIFO topic that you want to create. \n\n" + " wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n" + " retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" + " analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n"; if (args.length != 4) { System.out.println(usage); System.exit(1); } final String fifoTopicName = args[0]; final String wholeSaleQueueName = args[1]; final String retailQueueName = args[2]; final String analyticsQueueName = args[3]; // For convenience, the QueueData class holds metadata about a queue: ARN, URL, // name and type. List<QueueData> queues = List.of( new QueueData(wholeSaleQueueName, QueueType.FIFO), new QueueData(retailQueueName, QueueType.FIFO), FIFO example (AWS SDKs) 119 Amazon Simple Notification Service Developer Guide new QueueData(analyticsQueueName, QueueType.Standard)); // Create queues. createQueues(queues); // Create a topic. String topicARN = createFIFOTopic(fifoTopicName); // Subscribe each queue to the topic. subscribeQueues(queues, topicARN); // Allow the newly created topic to send messages to the queues. addAccessPolicyToQueuesFINAL(queues, topicARN); // Publish a sample price update message with payload. publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables"); // Clean up resources. deleteSubscriptions(queues); deleteQueues(queues); deleteTopic(topicARN); } public static String createFIFOTopic(String topicName) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = Map.of( "FifoTopic", "true", "ContentBasedDeduplication", "false", "FifoThroughputScope", "MessageGroup"); CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); String topicArn = response.topicArn(); System.out.println("The topic ARN is" + topicArn); return topicArn; } catch (SnsException e) { FIFO example (AWS SDKs) 120 Amazon Simple Notification Service Developer Guide System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void subscribeQueues(List<QueueData> queues, String topicARN) { queues.forEach(queue -> { SubscribeRequest subscribeRequest = SubscribeRequest.builder() .topicArn(topicARN) .endpoint(queue.queueARN) .protocol("sqs") .build(); // Subscribe to the endpoint by using the SNS service client. // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO // topic. SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest); System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]"); queue.subscriptionARN = subscribeResponse.subscriptionArn(); }); } public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName = "business"; String attributeValue = "wholesale"; MessageAttributeValue msgAttValue = MessageAttributeValue.builder() .dataType("String") .stringValue(attributeValue) .build(); Map<String, MessageAttributeValue> attributes = new HashMap<>(); attributes.put(attributeName, msgAttValue); PublishRequest pubRequest = PublishRequest.builder() FIFO example (AWS SDKs) 121 Amazon Simple Notification Service Developer Guide .topicArn(topicArn) .subject(subject) .message(payload) .messageGroupId(groupId) .messageDeduplicationId(dedupId) .messageAttributes(attributes) .build(); final PublishResponse response = snsClient.publish(pubRequest); System.out.println(response.messageId()); System.out.println(response.sequenceNumber()); System.out.println("Message was published to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } • For API details, see the following topics in AWS SDK for Java 2.x
|
sns-dg-037
|
sns-dg.pdf
| 37 |
and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName = "business"; String attributeValue = "wholesale"; MessageAttributeValue msgAttValue = MessageAttributeValue.builder() .dataType("String") .stringValue(attributeValue) .build(); Map<String, MessageAttributeValue> attributes = new HashMap<>(); attributes.put(attributeName, msgAttValue); PublishRequest pubRequest = PublishRequest.builder() FIFO example (AWS SDKs) 121 Amazon Simple Notification Service Developer Guide .topicArn(topicArn) .subject(subject) .message(payload) .messageGroupId(groupId) .messageDeduplicationId(dedupId) .messageAttributes(attributes) .build(); final PublishResponse response = snsClient.publish(pubRequest); System.out.println(response.messageId()); System.out.println(response.sequenceNumber()); System.out.println("Message was published to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateTopic • Publish • Subscribe Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SNS FIFO topic, subscribe Amazon SQS FIFO and standard queues to the topic, and publish a message to the topic. def usage_demo(): """Shows how to subscribe queues to a FIFO topic.""" FIFO example (AWS SDKs) 122 Amazon Simple Notification Service Developer Guide print("-" * 88) print("Welcome to the `Subscribe queues to a FIFO topic` demo!") print("-" * 88) sns = boto3.resource("sns") sqs = boto3.resource("sqs") fifo_topic_wrapper = FifoTopicWrapper(sns) sns_wrapper = SnsWrapper(sns) prefix = "sqs-subscribe-demo-" queues = set() subscriptions = set() wholesale_queue = sqs.create_queue( QueueName=prefix + "wholesale.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(wholesale_queue) print(f"Created FIFO queue with URL: {wholesale_queue.url}.") retail_queue = sqs.create_queue( QueueName=prefix + "retail.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(retail_queue) print(f"Created FIFO queue with URL: {retail_queue.url}.") analytics_queue = sqs.create_queue(QueueName=prefix + "analytics", Attributes={}) queues.add(analytics_queue) print(f"Created standard queue with URL: {analytics_queue.url}.") FIFO example (AWS SDKs) 123 Amazon Simple Notification Service Developer Guide topic = fifo_topic_wrapper.create_fifo_topic("price-updates-topic.fifo") print(f"Created FIFO topic: {topic.attributes['TopicArn']}.") for q in queues: fifo_topic_wrapper.add_access_policy(q, topic.attributes["TopicArn"]) print(f"Added access policies for topic: {topic.attributes['TopicArn']}.") for q in queues: sub = fifo_topic_wrapper.subscribe_queue_to_topic( topic, q.attributes["QueueArn"] ) subscriptions.add(sub) print(f"Subscribed queues to topic: {topic.attributes['TopicArn']}.") input("Press Enter to publish a message to the topic.") message_id = fifo_topic_wrapper.publish_price_update( topic, '{"product": 214, "price": 79.99}', "Consumables" ) print(f"Published price update with message ID: {message_id}.") # Clean up the subscriptions, queues, and topic. input("Press Enter to clean up resources.") for s in subscriptions: sns_wrapper.delete_subscription(s) sns_wrapper.delete_topic(topic) for q in queues: fifo_topic_wrapper.delete_queue(q) print(f"Deleted subscriptions, queues, and topic.") print("Thanks for watching!") print("-" * 88) class FifoTopicWrapper: """Encapsulates Amazon SNS FIFO topic and subscription functions.""" FIFO example (AWS SDKs) 124 Amazon Simple Notification Service Developer Guide def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def create_fifo_topic(self, topic_name): """ Create a FIFO topic. Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long. For a FIFO topic, the name must end with the .fifo suffix. :param topic_name: The name for the topic. :return: The new topic. """ try: topic = self.sns_resource.create_topic( Name=topic_name, Attributes={ "FifoTopic": str(True), "ContentBasedDeduplication": str(False), "FifoThroughputScope": "MessageGroup", }, ) logger.info("Created FIFO topic with name=%s.", topic_name) return topic except ClientError as error: logger.exception("Couldn't create topic with name=%s!", topic_name) raise error @staticmethod def add_access_policy(queue, topic_arn): """ Add the necessary access policy to a queue, so it can receive messages from a topic. :param queue: The queue resource. :param topic_arn: The ARN of the topic. :return: None. """ FIFO example (AWS SDKs) 125 Amazon Simple Notification Service try: Developer Guide queue.set_attributes( Attributes={ "Policy": json.dumps( { "Version": "2012-10-17", "Statement": [ { "Sid": "test-sid", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "SQS:SendMessage", "Resource": queue.attributes["QueueArn"], "Condition": { "ArnLike": {"aws:SourceArn": topic_arn} }, } ], } ) } ) logger.info("Added trust policy to the queue.") except ClientError as error: logger.exception("Couldn't add trust policy to the queue!") raise error @staticmethod def subscribe_queue_to_topic(topic, queue_arn): """ Subscribe a queue to a topic. :param topic: The topic resource. :param queue_arn: The ARN of the queue. :return: The subscription resource. """ try: subscription = topic.subscribe( Protocol="sqs", Endpoint=queue_arn, ) logger.info("The queue is subscribed to the topic.") return subscription FIFO example (AWS SDKs) 126 Amazon Simple Notification Service Developer Guide except ClientError as error: logger.exception("Couldn't subscribe queue to topic!") raise error @staticmethod def publish_price_update(topic, payload, group_id): """ Compose and publish a message that updates the wholesale price. :param topic: The topic to publish to. :param payload: The message to publish. :param group_id: The group ID for the message. :return: The ID of the message. """ try: att_dict = {"business": {"DataType": "String", "StringValue": "wholesale"}} dedup_id = uuid.uuid4() response = topic.publish( Subject="Price Update", Message=payload, MessageAttributes=att_dict, MessageGroupId=group_id, MessageDeduplicationId=str(dedup_id), ) message_id = response["MessageId"] logger.info("Published message to topic %s.", topic.arn) except ClientError as error: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise error return message_id @staticmethod def delete_queue(queue): """ Removes an SQS queue. When run against an AWS account, it can take up to 60 seconds before the queue is actually
|
sns-dg-038
|
sns-dg.pdf
| 38 |
price. :param topic: The topic to publish to. :param payload: The message to publish. :param group_id: The group ID for the message. :return: The ID of the message. """ try: att_dict = {"business": {"DataType": "String", "StringValue": "wholesale"}} dedup_id = uuid.uuid4() response = topic.publish( Subject="Price Update", Message=payload, MessageAttributes=att_dict, MessageGroupId=group_id, MessageDeduplicationId=str(dedup_id), ) message_id = response["MessageId"] logger.info("Published message to topic %s.", topic.arn) except ClientError as error: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise error return message_id @staticmethod def delete_queue(queue): """ Removes an SQS queue. When run against an AWS account, it can take up to 60 seconds before the queue is actually deleted. :param queue: The queue to delete. :return: None """ try: FIFO example (AWS SDKs) 127 Amazon Simple Notification Service Developer Guide queue.delete() logger.info("Deleted queue with URL=%s.", queue.url) except ClientError as error: logger.exception("Couldn't delete queue with URL=%s!", queue.url) raise error • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • CreateTopic • Publish • Subscribe SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a FIFO topic, subscribe an Amazon SQS FIFO queue to the topic, and publish a message to an Amazon SNS topic. " Creates a FIFO topic. " DATA lt_tpc_attributes TYPE /aws1/ cl_snstopicattrsmap_w=>tt_topicattributesmap. DATA ls_tpc_attributes TYPE /aws1/ cl_snstopicattrsmap_w=>ts_topicattributesmap_maprow. ls_tpc_attributes-key = 'FifoTopic'. ls_tpc_attributes-value = NEW /aws1/cl_snstopicattrsmap_w( iv_value = 'true' ). INSERT ls_tpc_attributes INTO TABLE lt_tpc_attributes. TRY. FIFO example (AWS SDKs) 128 Amazon Simple Notification Service Developer Guide DATA(lo_create_result) = lo_sns->createtopic( iv_name = iv_topic_name it_attributes = lt_tpc_attributes ). DATA(lv_topic_arn) = lo_create_result->get_topicarn( ). ov_topic_arn = lv_topic_arn. " ov_topic_arn is returned for testing purposes. " MESSAGE 'FIFO topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY. " Subscribes an endpoint to an Amazon Simple Notification Service (Amazon SNS) topic. " " Only Amazon Simple Queue Service (Amazon SQS) FIFO queues can be subscribed to an SNS FIFO topic. " TRY. DATA(lo_subscribe_result) = lo_sns->subscribe( iv_topicarn = lv_topic_arn iv_protocol = 'sqs' iv_endpoint = iv_queue_arn ). DATA(lv_subscription_arn) = lo_subscribe_result->get_subscriptionarn( ). ov_subscription_arn = lv_subscription_arn. " ov_subscription_arn is returned for testing purposes. " MESSAGE 'SQS queue was subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY. " Publish message to SNS topic. " TRY. DATA lt_msg_attributes TYPE /aws1/ cl_snsmessageattrvalue=>tt_messageattributemap. DATA ls_msg_attributes TYPE /aws1/ cl_snsmessageattrvalue=>ts_messageattributemap_maprow. ls_msg_attributes-key = 'Importance'. ls_msg_attributes-value = NEW /aws1/cl_snsmessageattrvalue( iv_datatype = 'String' iv_stringvalue = 'High' ). INSERT ls_msg_attributes INTO TABLE lt_msg_attributes. FIFO example (AWS SDKs) 129 Amazon Simple Notification Service Developer Guide DATA(lo_result) = lo_sns->publish( iv_topicarn = lv_topic_arn iv_message = 'The price of your mobile plan has been increased from $19 to $23' iv_subject = 'Changes to mobile plan' iv_messagegroupid = 'Update-2' iv_messagededuplicationid = 'Update-2.1' it_messageattributes = lt_msg_attributes ). ov_message_id = lo_result->get_messageid( ). " ov_message_id is returned for testing purposes. " MESSAGE 'Message was published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see the following topics in AWS SDK for SAP ABAP API reference. • CreateTopic • Publish • Subscribe Receiving messages from FIFO subscriptions You can now receive price updates in the three subscribed applications. As shown in the the section called “FIFO topic use case”, the point of entry for each consumer application is the Amazon SQS queue, which its corresponding AWS Lambda function can poll automatically. When an Amazon SQS queue is an event source for a Lambda function, Lambda scales its fleet of pollers as needed to efficiently consume messages. For more information, see Using AWS Lambda with Amazon SQS in the AWS Lambda Developer Guide. For information on writing your own queue pollers, see Recommendations for Amazon SQS standard and FIFO queues in the Amazon Simple Queue Service Developer Guide and ReceiveMessage in the Amazon Simple Queue Service API Reference. FIFO example (AWS SDKs) 130 Amazon Simple Notification Service Developer Guide Using AWS CloudFormation AWS CloudFormation allows you to use a template file to create and configure a collection of AWS resources together as a single unit. This section has an example template that creates the following: • The Amazon SNS FIFO topic that distributes the price updates • The Amazon SQS FIFO queues that provide these updates to the wholesale and retail applications • The Amazon SQS standard queue for the analytics application that stores records, which can be queried for business intelligence (BI) • The Amazon SNS FIFO subscriptions that connect the three queues to the topic • A filter policy that specifies that subscriber applications receive only the price updates that they need Note If you
|
sns-dg-039
|
sns-dg.pdf
| 39 |
of AWS resources together as a single unit. This section has an example template that creates the following: • The Amazon SNS FIFO topic that distributes the price updates • The Amazon SQS FIFO queues that provide these updates to the wholesale and retail applications • The Amazon SQS standard queue for the analytics application that stores records, which can be queried for business intelligence (BI) • The Amazon SNS FIFO subscriptions that connect the three queues to the topic • A filter policy that specifies that subscriber applications receive only the price updates that they need Note If you test this code sample by publishing a message to the topic, make sure that you publish the message with the business attribute. Specify either retail or wholesale for the attribute value. Otherwise, the message is filtered out and not delivered to the subscribed queues. { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "PriceUpdatesTopic": { "Type": "AWS::SNS::Topic", "Properties": { "TopicName": "PriceUpdatesTopic.fifo", "FifoTopic": true, "ContentBasedDeduplication": false, "ArchivePolicy": { "MessageRetentionPeriod": "30" } } }, "WholesaleQueue": { FIFO example (AWS CloudFormation) 131 Amazon Simple Notification Service Developer Guide "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "WholesaleQueue.fifo", "FifoQueue": true, "ContentBasedDeduplication": false } }, "RetailQueue": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "RetailQueue.fifo", "FifoQueue": true, "ContentBasedDeduplication": false } }, "AnalyticsQueue": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "AnalyticsQueue" } }, "WholesaleSubscription": { "Type": "AWS::SNS::Subscription", "Properties": { "TopicArn": { "Ref": "PriceUpdatesTopic" }, "Endpoint": { "Fn::GetAtt": [ "WholesaleQueue", "Arn" ] }, "Protocol": "sqs", "RawMessageDelivery": "false", "FilterPolicyScope": "MessageBody", "FilterPolicy": { "business": [ "wholesale" ] } } }, "RetailSubscription": { FIFO example (AWS CloudFormation) 132 Amazon Simple Notification Service Developer Guide "Type": "AWS::SNS::Subscription", "Properties": { "TopicArn": { "Ref": "PriceUpdatesTopic" }, "Endpoint": { "Fn::GetAtt": [ "RetailQueue", "Arn" ] }, "Protocol": "sqs", "RawMessageDelivery": "false", "FilterPolicyScope": "MessageBody", "FilterPolicy": { "business": [ "retail" ] } } }, "AnalyticsSubscription": { "Type": "AWS::SNS::Subscription", "Properties": { "TopicArn": { "Ref": "PriceUpdatesTopic" }, "Endpoint": { "Fn::GetAtt": [ "AnalyticsQueue", "Arn" ] }, "Protocol": "sqs", "RawMessageDelivery": "false" } }, "SalesQueuesPolicy": { "Type": "AWS::SQS::QueuePolicy", "Properties": { "PolicyDocument": { "Statement": [ { "Effect": "Allow", FIFO example (AWS CloudFormation) 133 Amazon Simple Notification Service Developer Guide "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "sqs:SendMessage" ], "Resource": "*", "Condition": { "ArnEquals": { "aws:SourceArn": { "Ref": "PriceUpdatesTopic" } } } } ] }, "Queues": [ { "Ref": "WholesaleQueue" }, { "Ref": "RetailQueue" }, { "Ref": "AnalyticsQueue" } ] } } } } For more information about deploying AWS resources using an AWS CloudFormation template, see Get Started in the AWS CloudFormation User Guide. FIFO example (AWS CloudFormation) 134 Amazon Simple Notification Service Developer Guide Amazon SNS message filtering By default, an Amazon SNS topic subscriber receives every message that's published to the topic. To receive only a subset of the messages, a subscriber must assign a filter policy to the topic subscription. A filter policy is a JSON object containing properties that define which messages the subscriber receives. Amazon SNS supports policies that act on the message attributes or on the message body, according to the filter policy scope that you set for the subscription. Filter policies for the message body assume that the message payload is a well-formed JSON object. If a subscription doesn't have a filter policy, the subscriber receives every message published to its topic. When you publish a message to a topic with a filter policy in place, Amazon SNS compares the message attributes or the message body to the properties in the filter policy for each of the topic's subscriptions. If all of the message attributes or message body properties satisfy the conditions specified in the filter policy, Amazon SNS sends the message to the subscriber. Otherwise, Amazon SNS doesn't send the message to that subscriber. For more information, see Filter Messages Published to Topics. Amazon SNS subscription filter policy scope The FilterPolicyScope subscription attribute allows you define the filtering scope by setting one of the following values: • MessageAttributes – Applies the filter policy to message attributes (default setting). • MessageBody – Applies the filter policy to the message body. Note If no filter policy scope is defined for an existing filter policy, the scope defaults to MessageAttributes. Subscription filter policy scope 135 Amazon Simple Notification Service Developer Guide Amazon SNS subscription filter policies A subscription filter policy allows you to specify property names and assign a list of values to each property name. For more information, see Amazon SNS message filtering. When Amazon SNS evaluates message attributes or message body properties against the subscription filter policy, it ignores the ones that aren't specified in the policy. Important AWS services such as IAM and Amazon SNS use a distributed computing model called eventual consistency. Additions or changes to a subscription filter policy require up to 15 minutes to fully take effect. A subscription accepts a message under the following conditions: • When the filter policy scope is
|
sns-dg-040
|
sns-dg.pdf
| 40 |
policy allows you to specify property names and assign a list of values to each property name. For more information, see Amazon SNS message filtering. When Amazon SNS evaluates message attributes or message body properties against the subscription filter policy, it ignores the ones that aren't specified in the policy. Important AWS services such as IAM and Amazon SNS use a distributed computing model called eventual consistency. Additions or changes to a subscription filter policy require up to 15 minutes to fully take effect. A subscription accepts a message under the following conditions: • When the filter policy scope is set to MessageAttributes, each property name in the filter policy matches a message attribute name. For each matching property name in the filter policy, at least one property value matches the message attribute value. • When the filter policy scope is set to MessageBody, each property name in the filter policy matches a message body property name. For each matching property name in the filter policy, at least one property value matches the message body property value. Amazon SNS currently supports the following filter operators: • AND logic • OR logic • OR operator • Key matching • Numeric value exact matching • Numeric value anything-but matching • Numeric value range matching • String value exact matching • String value anything-but matching Subscription filter policies 136 Amazon Simple Notification Service Developer Guide • String matching using a prefix with the anything-but operator • String value equals-ignore case • String value IP address matching • String value prefix matching • String value suffix matching Amazon SNS example filter policies The following example shows a message payload delivered by an Amazon SNS topic that processes customer transactions. The first example includes the MessageAttributes field with attributes that describe the transaction: • Customer's interests • Store name • Event state • Purchase price in USD Because this message includes the MessageAttributes field, any topic subscription that sets a FilterPolicy can selectively accept or reject the message, as long as FilterPolicyScope is set to MessageAttributes in the subscription. For information about applying attributes to a message, see Amazon SNS message attributes. { "Type": "Notification", "MessageId": "a1b2c34d-567e-8f90-g1h2-i345j67klmn8", "TopicArn": "arn:aws:sns:us-east-2:123456789012:MyTopic", "Message": "message-body-with-transaction-details", "Timestamp": "2019-11-03T23:28:01.631Z", "SignatureVersion": "4", "Signature": "signature", "UnsubscribeURL": "unsubscribe-url", "MessageAttributes": { "customer_interests": { "Type": "String.Array", "Value": "[\"soccer\", \"rugby\", \"hockey\"]" }, Amazon SNS example filter policies 137 Amazon Simple Notification Service Developer Guide "store": { "Type": "String", "Value":"example_corp" }, "event": { "Type": "String", "Value": "order_placed" }, "price_usd": { "Type": "Number", "Value": "210.75" } } } The following example shows the same attributes included within the Message field, also referred to as the message payload or message body. Any topic subscription that includes a FilterPolicy can selectively accept or reject the message, as long as FilterPolicyScope is set to MessageBody in the subscription. { "Type": "Notification", "MessageId": "a1b2c34d-567e-8f90-g1h2-i345j67klmn8", "TopicArn": "arn:aws:sns:us-east-2:123456789012:MyTopic", "Message": "{ \"customer_interests\": [\"soccer\", \"rugby\", \"hockey\"], \"store\": \"example_corp\", \"event\":\"order_placed\", \"price_usd\":210.75 }", "Timestamp": "2019-11-03T23:28:01.631Z", "SignatureVersion": "4", "Signature": "signature", "UnsubscribeURL": "unsubscribe-url" } The following filter policies accept or reject messages based on their property names and values. A policy that accepts the example message The properties in the following subscription filter policy match the attributes assigned to the example message. Note that the same filter policy works for a FilterPolicyScope whether Amazon SNS example filter policies 138 Amazon Simple Notification Service Developer Guide it's set to MessageAttributes or MessageBody. Each subscriber chooses their filtering scope according to the composition of the messages that they receive from the topic. If any single property in this policy doesn't match an attribute assigned to the message, the policy rejects the message. { "store": ["example_corp"], "event": [{"anything-but": "order_cancelled"}], "customer_interests": [ "rugby", "football", "baseball" ], "price_usd": [{"numeric": [">=", 100]}] } A policy that rejects the example message The following subscription filter policy has multiple mismatches between its properties and the attributes assigned to the example message. For example, because the encrypted property name isn't present in the message attributes, this policy property causes the message to be rejected regardless of the value assigned to it. If any mismatches occur, the policy rejects the message. { "store": ["example_corp"], "event": ["order_cancelled"], "encrypted": [false], "customer_interests": [ "basketball", "baseball" ] } Filter policy constraints in Amazon SNS When you’re setting up filter policies in Amazon SNS, there are a few important rules to keep in mind. These rules help ensure the effective application of filter policies while maintaining system performance and compatibility. Filter policy constraints 139 Amazon Simple Notification Service Developer Guide Common policy constraints When configuring filter policies in Amazon SNS, follow these important rules to ensure they work effectively while maintaining system performance and compatibility: • String matching – For string matching in the filter policy, the comparison is case-sensitive. • Numeric matching – For numeric matching, the value can range from -109 to 109 (-1
|
sns-dg-041
|
sns-dg.pdf
| 41 |
you’re setting up filter policies in Amazon SNS, there are a few important rules to keep in mind. These rules help ensure the effective application of filter policies while maintaining system performance and compatibility. Filter policy constraints 139 Amazon Simple Notification Service Developer Guide Common policy constraints When configuring filter policies in Amazon SNS, follow these important rules to ensure they work effectively while maintaining system performance and compatibility: • String matching – For string matching in the filter policy, the comparison is case-sensitive. • Numeric matching – For numeric matching, the value can range from -109 to 109 (-1 billion to 1 billion), with five digits of accuracy after the decimal point. • Filter policy complexity – The total combination of values in a filter policy must not exceed 150. To calculate the total combination, multiply the number of values in each array in the filter policy. • Limit number of keys – A filter policy can have a maximum of five keys. Additional considerations • The JSON of the filter policy can contain the following: • Strings enclosed in quotation marks • Numbers • The keywords true, false, and null, without quotation marks • When using the Amazon SNS API, you must pass the JSON of the filter policy as a valid UTF-8 string. • The maximum size of a filter policy is 256 KB. • By default, you can have up to 200 filter policies per topic, and 10,000 filter policies per AWS account. This policy limit won't stop Amazon SQS queue subscriptions from being created with the Subscribe API. However, it will fail when you attach the filter policy in the Subscribe API call (or the SetSubscriptionAttributes API call). To increase this quota, you can use AWS Service Quotas. Filter policy constraints 140 Amazon Simple Notification Service Developer Guide Policy constraints for attribute-based filtering Attribute-based filtering is the default option. FilterPolicyScope is set to MessageAttributes in the subscription. • Amazon SNS doesn't accept a nested filter policy for attribute-based filtering. • Amazon SNS compares policy properties only to message attributes that have the following data types: • String • String.Array Important When using attribute-based filtering in Amazon SNS, you must double-escape certain special characters, specifically: • Double quotes (") • Backslashes () Failure to double-escape these characters will result in the filter policy not matching the attributes of a published message, and the notification won't be delivered. Additional considerations • Passing objects in arrays isn't recommended because it may yield unexpected results due to the nesting, which isn't supported by attribute-based filtering. Use payload-based filtering for nested policies. • Number is supported for numeric attribute values. • Amazon SNS ignores message attributes with the Binary data type. Example policy for complexity: In the following policy example, the first key has three match operators, the second has one match operator, and the third has two match operators. { "key_a": ["value_one", "value_two", "value_three"], "key_b": ["value_one"], Filter policy constraints 141 Amazon Simple Notification Service Developer Guide "key_c": ["value_one", "value_two"] } The total combination is calculated as the product of the number of match operators for each key in the filter policy: 3(match operators of key_a) x 1(match operators of key_b) x 2(match operators of key_c) = 6 Policy constraints for payload-based filtering To switch from attribute-based (default) to payload-based filtering, you must set the FilterPolicyScope to MessageBody in the subscription. • Amazon SNS accepts a nested filter policy for payload-based filtering. • For a nested policy, only leaf keys are counted towards the five key limit. Example policy for key limit: In the following policy example: • There are two leaf keys: key_c and key_e. • key_c has four match operators with a nested level of three, and key_e has three match operators with a nested level of two. { "key_a": { "key_b": { "key_c": ["value_one", "value_two", "value_three", "value_four"] } }, "key_d": { "key_e": ["value_one", "value_two", "value_three"] } } Filter policy constraints 142 Amazon Simple Notification Service Developer Guide The total combination is calculated as the product of the number of match operators and the nested level for each key in the filter policy: 4(match operators of key_c) x 3(nested level of key_c) x 3(match operators of key_e) x 2(nested level of key_e) = 72 AND/OR logic Use AND/OR logic in filter policies to match message attributes or message body properties in Amazon SNS. This enables more precise and flexible message filtering. AND logic You can apply AND logic using multiple property names. Consider the following policy: { "customer_interests": ["rugby"], "price_usd": [{"numeric": [">", 100]}] } It matches any message attribute or message body property with the value of customer_interests set to rugby and the value of price_usd set to a number larger than 100. Note You can't apply AND logic to values of the same attribute. OR logic You
|
sns-dg-042
|
sns-dg.pdf
| 42 |
2(nested level of key_e) = 72 AND/OR logic Use AND/OR logic in filter policies to match message attributes or message body properties in Amazon SNS. This enables more precise and flexible message filtering. AND logic You can apply AND logic using multiple property names. Consider the following policy: { "customer_interests": ["rugby"], "price_usd": [{"numeric": [">", 100]}] } It matches any message attribute or message body property with the value of customer_interests set to rugby and the value of price_usd set to a number larger than 100. Note You can't apply AND logic to values of the same attribute. OR logic You can apply OR logic by assigning multiple values to a property name. Consider the following policy: { AND/OR logic 143 Amazon Simple Notification Service Developer Guide "customer_interests": ["rugby", "football", "baseball"] } It matches any message attribute or message body property with the value of customer_interests set to rugby, football, or baseball. OR operator You can use the "$or" operator to explicitly define a filter policy to express the OR relationship between multiple attributes in the policy. Amazon SNS only recognizes an "$or" relationship when the policy has met all of the following conditions. When all of these conditions are not met, "$or" is treated as a regular attribute name, the same as any other string in the policy. • There is an "$or" field attribute in the rule followed with an array, for example “$or” : []. • There are at least 2 objects in the "$or" array: "$or": [{}, {}]. • None of the objects in the "$or" array have field names that are reserved keywords. Otherwise "$or" is treated as a normal attribute name, the same as other strings in the policy. The following policy isn't parsed as an OR relationship because numeric and prefix are reserved keywords. { "$or": [ {"numeric" : 123}, {"prefix": "abc"} ] } OR operator examples Standard OR: { "source": [ "aws.cloudwatch" ], "$or": [ { "metricName": [ "CPUUtilization" ] }, { "namespace": [ "AWS/EC2" ] } ] } AND/OR logic 144 Developer Guide Amazon Simple Notification Service The filter logic for this policy is: "source" && ("metricName" || "namespace") It matches either of the following sets of message attributes: "source": {"Type": "String", "Value": "aws.cloudwatch"}, "metricName": {"Type": "String", "Value": "CPUUtilization"} or "source": {"Type": "String", "Value": "aws.cloudwatch"}, "namespace": {"Type": "String", "Value": "AWS/EC2"} It also matches either of the following message bodies: { "source": "aws.cloudwatch", "metricName": "CPUUtilization" } or { "source": "aws.cloudwatch", "namespace": "AWS/EC2" } Policy constraints that include OR relationships Consider the following policy: { "source": [ "aws.cloudwatch" ], "$or": [ { "metricName": [ "CPUUtilization", "ReadLatency" ] }, { "metricType": [ "MetricType" ] , "$or" : [ { "metricId": [ 1234, 4321 ] }, { "spaceId": [ 1000, 2000, 3000 ] } AND/OR logic 145 Amazon Simple Notification Service Developer Guide ] } ] } The logic for this policy can also be simplified as: ("source" AND "metricName") OR ("source" AND "metricType" AND "metricId") OR ("source" AND "metricType" AND "spaceId") The complexity calculation for policies with OR relationships can be simplified as the sum of the combination complexities for each OR statement. The total combination is calculated as follows: (source * metricName) + (source * metricType * metricId) + (source * metricType * spaceId) = (1 * 2) + (1 * 1 * 2) + (1 * 1 * 3) = 7 source has one value, metricName has two values, metricType has one value, metricId has two values and spaceId has three values. Consider the following nested filter policy: { "$or": [ { "metricName": [ "CPUUtilization", "ReadLatency" ] }, { "namespace": [ "AWS/EC2", "AWS/ES" ] } ], "detail" : { "scope" : [ "Service" ], "$or": [ { "source": [ "aws.cloudwatch" ] }, { "type": [ "CloudWatch Alarm State Change"] } ] } } AND/OR logic 146 Amazon Simple Notification Service Developer Guide The logic for this policy can be simplified as: ("metricName" AND ("detail"."scope" AND "detail"."source") OR ("metricName" AND ("detail"."scope" AND "detail"."type") OR ("namespace" AND ("detail"."scope" AND "detail"."source") OR ("namespace" AND ("detail"."scope" AND "detail"."type") The calculation for total combinations is the same for non-nested policies except we need to consider the a key’s nesting level. The total combination is calculated as follows: (2 * 2 * 2) + (2 * 2 * 2) + (2 * 2 * 2) + (2 * 2 * 2) = 32 metricName has two values, namespace has two values, scope is a two level nested key with one value, source is a two level nested key with one value, and type is a two level nested key with one value. Key matching Use the exists operator in a filter policy to match incoming messages based on whether a specific property is present or absent. • exists works only on leaf nodes (final attributes in the structure). •
|
sns-dg-043
|
sns-dg.pdf
| 43 |
* 2 * 2) + (2 * 2 * 2) + (2 * 2 * 2) + (2 * 2 * 2) = 32 metricName has two values, namespace has two values, scope is a two level nested key with one value, source is a two level nested key with one value, and type is a two level nested key with one value. Key matching Use the exists operator in a filter policy to match incoming messages based on whether a specific property is present or absent. • exists works only on leaf nodes (final attributes in the structure). • It does not apply to intermediate nodes within a nested JSON structure. • Use "exists": true to match incoming messages that include the specified property. The key must have a non-null and non-empty value. For example, the following policy property uses the exists operator with a value of true: "store": [{"exists": true}] It matches any list of message attributes that contains the store attribute key, such as the following: Key matching 147 Amazon Simple Notification Service Developer Guide "store": {"Type": "String", "Value": "fans"} "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball \"]"} It also matches either of the following message body: { "store": "fans" "customer_interests": ["baseball", "basketball"] } However, it doesn't match any list of message attributes without the store attribute key, such as the following: "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball \"]"} Nor does it match the following message body: { "customer_interests": ["baseball", "basketball"] } • Use "exists": false to match incoming messages that don't include the specified property. Note "exists": false only matches if at least one attribute is present. An empty set of attributes results in the filter not matching. For example, the following policy property uses the exists operator with a value of false: "store": [{"exists": false}] It doesn't match any list of message attributes that contains the store attribute key, such as the following: Key matching 148 Amazon Simple Notification Service Developer Guide "store": {"Type": "String", "Value": "fans"} "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball \"]"} It also doesn’t match the following message body: { "store": "fans" "customer_interests": ["baseball", "basketball"] } However, it matches any list of message attributes without the store attribute key, such as the following: "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball \"]"} It also matches the following message body: { "customer_interests": ["baseball", "basketball"] } Numeric value matching Filter messages by matching numeric values to message attribute values or to message body property values. Numeric values aren't enclosed in double quotation marks in the JSON policy. You can use the following numeric operations for filtering. Note Prefixes are supported for string matching only. Numeric value matching 149 Amazon Simple Notification Service Exact matching Developer Guide When a policy property value includes the keyword numeric and the operator =, it matches any message attribute or message body property values that have the same name and an equal numeric value. Consider the following policy property: "price_usd": [{"numeric": ["=",301.5]}] It matches either of the following message attributes: "price_usd": {"Type": "Number", "Value": 301.5} "price_usd": {"Type": "Number", "Value": 3.015e2} It also matches either of the following message bodies: { "price_usd": 301.5 } { "price_usd": 3.015e2 } Anything-but matching When a policy property value includes the keyword anything-but, it matches any message attribute or message body property values that don't include any of the policy property values. Consider the following policy property: "price": [{"anything-but": [100, 500]}] It matches either of the following message attributes: "price": {"Type": "Number", "Value": 101} Numeric value matching 150 Amazon Simple Notification Service Developer Guide "price": {"Type": "Number", "Value": 100.1} It also matches either of the following message bodies: { "price": 101 } { "price": 100.1 } Moreover, it matches the following message attribute (because it contains a value that isn't 100 or 500): "price": {"Type": "Number.Array", "Value": "[100, 50]"} And it also matches the following message body (because it contains a value that isn't 100 or 500): { "price": [100, 50] } However, it doesn't match the following message attribute: "price": {"Type": "Number", "Value": 100} Nor does it match the following message body: { "price": 100 } Value range matching In addition to the operator =, a numeric policy property can include the following operators: <, <=, >, and >=. Consider the following policy property: Numeric value matching 151 Amazon Simple Notification Service Developer Guide "price_usd": [{"numeric": ["<", 0]}] It matches any message attribute or message body property with negative numeric values. Consider another message attribute: "price_usd": [{"numeric": [">", 0, "<=", 150]}] It matches any message attribute or message body property with positive numbers up to and including 150. String value matching Filter messages by matching string values to message attribute values or message body property values. String values are enclosed in double quotation marks in the JSON policy. You can use the following string operations to
|
sns-dg-044
|
sns-dg.pdf
| 44 |
>, and >=. Consider the following policy property: Numeric value matching 151 Amazon Simple Notification Service Developer Guide "price_usd": [{"numeric": ["<", 0]}] It matches any message attribute or message body property with negative numeric values. Consider another message attribute: "price_usd": [{"numeric": [">", 0, "<=", 150]}] It matches any message attribute or message body property with positive numbers up to and including 150. String value matching Filter messages by matching string values to message attribute values or message body property values. String values are enclosed in double quotation marks in the JSON policy. You can use the following string operations to match message attributes or message body properties: Exact matching Exact matching occurs when a policy property value matches one or more message attribute values. For String.Array type attributes, each element in the array is treated as a separate string for matching purposes. Consider the following policy property: "customer_interests": ["rugby", "tennis"] It matches the following message attributes: "customer_interests": {"Type": "String", "Value": "rugby"} "customer_interests": {"Type": "String", "Value": "tennis"} "customer_interests": {"Type": "String.Array", "Value": "[\"rugby\", \"tennis\"]"} It also matches the following message bodies: { String value matching 152 Amazon Simple Notification Service Developer Guide "customer_interests": "rugby" } { "customer_interests": "tennis" } However, it doesn't match the following message attributes: "customer_interests": {"Type": "String", "Value": "baseball"} "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\"]"} Nor does it match the following message body: { "customer_interests": "baseball" } Anything-but matching When a policy property value includes the keyword anything-but, it matches any message attribute or message body values that don't include any of the policy property values. anything- but can be combined with "exists": false. For String.Array type attributes, it matches if none of the array elements are listed in the policy property. Consider the following policy property: "customer_interests": [{"anything-but": ["rugby", "tennis"]}] It matches any of the following message attributes: "customer_interests": {"Type": "String", "Value": "baseball"} "customer_interests": {"Type": "String", "Value": "football"} "customer_interests": {"Type": "String.Array", "Value": "[\"rugby\", \"baseball\"]"} String value matching 153 Amazon Simple Notification Service Developer Guide It also matches either of the following message bodies: { "customer_interests": "baseball" } { "customer_interests": "football" } Moreover, it matches the following message attribute (because it contains a value that isn't rugby or tennis): "customer_interests": {"Type": "String.Array", "Value": "[\"rugby\", \"baseball\"]"} And it also matches the following message body (because it contains a value that isn't rugby or tennis): { "customer_interests": ["rugby", "baseball"] } However, it doesn't match the following message attributes: "customer_interests": {"Type": "String", "Value": "rugby"} "customer_interests": {"Type": "String.Array", "Value": "[\"rugby\"]"} Nor does it match the following message body: { "customer_interests": ["rugby"] } Using a prefix with the anything-but operator For string matching, you can also use a prefix with the anything-but operator. For example, the following policy property denies the order- prefix: String value matching 154 Amazon Simple Notification Service Developer Guide "event":[{"anything-but": {"prefix": "order-"}}] It matches either of the following attributes: "event": {"Type": "String", "Value": "data-entry"} "event": {"Type": "String", "Value": "order_number"} It also matches either of the following message bodies: { "event": "data-entry" } { "event": "order_number" } However, it doesn't match the following message attribute: "event": {"Type": "String", "Value": "order-cancelled"} Nor does it match the following message body: { "event": "order-cancelled" } Equals-ignore-case matching When a policy property includes the keyword equals-ignore-case, it will perform a case- insensitive match with any message attribute or body property value. Consider the following policy property: "customer_interests": [{"equals-ignore-case": "tennis"}] It matches either of the following message attributes: String value matching 155 Amazon Simple Notification Service Developer Guide "customer_interests": {"Type": "String", "Value": "TENNIS"} "customer_interests": {"Type": "String", "Value": "Tennis"} It also matches either of the following message bodies: { "customer_interests": "TENNIS" } { "customer_interests": "teNnis" { IP address matching You can use the cidr operator to check whether an incoming message originates from a specific IP address or subnet. Consider the following policy property: "source_ip":[{"cidr": "10.0.0.0/24"}] It matches either of the following message attributes: "source_ip": {"Type": "String", "Value": "10.0.0.0"} "source_ip": {"Type": "String", "Value": "10.0.0.255"} It also matches either of the following message bodies: { "source_ip": "10.0.0.0" } { String value matching 156 Amazon Simple Notification Service Developer Guide "source_ip": "10.0.0.255" } However, it doesn't match the following message attribute: "source_ip": {"Type": "String", "Value": "10.1.1.0"} Nor does it match the following message body: { "source_ip": "10.1.1.0" } Prefix matching When a policy property includes the keyword prefix, it matches any message attribute or body property values that begin with the specified characters. Consider the following policy property: "customer_interests": [{"prefix": "bas"}] It matches either of the following message attributes: "customer_interests": {"Type": "String", "Value": "baseball"} "customer_interests": {"Type": "String", "Value": "basketball"} It also matches either of the following message bodies: { "customer_interests": "baseball" } { "customer_interests": "basketball" } String value matching 157 Amazon Simple Notification Service Developer Guide However, it doesn't match the following message attribute: "customer_interests": {"Type": "String", "Value": "rugby"} Nor does it match the following message body: { "customer_interests": "rugby"
|
sns-dg-045
|
sns-dg.pdf
| 45 |
When a policy property includes the keyword prefix, it matches any message attribute or body property values that begin with the specified characters. Consider the following policy property: "customer_interests": [{"prefix": "bas"}] It matches either of the following message attributes: "customer_interests": {"Type": "String", "Value": "baseball"} "customer_interests": {"Type": "String", "Value": "basketball"} It also matches either of the following message bodies: { "customer_interests": "baseball" } { "customer_interests": "basketball" } String value matching 157 Amazon Simple Notification Service Developer Guide However, it doesn't match the following message attribute: "customer_interests": {"Type": "String", "Value": "rugby"} Nor does it match the following message body: { "customer_interests": "rugby" } Suffix matching When a policy property includes the keyword suffix, it matches any message attribute or body property values that end with the specified characters. Consider the following policy property: "customer_interests": [{"suffix": "ball"}] It matches either of the following message attributes: "customer_interests": {"Type": "String", "Value": "baseball"} "customer_interests": {"Type": "String", "Value": "basketball"} It also matches either of the following message bodies: { "customer_interests": "baseball" } { "customer_interests": "basketball" } However, it doesn't match the following message attribute: "customer_interests": {"Type": "String", "Value": "rugby"} String value matching 158 Amazon Simple Notification Service Developer Guide Nor does it match the following message body: { "customer_interests": "rugby" } Applying a subscription filter policy in Amazon SNS Message filtering in Amazon SNS allows you to selectively deliver messages to subscribers based on filter policies. These policies define conditions that messages must meet to be delivered to a subscription. While raw message delivery is an option that can affect message processing, it is not required for subscription filters to work. You can apply a filter policy to an Amazon SNS subscription using the Amazon SNS console. Or, to apply policies programmatically, you can use the Amazon SNS API, the AWS Command Line Interface (AWS CLI), or any AWS SDK that supports Amazon SNS. You can also use AWS CloudFormation. Enabling Raw Message Delivery Raw message delivery ensures that message payloads are delivered as-is to subscribers without any additional encoding or transformation. This can be useful when subscribers require the original message format for processing. However, raw message delivery is not directly related to the functionality of subscription filters. Applying Subscription Filters To apply message filters to a subscription, you define a filter policy using JSON syntax. This policy specifies the conditions that a message must meet to be delivered to the subscription. Filters can be based on message attributes, such as message attributes, message structure, or even message content. Relationship between Raw Message Delivery and Subscription Filters While enabling raw message delivery can affect how messages are delivered and processed by subscribers, it is not a prerequisite for using subscription filters. However, in scenarios where subscribers require the original message format without any modifications, enabling raw message delivery might be beneficial alongside subscription filters. Considerations for Effective Filtering Applying a subscription filter policy 159 Amazon Simple Notification Service Developer Guide When implementing message filtering, consider the specific requirements of your application and subscribers. Define filter policies that accurately match the criteria for message delivery to ensure efficient and targeted message distribution. Important AWS services such as IAM and Amazon SNS use a distributed computing model called eventual consistency. Additions or changes to a subscription filter policy require up to 15 minutes to fully take effect. AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Subscriptions. 3. Select a subscription and then choose Edit. 4. On the Edit page, expand the Subscription filter policy section. 5. Choose between attribute-based filtering or payload-based filtering. 6. In the JSON editor field, provide the JSON body of your filter policy. 7. Choose Save changes. Amazon SNS applies your filter policy to the subscription. AWS CLI To apply a filter policy with the AWS Command Line Interface (AWS CLI), use the set- subscription-attributes command, as shown in the following example. For the -- attribute-name option, specify FilterPolicy. For --attribute-value, specify your JSON policy. $ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... -- attribute-name FilterPolicy --attribute-value '{"store":["example_corp"],"event": ["order_placed"]}' To provide valid JSON for your policy, enclose the attribute names and values in double quotes. You must also enclose the entire policy argument in quotes. To avoid escaping quotes, you can use AWS Management Console 160 Amazon Simple Notification Service Developer Guide single quotes to enclose the policy and double quotes to enclose the JSON names and values, as shown in the above example. If you want to switch from attribute-based (default) to payload-based message filtering, you can use the set-subscription-attributes command as well. For the --attribute-name option, specify FilterPolicyScope. For --attribute-value, specify MessageBody. $ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute- name FilterPolicyScope --attribute-value MessageBody To verify that your filter policy was applied, use the get-subscription-attributes command. The attributes in the terminal output should show
|
sns-dg-046
|
sns-dg.pdf
| 46 |
avoid escaping quotes, you can use AWS Management Console 160 Amazon Simple Notification Service Developer Guide single quotes to enclose the policy and double quotes to enclose the JSON names and values, as shown in the above example. If you want to switch from attribute-based (default) to payload-based message filtering, you can use the set-subscription-attributes command as well. For the --attribute-name option, specify FilterPolicyScope. For --attribute-value, specify MessageBody. $ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute- name FilterPolicyScope --attribute-value MessageBody To verify that your filter policy was applied, use the get-subscription-attributes command. The attributes in the terminal output should show your filter policy for the FilterPolicy key, as shown in the following example: $ aws sns get-subscription-attributes --subscription-arn arn:aws:sns: ... { "Attributes": { "Endpoint": "endpoint . . .", "Protocol": "https", "RawMessageDelivery": "false", "EffectiveDeliveryPolicy": "delivery policy . . .", "ConfirmationWasAuthenticated": "true", "FilterPolicy": "{\"store\": [\"example_corp\"], \"event\": [\"order_placed \"]}", "FilterPolicyScope": "MessageAttributes", "Owner": "111122223333", "SubscriptionArn": "arn:aws:sns: . . .", "TopicArn": "arn:aws:sns: . . ." } } AWS SDKs The following code examples show how to use SetSubscriptionAttributes. Important If you are using the SDK for Java 2.x example, the class SNSMessageFilterPolicy is not available out of the box. For instructions on how to install this class, see the example from the GitHub website. AWS SDKs 161 Amazon Simple Notification Service Developer Guide CLI AWS CLI To set subscription attributes The following set-subscription-attributes example sets the RawMessageDelivery attribute to an SQS subscription. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us- east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name RawMessageDelivery \ --attribute-value true This command produces no output. The following set-subscription-attributes example sets a FilterPolicy attribute to an SQS subscription. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us- east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }" This command produces no output. The following set-subscription-attributes example removes the FilterPolicy attribute from an SQS subscription. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us- east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{}" This command produces no output. • For API details, see SetSubscriptionAttributes in AWS CLI Command Reference. AWS SDKs 162 Amazon Simple Notification Service Developer Guide Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.ArrayList; /** * 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 UseMessageFilterPolicy { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of a subscription. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() AWS SDKs 163 Amazon Simple Notification Service Developer Guide .region(Region.US_EAST_1) .build(); usePolicy(snsClient, subscriptionArn); snsClient.close(); } public static void usePolicy(SnsClient snsClient, String subscriptionArn) { try { SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy(); // Add a filter policy attribute with a single value fp.addAttribute("store", "example_corp"); fp.addAttribute("event", "order_placed"); // Add a prefix attribute fp.addAttributePrefix("customer_interests", "bas"); // Add an anything-but attribute fp.addAttributeAnythingBut("customer_interests", "baseball"); // Add a filter policy attribute with a list of values ArrayList<String> attributeValues = new ArrayList<>(); attributeValues.add("rugby"); attributeValues.add("soccer"); attributeValues.add("hockey"); fp.addAttribute("customer_interests", attributeValues); // Add a numeric attribute fp.addAttribute("price_usd", "=", 0); // Add a numeric attribute with a range fp.addAttributeRange("price_usd", ">", 0, "<=", 100); // Apply the filter policy attributes to an Amazon SNS subscription fp.apply(snsClient, subscriptionArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } AWS SDKs 164 Amazon Simple Notification Service Developer Guide • For API details, see SetSubscriptionAttributes in AWS SDK for Java 2.x API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def add_subscription_filter(subscription, attributes): """ Adds a filter policy to a subscription. A filter policy is a key and a list of values that are allowed. When a message is published, it must have an attribute that passes the filter or it will not be sent to the subscription. :param subscription: The subscription the filter policy is attached to. :param attributes: A dictionary of key-value pairs that define the filter. """ try: att_policy = {key: [value] for key, value in attributes.items()} subscription.set_attributes( AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy) ) logger.info("Added filter to subscription %s.", subscription.arn) AWS SDKs 165 Amazon Simple Notification Service Developer Guide except ClientError: logger.exception( "Couldn't add filter to subscription %s.", subscription.arn ) raise • For API details, see SetSubscriptionAttributes in AWS SDK for Python (Boto3) API Reference. Amazon SNS API To apply a filter policy with the Amazon SNS API, make a request to the SetSubscriptionAttributes action. Set the AttributeName parameter to
|
sns-dg-047
|
sns-dg.pdf
| 47 |
The subscription the filter policy is attached to. :param attributes: A dictionary of key-value pairs that define the filter. """ try: att_policy = {key: [value] for key, value in attributes.items()} subscription.set_attributes( AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy) ) logger.info("Added filter to subscription %s.", subscription.arn) AWS SDKs 165 Amazon Simple Notification Service Developer Guide except ClientError: logger.exception( "Couldn't add filter to subscription %s.", subscription.arn ) raise • For API details, see SetSubscriptionAttributes in AWS SDK for Python (Boto3) API Reference. Amazon SNS API To apply a filter policy with the Amazon SNS API, make a request to the SetSubscriptionAttributes action. Set the AttributeName parameter to FilterPolicy, and set the AttributeValue parameter to your filter policy JSON. If you want to switch from attribute-based (default) to payload-based message filtering, you can use the SetSubscriptionAttributes action as well. Set the AttributeName parameter to FilterPolicyScope, and set the AttributeValue parameter to MessageBody. AWS CloudFormation To apply a filter policy using AWS CloudFormation, use a JSON or YAML template to create a AWS CloudFormation stack. For more information, see the FilterPolicy property of the AWS::SNS::Subscription resource in the AWS CloudFormation User Guide and the example AWS CloudFormation template. 1. Sign in to the AWS CloudFormation console. 2. Choose Create Stack. 3. On the Select Template page, choose Upload a template to Amazon S3, choose the file, and choose Next. 4. On the Specify Details page, do the following: a. b. For Stack Name, type MyFilterPolicyStack. For myHttpEndpoint, type the HTTP endpoint to be subscribed to your topic. Amazon SNS API 166 Amazon Simple Notification Service Developer Guide Tip If you don't have an HTTP endpoint, create one. 5. On the Options page, choose Next. 6. On the Review page, choose Create. Removing a subscription filter policy in Amazon SNS To stop filtering the messages that are sent to a subscription, remove the subscription's filter policy by overwriting it with an empty JSON body. After you remove the policy, the subscription accepts every message that's published to it. Using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Subscriptions. 3. Select a subscription and then choose Edit. 4. On the Edit EXAMPLE1-23bc-4567-d890-ef12g3hij456 page, expand the Subscription filter policy section. 5. In the JSON editor field, provide an empty JSON body for your filter policy: {}. 6. Choose Save changes. Amazon SNS applies your filter policy to the subscription. Using the AWS CLI To remove a filter policy with the AWS CLI, use the set-subscription-attributes command and provide an empty JSON body for the --attribute-value argument: $ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute- name FilterPolicy --attribute-value "{}" Removing a subscription filter policy 167 Amazon Simple Notification Service Developer Guide Using the Amazon SNS API To remove a filter policy with the Amazon SNS API, make a request to the SetSubscriptionAttributes action. Set the AttributeName parameter to FilterPolicy, and provide an empty JSON body for the AttributeValue parameter. Using the Amazon SNS API 168 Amazon Simple Notification Service Developer Guide Message data protection in Amazon SNS What is message data protection? Message data protection safeguards the data that's published to your Amazon SNS topics by using data protection policies to audit, mask, redact, or block the sensitive information that moves between applications or AWS services. Message data protection scans data in motion for personally identifiable information (PII) and protected health information (PHI) using data identifiers. You can choose to use predefined (or Amazon SNS managed) data identifiers (for example, names, addresses, credit card numbers, and prescription drug codes), or you can create your own custom data identifiers, specific to your business use case. Using the scanned information, message data protection provides detailed audit logs, and allows you to take action to protect that data. Message data protection supports the following actions to help protect sensitive customer information: • Audit – Audit up to 99% of the data that's published to an Amazon SNS topic. You can then choose to send the findings to Amazon CloudWatch, Amazon S3, or Amazon Data Firehose. • De-identify – Mask or redact sensitive data without interrupting message publishing or delivering. • Deny – Block the transmission of data between applications and AWS resources if sensitive data is present within the payload. Note Amazon SNS supports message data protection for Amazon SNS standard topics only. Why should I use message data protection? By introducing message data protection into your governance, risk management, and compliance programs, you can implement data protection policies that help you to identify and prevent data leakage. This provides your teams with tools that can help to reduce financial, legal, and regulatory risks by complying with privacy regulations such as HIPAA, GDPR, PCI, and FedRAMP. It also frees What is message data protection 169 Amazon Simple Notification Service Developer Guide your developers from the operational
|
sns-dg-048
|
sns-dg.pdf
| 48 |
present within the payload. Note Amazon SNS supports message data protection for Amazon SNS standard topics only. Why should I use message data protection? By introducing message data protection into your governance, risk management, and compliance programs, you can implement data protection policies that help you to identify and prevent data leakage. This provides your teams with tools that can help to reduce financial, legal, and regulatory risks by complying with privacy regulations such as HIPAA, GDPR, PCI, and FedRAMP. It also frees What is message data protection 169 Amazon Simple Notification Service Developer Guide your developers from the operational overhead that's associated with building and managing your own tools to protect sensitive data. For example, you can use message data protection to create an audit policy to determine whether any of your systems are inadvertently sending or receiving sensitive data. If your audit results show that systems are sending credit card information to systems that don’t require it, you can use a block policy to prevent the delivery of the data. Note Amazon SNS supports message data protection for Amazon SNS standard topics only. Understanding Amazon SNS data protection policies What are data protection policies? Amazon SNS uses data protection policies to select the sensitive data for which you want to scan, and the actions that you want to take to protect that data from being exchanged by your Amazon SNS topics. To select the sensitive data of interest, you use data identifiers. Amazon SNS message data protection then detects the sensitive data by using machine learning and pattern matching. To act upon data identifiers that are found, you can define an audit, de-identify, or deny operation. These operations let you log the sensitive data that is found (or not found), mask or redact sensitive data, or deny message delivery. Data protection policies 170 Amazon Simple Notification Service Developer Guide How is the data protection policy structured? As illustrated in the following figure, a data protection policy document includes the following elements: • Optional policy-wide information at the top of the document • One or more individual statements Each statement includes information about a single permission. Only one data protection policy can be defined per Amazon SNS topic. The data protection policy can have one or more deny or de-identify statements, but only one audit statement. JSON properties for the data protection policy A data protection policy requires the following basic policy information for identification: • Name – The policy name. • Description (Optional) – The policy description. Overview of data protection policy structure 171 Amazon Simple Notification Service Developer Guide • Version – The policy language version. The current version is 2021-06-01. • Statement – A list of statements that specifies data protection policy actions. { "Name": "basicPII-protection", "Description": "Protect basic types of sensitive data", "Version": "2021-06-01", "Statement": [ ... ] } JSON properties for a policy statement A policy statement sets the detection context for the data protection operation. • Sid (Optional) – The statement identifier. • DataDirection – Inbound (for Publish API requests) or Outbound (for notification deliveries) with respect to the Amazon SNS topic. • DataIdentifier – The sensitive data for which the Amazon SNS topic should scan. For example, name, address, or phone number. • Principal – The IAM principal that is published to the topic, or the IAM principal that is subscribed to the topic. • Operation – The follow-on action, either Audit, De-identify (mask or redact), or Deny (block), which the Amazon SNS topic executes once it finds sensitive data. { "Sid": "basicPII-inbound-protection", "DataDirection": "Inbound", "Principal": ["*"], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/Name", "arn:aws:dataprotection::aws:data-identifier/PhoneNumber-US" ], "Operation": { ... } Overview of data protection policy structure 172 Amazon Simple Notification Service Developer Guide } JSON properties for a policy statement operation A policy statement sets one of the following data protection operations. • Audit – Emits metrics and finding logs without interrupting message publishing or delivery. • De-identify – Mask or redact sensitive data without interrupting message publishing. • Deny – Blocks the Amazon SNS publish request or fails the message delivery. How do I determine the IAM principals for my data protection policy? Message data protection uses two IAM principals that interact with Amazon SNS. 1. Publish API Principal (Inbound) – The authenticated IAM principal calling the Amazon SNS Publish API. 2. Subscription Principal (Outbound) – The authenticated IAM principal that called the Subscribe API during subscription creation. The SubscriptionPrincipal is a publicly available Amazon SNS subscription property that can be retrieved from the GetSubscriptionAttributes API. { "Attributes": { "SubscriptionPrincipal": "arn:aws:iam::123456789012:user/NoNameAccess", "Owner": "123412341234", "RawMessageDelivery": "true", "TopicArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic", "Endpoint": "arn:aws:sqs:us-east-1:123456789012:NoNameAccess", "Protocol": "sqs", "PendingConfirmation": "false", "ConfirmationWasAuthenticated": "true", "SubscriptionArn": "arn:aws:sns:us-east-1:123412341234:PII-data- topic:5d8634ef-67ef-49eb-a824-4042b28d6f55" } } How do I determine the IAM principals 173 Amazon Simple Notification Service Developer Guide Data protection policy operations in Amazon SNS The following are examples
|
sns-dg-049
|
sns-dg.pdf
| 49 |
1. Publish API Principal (Inbound) – The authenticated IAM principal calling the Amazon SNS Publish API. 2. Subscription Principal (Outbound) – The authenticated IAM principal that called the Subscribe API during subscription creation. The SubscriptionPrincipal is a publicly available Amazon SNS subscription property that can be retrieved from the GetSubscriptionAttributes API. { "Attributes": { "SubscriptionPrincipal": "arn:aws:iam::123456789012:user/NoNameAccess", "Owner": "123412341234", "RawMessageDelivery": "true", "TopicArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic", "Endpoint": "arn:aws:sqs:us-east-1:123456789012:NoNameAccess", "Protocol": "sqs", "PendingConfirmation": "false", "ConfirmationWasAuthenticated": "true", "SubscriptionArn": "arn:aws:sns:us-east-1:123412341234:PII-data- topic:5d8634ef-67ef-49eb-a824-4042b28d6f55" } } How do I determine the IAM principals 173 Amazon Simple Notification Service Developer Guide Data protection policy operations in Amazon SNS The following are examples of data protection policies that you can use to audit and deny sensitive data. For a complete tutorial that includes an example application, see the Introducing message data protection for Amazon SNS blog post. Audit operation The Audit operation samples topic inbound messages, and logs the sensitive data findings in an AWS destination. The sample rate can be an integer between 0–99. This operation requires one of the following types of logging destinations: 1. FindingsDestination – The logging destination when the Amazon SNS topic finds sensitive data in the payload. 2. NoFindingsDestination – The logging destination when the Amazon SNS topic doesn't find sensitive data in the payload. You can use the following AWS services in each of the following log destination types: • Amazon CloudWatch Logs (Optional) – The LogGroup must be in the topic region and the name must start with /aws/vendedlogs/. • Amazon Data Firehose (Optional) – The DeliveryStream must be in the topic region and have Direct PUT as the source of delivery stream. For additional details, see Source, Destination, and Name in the Amazon Data Firehose Developer Guide. • Amazon S3 (Optional) – An Amazon S3 bucket name. Extra actions are required for using Amazon S3 bucket with SSE-KMS encryption enabled. { "Operation": { "Audit": { "SampleRate": "99", "FindingsDestination": { "CloudWatchLogs": { "LogGroup": "/aws/vendedlogs/log-group-name" }, "Firehose": { "DeliveryStream": "delivery-stream-name" }, Data protection policy operations 174 Developer Guide Amazon Simple Notification Service "S3": { "Bucket": "bucket-name" } }, "NoFindingsDestination": { "CloudWatchLogs": { "LogGroup": "/aws/vendedlogs/log-group-name" }, "Firehose": { "DeliveryStream": "delivery-stream-name" }, "S3": { "Bucket": "bucket-name" } } } } } Required permissions when specifying log destinations When you specify logging destinations in the data protection policy, you must add the following permissions to the IAM identity policy of the IAM principal that is calling the Amazon SNS PutDataProtectionPolicy API, or the CreateTopic API with the --data-protection- policy parameter. Audit destination IAM permission Default logs:CreateLogDelivery logs:GetLogDelivery logs:UpdateLogDelivery logs:DeleteLogDelivery logs:ListLogDeliveries CloudWatchLogs logs:PutResourcePolicy logs:DescribeResourcePolicies Data protection policy operations 175 Amazon Simple Notification Service Developer Guide Audit destination IAM permission logs:DescribeLogGroups Firehose iam:CreateServiceLinkedRole firehose:TagDeliveryStream s3:PutBucketPolicy s3:GetBucketPolicy Extra actions are required for using Amazon S3 bucket with SSE-KMS encryption enabled. S3 { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogDelivery", "logs:GetLogDelivery", "logs:UpdateLogDelivery", "logs:DeleteLogDelivery", "logs:ListLogDeliveries" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "logs:PutResourcePolicy", "logs:DescribeResourcePolicies", "logs:DescribeLogGroups" ], "Resource": [ "arn:aws:logs:region:account-id:SampleLogGroupName:*:*" ] }, Data protection policy operations 176 Developer Guide Amazon Simple Notification Service { "Effect": "Allow", "Action": [ "iam:CreateServiceLinkedRole", "firehose:TagDeliveryStream" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "s3:PutBucketPolicy", "s3:GetBucketPolicy" ], "Resource": [ "arn:aws:s3:::bucket-name" ] } ] } Required key policy for use with SSE-KMS If you use an Amazon S3 bucket as a log destination, you can protect the data in your bucket by enabling either Server-Side Encryption with Amazon S3-Managed Keys (SSE-S3), or Server-Side Encryption with AWS KMS keys (SSE-KMS). For more information, see Protecting data using server- side encryption in the Amazon S3 User Guide. If you choose SSE-S3, no additional configuration is required. Amazon S3 handles the encryption key. If you choose SSE-KMS, you must use a customer managed key. You must update the key policy for your customer managed key so that the log delivery account can write to your S3 bucket. For more information about the required key policy for use with SSE-KMS, see Amazon S3 bucket server-side encryption in the Amazon CloudWatch Logs User Guide. Audit destination log example In the following example, callerPrincipal is used to identify the source of the sensitive content, and messageID is used as a reference to check against the Publish API response. { Data protection policy operations 177 Amazon Simple Notification Service Developer Guide "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf", "auditTimestamp": "2022-05-12T2:10:44Z", "callerPrincipal": "arn:aws:iam::123412341234:role/Publisher", "resourceArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic", "dataIdentifiers": [ { "name": "Name", "count": 1, "detections": [ { "start": 1, "end": 2 } ] }, { "name": "PhoneNumber", "count": 2, "detections": [ { "start": 3, "end": 4 }, { "start": 5, "end": 6 } ] } ] } Audit operation metrics When an audit operation has specified the FindingsDestination or the NoFindingsDestination property, the topic owners also receive CloudWatch MessagesWithFindings and MessagesWithNoFindings metrics. Data protection policy operations 178 Amazon Simple Notification Service Developer Guide De-identify operation The De-identify operation masks
|
sns-dg-050
|
sns-dg.pdf
| 50 |
protection policy operations 177 Amazon Simple Notification Service Developer Guide "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf", "auditTimestamp": "2022-05-12T2:10:44Z", "callerPrincipal": "arn:aws:iam::123412341234:role/Publisher", "resourceArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic", "dataIdentifiers": [ { "name": "Name", "count": 1, "detections": [ { "start": 1, "end": 2 } ] }, { "name": "PhoneNumber", "count": 2, "detections": [ { "start": 3, "end": 4 }, { "start": 5, "end": 6 } ] } ] } Audit operation metrics When an audit operation has specified the FindingsDestination or the NoFindingsDestination property, the topic owners also receive CloudWatch MessagesWithFindings and MessagesWithNoFindings metrics. Data protection policy operations 178 Amazon Simple Notification Service Developer Guide De-identify operation The De-identify operation masks or redacts sensitive data from published or delivered messages. This operation is available for both inbound and outbound messages, and requires one of the following types of configurations: • MaskConfig – Mask using a supported character from the following table. For example, ssn: 123-45-6789 becomes ssn: ###########. { "Operation": { "Deidentify": { "MaskConfig": { "MaskWithCharacter": "#" } } } Supported mask character * A-Z, a-z, and 0-9 ! Name Asterisk Alphanumeric Space Exclamation mark Data protection policy operations 179 Amazon Simple Notification Service Developer Guide Supported mask character Name $ % & () + , - . /\ # : ; Dollar sign Percent sign Ampersand Parenthesis Plus sign Comma Hyphen Period Slash, back slash Number sign Colon Semicolon =, <> Equals. less or greater than @ [] ^ _ ` | ~ At sign Brackets Caret symbol Underscore Backtick Vertical bar Tilde symbol Data protection policy operations 180 Amazon Simple Notification Service Developer Guide • RedactConfig – Redact by removing the data entirely. For example, ssn: 123-45-6789 becomes ssn: . { "Operation": { "Deidentify": { "RedactConfig": {} } } On an inbound message, the sensitive data is de-identified after the audit operation, and the SNS:Publish API caller receives the following invalid parameter error when the entire message is sensitive. Error code: AuthorizationError ... Deny operation The Deny operation interrupts either the Publish API request or the delivery of the message if the message contains sensitive data. The Deny operation object is empty, as it doesn't require additional configuration. "Operation": { "Deny": {} } On an inbound message, the SNS:Publish API caller receives an authorization error. Error code: AuthorizationError ... On an outbound message, the Amazon SNS topic does not deliver the message to the subscription. To track unauthorized deliveries, enable the topic’s delivery status logging. The following is an example of a delivery status log: { "notification": { "messageMD5Sum": "29638742ffb68b32cf56f42a79bcf16b", "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf", "topicArn": "arn:aws:sns:us-east-1:123412341234:PII-data-topic", Data protection policy operations 181 Amazon Simple Notification Service Developer Guide "timestamp": "2022-05-12T2:12:44Z" }, "delivery": { "deliveryId": "98236591c-56aa-51ee-a5ed-0c7d43493170", "destination": "arn:aws:sqs:us-east-1:123456789012:NoNameAccess", "providerResponse": "The topic's data protection policy prohibits this message from being delivered to <subscription-arn>", "dwellTimeMs":20, "attempts":1, "statusCode": 403 }, "status": "FAILURE" } Amazon SNS data protection policy examples The following examples are data protection policies that you can use to audit and deny sensitive data. For a complete tutorial that includes an example application, see the Introducing message data protection for Amazon SNS blog post. Example policy for auditing Audit policies allow you to audit up to 99% of inbound messages and send findings to Amazon CloudWatch, Amazon Data Firehose, and Amazon S3. For example, you can create an audit policy to evaluate whether any of your systems are inadvertently sending or receiving sensitive data. If your audit results show that systems are sending credit card information to systems that don’t require it, you can implement a data protection policy to block the delivery of the data. The following example audits 99% of the messages that flow through the topic by looking for credit card numbers and sending the findings to CloudWatch Logs, Firehose, and Amazon S3. Data protection policy: { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { Data protection policy examples 182 Amazon Simple Notification Service Developer Guide "DataDirection": "Inbound", "Principal": ["*"], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" ], "Operation": { "Audit": { "SampleRate": "99", "FindingsDestination": { "CloudWatchLogs": { "LogGroup": "<example log name>" }, "Firehose": { "DeliveryStream": "<example stream name>" }, "S3": { "Bucket": "<example bucket name>" } } } } } ] } Audit results format example: { "messageId": "...", "callerPrincipal": "arn:aws:sts::123456789012:assumed-role/ExampleRole", "resourceArn": "arn:aws:sns:us-east-1:123456789012:ExampleArn", "dataIdentifiers": [ { "name": "CreditCardNumber", "count": 1, "detections": [ { "start": 1, "end": 2 } ] } ], "timestamp": "2021-04-20T00:33:40.241Z" } Data protection policy examples 183 Amazon Simple Notification Service Developer Guide Example policy with inbound de-identify mask statement The following example prevents a user from publishing a message to a topic with CreditCardNumber by masking the sensitive data from the message content. { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Inbound", "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" ], "Operation": { "Deidentify": { "MaskConfig": { "MaskWithCharacter": "#" } } } } ] } Inbound de-identify mask results example: // original
|
sns-dg-051
|
sns-dg.pdf
| 51 |
"detections": [ { "start": 1, "end": 2 } ] } ], "timestamp": "2021-04-20T00:33:40.241Z" } Data protection policy examples 183 Amazon Simple Notification Service Developer Guide Example policy with inbound de-identify mask statement The following example prevents a user from publishing a message to a topic with CreditCardNumber by masking the sensitive data from the message content. { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Inbound", "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" ], "Operation": { "Deidentify": { "MaskConfig": { "MaskWithCharacter": "#" } } } } ] } Inbound de-identify mask results example: // original message My credit card number is 4539894458086459 // delivered message My credit card number is ################ Example policy with inbound de-identify redact statement The following example prevents a user from publishing a message to a topic with CreditCardNumber by redacting the sensitive data from the message content. Data protection policy examples 184 Amazon Simple Notification Service Developer Guide { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Inbound", "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" ], "Operation": { "Deidentify": { "RedactConfig": {} } } } ] } Inbound de-identify redact results example: // original message My credit card number is 4539894458086459 // delivered message My credit card number is Example policy with outbound de-identify mask statement The following example prevents a user from receiving a message with CreditCardNumber by masking the sensitive data from the message content. { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Outbound", Data protection policy examples 185 Amazon Simple Notification Service "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" Developer Guide ], "Operation": { "Deidentify": { "MaskConfig": { "MaskWithCharacter": "-" } } } } ] } Outbound de-identify mask results example: // original message My credit card number is 4539894458086459 // delivered message My credit card number is ---------------- Example policy with outbound de-identify redact statement The following example prevents a user from receiving a message with CreditCardNumber by redacting the sensitive data from the message content. { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Outbound", "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" Data protection policy examples 186 Amazon Simple Notification Service Developer Guide ], "Operation": { "Deidentify": { "RedactConfig": {} } } } ] } Outbound de-identify redact results example: // original message My credit card number is 4539894458086459 // delivered message My credit card number is Example policy with inbound deny statement The following example blocks a user from publishing a message to a topic with CreditCardNumber in the message content. Denied payloads in the API response have a status code of "403 AuthorizationError". { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Inbound", "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" ], "Operation": { "Deny": {} } } ] Data protection policy examples 187 Amazon Simple Notification Service Developer Guide } Example policy with outbound deny statement The following example blocks an AWS account from receiving messages that contain CreditCardNumber. { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Statement": [ { "DataDirection": "Outbound", "Principal": [ "arn:aws:iam::123456789012:user/ExampleUser" ], "DataIdentifier": [ "arn:aws:dataprotection::aws:data-identifier/CreditCardNumber" ], "Operation": { "Deny": {} } } ] } Outbound deny results example, logged in Amazon CloudWatch: { "notification": { "messageMD5Sum": "2e8f58ff2eeed723b56b15493fbfb5a5", "messageId": "8747a956-ebf1-59da-b291-f2c2e4b87c9c", "topicArn": "arn:aws:sns:us-east-2:664555388960:test1", "timestamp": "2022-09-08 15:40:57.144" }, "delivery": { "deliveryId": "6a422437-78cc-5171-ad64-7fa3778507aa", "destination": "arn:aws:sqs:us-east-2:664555388960:test", "providerResponse": "The topic's data protection policy prohibits this message from being delivered to <subscription arn>", "dwellTimeMs": 22, Data protection policy examples 188 Amazon Simple Notification Service "attempts": 1, "statusCode": 403 }, "status": "FAILURE" } Developer Guide Creating data protection policies in Amazon SNS Data protection policies help you safeguard the data that's published to your Amazon SNS topics by auditing, de-identifying (masking or redacting), and denying (blocking) sensitive information that moves between applications or AWS services. You can use AWS API, AWS CLI, AWS CloudFormation, or AWS Management Console to create data protection policies in Amazon SNS. Only one policy can be defined per Amazon SNS topic. Each data protection policy can have one or more de-identify and deny statements, but only one audit statement. Topics • Creating data protection policies in Amazon SNS using the API • Creating data protection policies in Amazon SNS using the CLI • Creating data protection policies in Amazon SNS using CloudFormation • Creating data protection policies in Amazon SNS using the console • Creating Amazon SNS data protection policies to secure message data using the SDK Creating data protection policies in Amazon SNS using the API The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. Creating a data protection policy using API Create an Amazon SNS data protection policy using the AWS
|
sns-dg-052
|
sns-dg.pdf
| 52 |
the API • Creating data protection policies in Amazon SNS using the CLI • Creating data protection policies in Amazon SNS using CloudFormation • Creating data protection policies in Amazon SNS using the console • Creating Amazon SNS data protection policies to secure message data using the SDK Creating data protection policies in Amazon SNS using the API The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. Creating a data protection policy using API Create an Amazon SNS data protection policy using the AWS API. To create a data protection policy together with an Amazon SNS topic (AWS API) Use the DataProtectionPolicy property of a standard Amazon SNS topic: • CreateTopic To retrieve or create a data protection policy for an existing Amazon SNS topic (AWS API) Creating data protection policies 189 Amazon Simple Notification Service Developer Guide Call one of the following operations: • GetDataProtectionPolicy • PutDataProtectionPolicy Creating data protection policies in Amazon SNS using the CLI The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. Creating data protection policies using the AWS CLI Create an Amazon SNS data protection policy using the AWS Command Line Interface. To create a data protection policy together with an Amazon SNS topic (AWS CLI) Use this option to create a new data protection policy together with a standard Amazon SNS topic: • create-topic To create or retrieve a data protection policy for an existing Amazon SNS topic (AWS CLI) Call one of the following operations: • get-data-protection-policy • put-data-protection-policy Creating data protection policies in Amazon SNS using CloudFormation The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. Creating data protection policies (CloudFormation) Create an Amazon SNS data protection policy using AWS CloudFormation. To create a data protection policy together with an Amazon SNS topic (CloudFormation) Use this option to create a new data protection policy together with a standard Amazon SNS topic: • AWS::SNS::Topic Creating data protection policies 190 Amazon Simple Notification Service Developer Guide Creating data protection policies in Amazon SNS using the console The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. To create a data protection policy together with an Amazon SNS topic (Console) Use this option to create a new data protection policy together with a standard Amazon SNS topic. 1. Sign in to the Amazon SNS console. 2. Choose a topic or create a new one. For more details on creating topics, see Creating an Amazon SNS topic. 3. On the Create topic page, in the Details section, choose Standard. a. b. Enter a Name for the topic. (Optional) Enter a Display name for the topic. 4. Expand Data protection policy. 5. Choose a Configuration mode: • Basic – Define a data protection policy using a simple menu. • Advanced – Define a custom data protection policy using JSON. 6. (Optional) To create your own custom data identifier, expand the Custom data identifier configuration section do the following: a. Enter a unique name for the custom data identifier. Custom data identifier names support alphanumeric, underscore (_), and hyphen (-) characters. Up to 128 character are supported. This name cannot share the same name as a managed data identifier. For a full list of custom data identifier limitations, see Custom data identifier constraints. b. Enter a regular expression (RegEx) for the custom data identifier. RegEx supports alphanumeric characters, RegEx reserved characters, and symbols. RegEx has a maximum length of 200 characters. If the RegEx is too complicated, Amazon SNS will fail the API call. For a full list of RegEx limitations, see Custom data identifier constraints. c. (Optional) Choose Add custom data identifier to add additional data identifiers as needed. A maximum of 10 custom data identifiers are supported for each data protection policy. Creating data protection policies 191 Amazon Simple Notification Service Developer Guide 7. Choose the statement(s) that you'd like to add to your data protection policy. You can add audit, de-identify (mask or redact), and deny (block) statement types to the same data protection policy. a. Add audit statement – Configure which sensitive data to audit, what percentage of messages you want to audit for that data, and where to send audit logs. Note Only one audit statement is allowed per data protection policy or topic. i. ii. Select data identifiers to define the sensitive data that you want to audit. For Audit sample rate, enter the percentage of messages to audit for sensitive information, up to a maximum of 99%.
|
sns-dg-053
|
sns-dg.pdf
| 53 |
to your data protection policy. You can add audit, de-identify (mask or redact), and deny (block) statement types to the same data protection policy. a. Add audit statement – Configure which sensitive data to audit, what percentage of messages you want to audit for that data, and where to send audit logs. Note Only one audit statement is allowed per data protection policy or topic. i. ii. Select data identifiers to define the sensitive data that you want to audit. For Audit sample rate, enter the percentage of messages to audit for sensitive information, up to a maximum of 99%. iii. For Audit destination, select which AWS services to send the audit finding results, and enter a destination name for each AWS service that you use. You can select from the following Amazon Web Services: • Amazon CloudWatch – CloudWatch Logs is the AWS standard logging solution. Using CloudWatch Logs, you can perform log analytics using Logs Insights (see samples here) and create metrics and alarms. CloudWatch Logs is where many services publish logs, which makes it easier to aggregate all logs using one solution. For information about Amazon CloudWatch, see the Amazon CloudWatch User Guide. • Amazon Data Firehose – Firehose satisfies the demands for real-time streaming to Splunk, OpenSearch, and Amazon Redshift for further log analytics. For information about Amazon Data Firehose, see the Amazon Data Firehose User Guide. • Amazon Simple Storage Service – Amazon S3 is an economical log destination for archival purposes. You may be required to retain logs for a period of years. In this case, you can put logs into Amazon S3 to save costs. For information about Amazon Simple Storage Service, see the Amazon Simple Storage Service User Guide. b. Add a de-identify statement – Configure the sensitive data you want to de-identify in the message, whether you want to mask or redact that data, and the accounts to stop delivery of that data. Creating data protection policies 192 Amazon Simple Notification Service Developer Guide i. ii. For Data identifiers, select the sensitive data that you want to de-identify. For Define this de-identify statement for, select the AWS accounts or IAM principals to which this de-identify statement applies. You can apply it to all AWS accounts, or to specific AWS accounts or IAM entities (account roots, roles, or users) that use account IDs or IAM entity ARNs. Separate multiple IDs or ARNs using a comma ( , ). The following IAM principals are supported: • IAM account principals – For example,arn:aws:iam::AWS-account-ID:root. • IAM role principals – For example, arn:aws:iam::AWS-account-ID:role/ role-name. • IAM user principals – For example, arn:aws:iam::AWS-account-ID:user/ user-name. iii. For De-identify Option, select how you want to de-identify the sensitive data. The following options are supported: • Redact – Completely removes data. For example, email: classified@amazon.com becomes email: . • Mask – Replaces the data with single characters. For example, email: classified@amazon.com becomes email: *********************. iv. (Optional) Continue to add de-identify statements as needed. c. Add deny statement – Configure which sensitive data to prevent from moving through your topic, and which principals to prevent from delivering that data. i. For data direction , choose the direction of the messages for the deny statement: • Inbound messages – Apply this deny statement to messages that are sent to the topic. • Outbound messages – Apply this deny statement to messages that the topic delivers to subscription endpoints. ii. Choose the data identifiers to define the sensitive data that you want to deny. iii. Choose the IAM principals that apply to this deny statement. You can apply it to all AWS accounts, to specific AWS accounts, or IAM entities (for example, account roots, roles, or users) that use account IDs or IAM entity ARNs. Separate multiple IDs or ARNs using a comma ( , ). The following IAM principals are supported: Creating data protection policies 193 Amazon Simple Notification Service Developer Guide • IAM account principals – For example, arn:aws:iam::AWS-account-ID:root. • IAM role principals – For example, arn:aws:iam::AWS-account-ID:role/ role-name. • IAM user principals – For example, arn:aws:iam::AWS-account-ID:user/ user-name. iv. (Optional) Continue to add deny statements as needed. Creating Amazon SNS data protection policies to secure message data using the SDK The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. Creating data protection policies using the AWS SDK Create an Amazon SNS data protection policy using the AWS SDK. To create a data protection policy together with an Amazon SNS topic (AWS SDK) Use the following options to create a new data protection policy together with a standard Amazon SNS topic: Java /** * For information regarding CreateTopic see this documentation topic: * * https://docs.aws.amazon.com/code-samples/latest/catalog/javav2-sns-src-main-java- com-example-sns-CreateTopic.java.html */ public static String createSNSTopicWithDataProtectionPolicy(SnsClient snsClient, String topicName, String dataProtectionPolicy) {
|
sns-dg-054
|
sns-dg.pdf
| 54 |
and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. Creating data protection policies using the AWS SDK Create an Amazon SNS data protection policy using the AWS SDK. To create a data protection policy together with an Amazon SNS topic (AWS SDK) Use the following options to create a new data protection policy together with a standard Amazon SNS topic: Java /** * For information regarding CreateTopic see this documentation topic: * * https://docs.aws.amazon.com/code-samples/latest/catalog/javav2-sns-src-main-java- com-example-sns-CreateTopic.java.html */ public static String createSNSTopicWithDataProtectionPolicy(SnsClient snsClient, String topicName, String dataProtectionPolicy) { try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .dataProtectionPolicy(dataProtectionPolicy) .build(); Creating data protection policies 194 Amazon Simple Notification Service Developer Guide CreateTopicResponse result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } JavaScript // Import required AWS SDK clients and commands for Node.js import {CreateTopicCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { Name: "TOPIC_NAME", DataProtectionPolicy: "DATA_PROTECTION_POLICY" }; const run = async () => { try { const data = await snsClient.send(new CreateTopicCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run(); To create or retrieve a data protection policy for an existing Amazon SNS topic (AWS SDK) Use the following options to create or retrieve a new data protection policy together with a standard Amazon SNS topic: Java public static void putDataProtectionPolicy(SnsClient snsClient, String topicName, String dataProtectionPolicy) { try { Creating data protection policies 195 Amazon Simple Notification Service Developer Guide PutDataProtectionPolicyRequest request = PutDataProtectionPolicyRequest.builder() .resourceArn(topicName) .dataProtectionPolicy(dataProtectionPolicy) .build(); PutDataProtectionPolicyResponse result = snsClient.putDataProtectionPolicy(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.resourceArn() + " DataProtectionPolicy " + request.dataProtectionPolicy()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void getDataProtectionPolicy(SnsClient snsClient, String topicName) { try { GetDataProtectionPolicyRequest request = GetDataProtectionPolicyRequest.builder() .resourceArn(topicName) .build(); GetDataProtectionPolicyResponse result = snsClient.getDataProtectionPolicy(request); System.out.println("\n\nStatus is " + result.sdkHttpResponse().statusCode() + "\n\nDataProtectionPolicy: \n\n" + result.dataProtectionPolicy()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } JavaScript // Import required AWS SDK clients and commands for Node.js import {PutDataProtectionPolicyCommand, GetDataProtectionPolicyCommand } from "@aws- sdk/client-sns"; Creating data protection policies 196 Amazon Simple Notification Service Developer Guide import {snsClient } from "./libs/snsClient.js"; // Set the parameters const putParams = { ResourceArn: "TOPIC_ARN", DataProtectionPolicy: "DATA_PROTECTION_POLICY" }; const runPut = async () => { try { const data = await snsClient.send(new PutDataProtectionPolicyCommand(putParams)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; runPut(); // Set the parameters const getParams = { ResourceArn: "TOPIC_ARN" }; const runGet = async () => { try { const data = await snsClient.send(new GetDataProtectionPolicyCommand(getParams)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; runGet(); Deleting data protection policies in Amazon SNS You can delete Amazon SNS data protection policies using the AWS API, AWS CLI, AWS CloudFormation, or AWS Management Console. For general information about Amazon SNS data protection policies, see Understanding Amazon SNS data protection policies. Deleting data protection policies 197 Amazon Simple Notification Service Developer Guide The number and size of Amazon SNS data protection policy resources in an AWS account are limited. For more information, see Amazon SNS API throttling in AWS General Reference. Deleting data protection policies using the console To delete a managed data protection policy using the console 1. Sign in to the Amazon SNS console. 2. Choose the topic that contains the data protection policy that you want to delete. 3. Choose Edit. 4. Expand the Data protection policy section. 5. Choose Remove next to the data protection policy statement that you want to remove. 6. Choose Save changes. Deleting a data protection policy using an empty JSON string You can delete a data protection policy by updating it to an empty JSON string. Deleting a data protection policy using the AWS CLI You can delete a data protection policy using the AWS CLI. //aws sns put-data-protection-policy --resource-arn topic-arn --data- protection-policy "" Amazon SNS data identifiers Amazon SNS uses a combination of criteria and techniques, including machine learning and pattern matching, to detect sensitive data. These criteria and techniques, collectively referred to as data identifiers, can detect a large and growing list of sensitive data types for many countries and regions. Amazon SNS managed data identifiers offer preconfigured data types for protecting financial data, personal health information (PHI), and personally identifiable information (PII). You can also use custom data identifiers to create your own data identifiers tailored to your specific use case. Data identifiers 198 Amazon Simple Notification Service Developer Guide Using managed data identifiers in Amazon SNS What are managed data identifiers? Amazon SNS managed data identifiers are designed to detect a specific type of sensitive data, such as credit card numbers, AWS secret access keys,
|
sns-dg-055
|
sns-dg.pdf
| 55 |
a large and growing list of sensitive data types for many countries and regions. Amazon SNS managed data identifiers offer preconfigured data types for protecting financial data, personal health information (PHI), and personally identifiable information (PII). You can also use custom data identifiers to create your own data identifiers tailored to your specific use case. Data identifiers 198 Amazon Simple Notification Service Developer Guide Using managed data identifiers in Amazon SNS What are managed data identifiers? Amazon SNS managed data identifiers are designed to detect a specific type of sensitive data, such as credit card numbers, AWS secret access keys, or passport numbers for a particular country or region. When you create a data protection policy, you can configure Amazon SNS to use these identifiers to analyze messages going through the topic, and take actions when they are detected. Amazon SNS can detect the following categories of sensitive data by using managed data identifiers: • Credentials, such as private keys or AWS secret access keys • Device identifiers, such as IP address or MAC address • Financial information, such as credit card numbers • Health information, for PHI such as health insurance or medical identification numbers • Personal information, for PII such as driver’s licenses or social security numbers Within each category, Amazon SNS can detect multiple types of sensitive data. The topics in this section list and describe each type and any relevant requirements for detecting it. For each type, they also indicate the unique identifier (ID) for the managed data identifier that's designed to detect the data. When you create a data protection policy, you can use this ID to include the managed data identifier for message data protection to detect. Keyword requirements To detect certain types of sensitive data, Amazon SNS scans for keywords in proximity of the data. If this is the case for a particular type of data, a subsequent topic in this section indicates specific keyword requirements for that data. Keywords aren’t case sensitive. In addition, if a keyword contains a space, Amazon SNS automatically matches keyword variations that don’t contain the space, or contain an underscore (_) or a hyphen (-) instead of the space. In certain cases, Amazon SNS also expands or abbreviates a keyword to address common variations of the keyword. Amazon SNS managed data identifiers for sensitive data types The following table lists and describes the types of credential, device, financial, medical, and personal health information (PHI) that Amazon SNS can detect using managed data identifiers. Managed data identifiers 199 Amazon Simple Notification Service Developer Guide These are in addition to certain types of data that might also qualify as personally identifiable information (PII). Region-dependent data identifiers require the identifier name with a dash, and the two letter (ISO 3166-1 alpha-2) codes. For example, DriversLicense-US. Identifier Category Countries/Languages BankAccountNumber Financial DE, ES, FR, GB, IT CepCode Cnpj CpfCode DriversLicense Personal Personal Personal Personal DrugEnforcementAge ncyNumber Health ElectoralRollNumber Personal HealthInsuranceCardNumber Health HealthInsuranceClaimNumber Health HealthInsuranceNumber Health HealthcareProcedureCode Health IndividualTaxIdentification Number Personal InseeCode Personal MedicareBeneficiaryNumber Health BR BR BR AT, AU, BE, BG, CA, CY, CZ, DE, DK, EE, ES, FI, FR, GB, GR, HR, HU, IE, IT, LT, LU, LV, MT, NL, PL, PT, RO, SE, SI, SK, US US GB EU US FR US US FR US Managed data identifiers 200 Amazon Simple Notification Service Developer Guide Identifier Category Countries/Languages NationalDrugCode Health NationalIdentificationNumber Personal NationalInsuranceNumber Personal NationalProviderId NhsNumber NieNumber NifNumber PassportNumber Health Health Personal Personal Personal US DE, ES, IT GB US GB ES ES CA, DE, ES, FR, GB, IT, US PermanentResidenceNumber Personal PersonalHealthNumber Health CA CA PhoneNumber PostalCode RgNumber Personal Personal Personal SocialInsuranceNumber Personal Ssn TaxId ZipCode Personal Personal Personal BR, DE, ES, FR, GB, IT, US CA BR CA ES, US DE, ES, FR, GB US Supported Identifiers that are language/region independent Managed data identifiers 201 Amazon Simple Notification Service Developer Guide Identifier Address AwsSecretKey CreditCardExpiration CreditCardNumber CreditCardSecurityCode EmailAddress IpAddress LatLong Name OpenSshPrivateKey PgpPrivateKey PkcsPrivateKey PuttyPrivateKey VehicleIdentificationNumber Category Personal Credentials Financial Financial Financial Personal Personal Personal Personal Credentials Credentials Credentials Credentials Personal Amazon SNS sensitive data types: Credentials The following table lists and describes the types of credentials that Amazon SNS can detect using managed data identifiers. Detection type Managed data identifier ID Keyword required Countries and regions AWS secret access key AwsSecretKey aws_secret_access_ key, credentials, Any Managed data identifiers 202 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Countries and regions secret access key, secret key, set-awscr edential OpenSSH private key OpenSshPrivateKey PGP private key PgpPrivateKey Public-Key Cryptogra phy Standard (PKCS) private key PkcsPrivateKey No No No PuTTY private key PuttyPrivateKey No Data identifier ARNs for credential data types Any Any Any Any The following lists the Amazon Resource Names (ARNs) for the data identifiers that you can add to your
|
sns-dg-056
|
sns-dg.pdf
| 56 |
type Managed data identifier ID Keyword required Countries and regions AWS secret access key AwsSecretKey aws_secret_access_ key, credentials, Any Managed data identifiers 202 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Countries and regions secret access key, secret key, set-awscr edential OpenSSH private key OpenSshPrivateKey PGP private key PgpPrivateKey Public-Key Cryptogra phy Standard (PKCS) private key PkcsPrivateKey No No No PuTTY private key PuttyPrivateKey No Data identifier ARNs for credential data types Any Any Any Any The following lists the Amazon Resource Names (ARNs) for the data identifiers that you can add to your data protection policies. Credential data identifier ARNs arn:aws:dataprotection::aws:data-identifier/AwsSecretKey arn:aws:dataprotection::aws:data-identifier/OpenSshPrivateKey arn:aws:dataprotection::aws:data-identifier/PgpPrivateKey arn:aws:dataprotection::aws:data-identifier/PkcsPrivateKey arn:aws:dataprotection::aws:data-identifier/PuttyPrivateKey Amazon SNS sensitive data types: Devices The following table lists and describes the types of device identifiers that Amazon SNS can detect using managed data identifiers. Managed data identifiers 203 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Countries and regions IP Address IpAddress No Any Data identifier ARNs for device data types The following lists the Amazon Resource Names (ARNs) for the data identifiers that you can add to your data protection policies. Device data identifier ARN arn:aws:dataprotection::aws:data-identifier/IpAddress Amazon SNS sensitive data types: Financial The following table lists and describes the types of financial information that Amazon SNS can detect using managed data identifiers. Detection type Managed data identifier ID Keyword required Additional information Countries and regions Bank account number BankAccou ntNumber BankAccou ntNumber-US Yes, see Keywords for bank account numbers. France, Germany, Italy, Spain, UK This includes: International Bank Account Numbers (IBANs) that consist of up to 34 alphanume ric character s, including elements such as country code. Managed data identifiers 204 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Credit card expiration date CreditCar dExpiration exp d, exp m, exp y, expiration, – Credit card magnetic strip CreditCar dMagneticStripe data expiry Yes, including : card data, iso7813, mag, magstripe, stripe, swipe. This includes tracks 1 and 2. Any Any Credit card number CreditCar dNumber account number, american Detection requires the data Any express, amex, to be a 13–19 bank card, card, digit sequence card num, card that adheres to number, cc #, the Luhn check ccn, check card, formula, and credit, credit uses a standard card#, dankort, card number debit, debit card, diners prefix for any of the following club, discover, types of credit electron, elo cards: American verification code, japanese Express, Dankort, Diner’s card bureau, jcb, Club, Discover, mastercard, mc, Electron, pan, payment Japanese Card account number, Bureau (JCB), payment card Mastercard, number, pcn, UnionPay, and union pay, visa Visa (superscript link below 1). Managed data identifiers 205 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Credit card verification code CreditCar dSecurityCode – Any card id, card identification code, card identification number, card security code, card validatio n code, card validation number, card verification data, card verification value, cvc, cvc2, cvv, cvv2, elo verification code 1. Amazon SNS doesn't report occurrences of the following sequences, which credit card issuers have reserved for public testing: 122000000000003, 2222405343248877, 2222990905257051, 2223007648726984, 2223577120017656, 30569309025904, 34343434343434, 3528000700000000, 3530111333300000, 3566002020360505, 36148900647913, 36700102000000, 371449635398431, 378282246310005, 378734493671000, 38520000023237, 4012888888881881, 4111111111111111, 4222222222222, 4444333322221111, 4462030000000000, 4484070000000000, 4911830000000, 4917300800000000, 4917610000000000, 4917610000000000003, 5019717010103742, 5105105105105100, 5111010030175156, 5185540810000019, 5200828282828210, 5204230080000017, 5204740009900014, 5420923878724339, 5454545454545454, 5455330760000018, 5506900490000436, 5506900490000444, 5506900510000234, 5506920809243667, 5506922400634930, 5506927427317625, 5553042241984105, 5555553753048194, 5555555555554444, 5610591081018250, 6011000990139424, 6011000400000000, Managed data identifiers 206 Amazon Simple Notification Service Developer Guide 6011111111111117, 630490017740292441, 630495060000000000, 6331101999990016, 6759649826438453, 6799990100000000019, and 76009244561. Keywords for bank account numbers Use the following keywords to detect International Bank Account Numbers (IBANs) that consist of up to 34 alphanumeric characters, including elements such as country code. Country or region France Germany Keywords account code, account number, accountno #, accountnu mber#, bban, code bancaire, compte bancaire, customer account id, customer account number, customer bank account id, iban, numéro de compte account code, account number, accountno #, accountnu mber#, bankleitz ahl, bban, customer account id, customer Managed data identifiers 207 Amazon Simple Notification Service Developer Guide Country or region Keywords Italy account number, customer bank account id, geheimzah l, iban, kartennummer, kontonumm er, kreditkar tennummer, sepa account code, account number, accountno #, accountnu mber#, bban, codice bancario, conto bancario, customer account id, customer account number, customer bank account id, iban, numero di conto Managed data identifiers 208 Amazon Simple Notification Service Developer Guide Country or region Spain UK Keywords account code, account number, accountno #, accountnu mber#, bban, código cuenta, código cuenta bancaria, cuenta cliente id, customer account ID, customer account number, customer bank account id, iban, número cuenta bancaria cliente, número cuenta cliente account code, account number, accountno #, accountnu mber#, bban, customer account id, customer account number, customer bank account id, iban,
|
sns-dg-057
|
sns-dg.pdf
| 57 |
tennummer, sepa account code, account number, accountno #, accountnu mber#, bban, codice bancario, conto bancario, customer account id, customer account number, customer bank account id, iban, numero di conto Managed data identifiers 208 Amazon Simple Notification Service Developer Guide Country or region Spain UK Keywords account code, account number, accountno #, accountnu mber#, bban, código cuenta, código cuenta bancaria, cuenta cliente id, customer account ID, customer account number, customer bank account id, iban, número cuenta bancaria cliente, número cuenta cliente account code, account number, accountno #, accountnu mber#, bban, customer account id, customer account number, customer bank account id, iban, sepa Managed data identifiers 209 Amazon Simple Notification Service Developer Guide Country or region US Keywords bank account, bank acct, checking account, checking acct, deposit account, deposit acct, savings account, savings acct, chequing account, chequing acct Data identifier ARNs for financial data types The following lists the Amazon Resource Names (ARNs) for the data identifiers that you can add to your data protection policies. Financial data identifier ARNs arn:aws:dataprotection::aws:data-identifier/BankAccountNumber-DE arn:aws:dataprotection::aws:data-identifier/BankAccountNumber-ES arn:aws:dataprotection::aws:data-identifier/BankAccountNumber-FR arn:aws:dataprotection::aws:data-identifier/BankAccountNumber-GB arn:aws:dataprotection::aws:data-identifier/BankAccountNumber-IT arn:aws:dataprotection::aws:data-identifier/BankAccountNumber-US arn:aws:dataprotection::aws:data-identifier/CreditCardExpiration arn:aws:dataprotection::aws:data-identifier/CreditCardNumber Managed data identifiers 210 Amazon Simple Notification Service Developer Guide Financial data identifier ARNs arn:aws:dataprotection::aws:data-identifier/CreditCardSecurityCode Amazon SNS sensitive data types: Protected health information (PHI) The following table lists and describes the types of protected health information (PHI) that Amazon SNS can detect using managed data identifiers. Detection type Managed data identifier ID Keyword required Countries and regions Drug Enforceme nt Agency (DEA) DrugEnforcementAge ncyNumber dea number, dea registration Registration Number Health Insurance Card Number (EHIC) HealthInsuranceCar dNumber assicurazione sanitaria numero, US EU carta assicuraz ione numero, carte d’assurance maladie, carte européenne d'assurance maladie, ceam, ehic, ehic#, finlandehicnumber# , gesundheitskarte, hälsokort, health card, health card number, health insurance card, health insurance number, insurance card number, krankenve rsicherungskarte, krankenversicherun gsnummer, medical account number, Managed data identifiers 211 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Countries and regions numero conto medico, numéro d’assurance maladie, numéro de carte d’assurance, numéro de compte medical, número de cuenta médica, número de seguro de salud, número de tarjeta de seguro, sairaanho itokortin, sairausva kuutuskortti, sairausvakuutusnum ero, sjukförsäkring nummer, sjukförsä kringskort, suomi ehic-numero, tarjeta de salud, terveysko rtti, tessera sanitaria assicurazione numero, versicher ungsnummer Health Insurance Claim Number (HICN) HealthInsuranceCla imNumber US health insurance claim number, hic no, hic no., hic number, hic#, hicn, hicn#., hicno# Health insurance or medical identification number HealthInsuranceNum ber carte d'assuré social, carte vitale, insurance card FR Managed data identifiers 212 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Countries and regions Healthcare Common Procedure Coding HealthcareProcedur eCode current procedural terminology, hcpcs, US System (HCPCS) code healthcare common procedure coding system Medicare Beneficiary Number (MBN) MedicareBeneficiar yNumber mbi, medicare beneficiary National Drug Code (NDC) NationalDrugCode National Provider Identifier (NPI) National Health Service (NHS) Number NationalProviderId NhsNumber national drug code, ndc hipaa, n.p.i, national provider, npi national health service, NHS US US US GB Personal Health Number (PHN) PersonalHealthNumb er canada healthcare number, msp number, CA personal healthcare number, phn, soins de santé Keywords for health insurance and medical identification numbers To detect various types of health insurance and medical identification numbers, Amazon SNS requires a keyword to be in proximity of the numbers. This includes European Health Insurance Card numbers (EU, Finland), health insurance numbers (France), Medicare Beneficiary Identifiers (US), National Insurance numbers (UK), NHS numbers (UK), and Personal Health Numbers (Canada). The following table lists the keywords that Amazon SNS recognizes for specific countries and regions. Managed data identifiers 213 Amazon Simple Notification Service Developer Guide Country or region Keywords Canada EU Finland Canada healthcare number, msp number, personal healthcare number, phn, soins de santé assicurazione sanitaria numero, carta assicuraz ione numero, carte d’assurance maladie, carte européenne d'assurance maladie, ceam, ehic, ehic#, finlandehicnumber#, gesundhei tskarte, hälsokort, health card, health card number, health insurance card, health insurance number, insurance card number, krankenversicherungskarte, krankenve rsicherungsnummer, medical account number, numero conto medico, numéro d’assurance maladie, numéro de carte d’assurance, numéro de compte medical, número de cuenta médica, número de seguro de salud, número de tarjeta de seguro, sairaanhoitokortin, sairausva kuutuskortti, sairausvakuutusnumero, sjukförsäkring nummer, sjukförsäkringskort, suomi ehic-numero, tarjeta de salud, terveysko rtti, tessera sanitaria assicurazione numero, versicherungsnummer ehic, ehic#, finland health insurance card, finlandehicnumber#, finska sjukförsäkringskor t, hälsokort, health card, health card number, health insurance card, health insurance number, sairaanhoitokortin, sairaanho itokortin, sairausvakuutuskortti, sairausva kuutusnumero, sjukförsäkring nummer, sjukförsäkringskort, suomen sairausva kuutuskortti, suomi ehic-numero, terveyskortti Managed data identifiers 214 Amazon Simple Notification Service Developer Guide Country or region Keywords France UK US carte d'assuré social, carte vitale, insurance card national health service, NHS mbi, medicare beneficiary Data identifier ARNs for protected health information data types (PHI) The following lists the data identifier Amazon Resource Names (ARNs) that can be used in PHI data protection policies. PHI data identifier
|
sns-dg-058
|
sns-dg.pdf
| 58 |
ehic, ehic#, finland health insurance card, finlandehicnumber#, finska sjukförsäkringskor t, hälsokort, health card, health card number, health insurance card, health insurance number, sairaanhoitokortin, sairaanho itokortin, sairausvakuutuskortti, sairausva kuutusnumero, sjukförsäkring nummer, sjukförsäkringskort, suomen sairausva kuutuskortti, suomi ehic-numero, terveyskortti Managed data identifiers 214 Amazon Simple Notification Service Developer Guide Country or region Keywords France UK US carte d'assuré social, carte vitale, insurance card national health service, NHS mbi, medicare beneficiary Data identifier ARNs for protected health information data types (PHI) The following lists the data identifier Amazon Resource Names (ARNs) that can be used in PHI data protection policies. PHI data identifier ARNs arn:aws:dataprotection::aws:data-identifier/DrugEnforcementAgencyNumber-US arn:aws:dataprotection::aws:data-identifier/HealthcareProcedureCode-US arn:aws:dataprotection::aws:data-identifier/HealthInsuranceCardNumber-EU arn:aws:dataprotection::aws:data-identifier/HealthInsuranceClaimNumber-US arn:aws:dataprotection::aws:data-identifier/HealthInsuranceNumber-FR arn:aws:dataprotection::aws:data-identifier/MedicareBeneficiaryNumber-US arn:aws:dataprotection::aws:data-identifier/NationalDrugCode-US arn:aws:dataprotection::aws:data-identifier/NationalInsuranceNumber-GB arn:aws:dataprotection::aws:data-identifier/NationalProviderId-US arn:aws:dataprotection::aws:data-identifier/NhsNumber-GB arn:aws:dataprotection::aws:data-identifier/PersonalHealthNumber-CA Managed data identifiers 215 Amazon Simple Notification Service Developer Guide Amazon SNS sensitive data types: Personally identifiable information (PII) The following table lists and describes the types of personally identifiable information (PII) that Amazon SNS can detect using managed data identifiers. Detection type Managed data identifier ID Keyword required Additional information Countries and regions Birth date DateOfBirth dob, date of birth, birthdate Support includes most date Any , birth date, formats, such birthday, b-day, as all digits and bday combinations of digits and names of months. Date components can be separated by spaces, slashes (/), or hyphens (‐). – – – cep, código de endereçamento postal, codigo de endereçam ento postal cadastro nacional da pessoa jurídica, cadastro nacional da pessoa juridica, cnpj Cadastro de pessoas fisicas, cadastro de Brazil Brazil Brazil 216 Código de Endereçamento Postal (CEP) CepCode Cnpj Cadastro Nacional da Pessoa Jurídica (CNPJ) CpfCode Cadastro de Pessoas Físicas (CPF) Managed data identifiers Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Driver’s license identification number DriversLicense pessoas físicas, cadastro de pessoa física, cadastro de pessoa fisica, cpf Yes, see Keywords for driver’s license identification numbers. – Australia, Austria, Belgium, Bulgaria, Canada, Croatia, Cyprus, Czech Republic, Denmark, Estonia, Finland, France, Germany, Greece, Hungary, Ireland, Italy, Latvia, Lithuania , Luxembourg, Malta, Netherlan ds, Poland, Portugal, Romania, Slovakia, Slovenia, Spain, Sweden, UK, US Managed data identifiers 217 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Electoral roll number Electoral RollNumber electoral#, electoral #, – UK electoralnumber, electoral number, electoralroll#, electoral roll#, electoral roll #, electoral roll no., electoral roll number, electoralrollno Individua l taxpayer Individua lTaxIdent Yes, see Keywords identification ificationNumber for taxpayer identification and reference numbers. Yes, see Keywords for national identific ation numbers. InseeCode National Institute for Statistics and Economic Studies (INSEE) – – US France Managed data identifiers 218 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions National identification NationalI dentifica Yes, see Keywords for This includes Documento Germany, Italy, Spain number tionNumber national identific Nacional de ation numbers. Identidad (DNI) identifiers (Spain), Codice fiscale codes (Italy), and National Identity Card numbers (German). National Insurance NationalI nsuranceN insurance no., insurance – UK Number (NINO) umber Número de identidad de extranjero (NIE) NieNumber number, insurance #, national insurance number, nationali nsurance# , nationali nsurancen umber, nin, nino Yes, see Keywords for taxpayer identification and reference numbers. – Spain Managed data identifiers 219 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Número de Identificación Fiscal (NIF) NifNumber Passport number PassportNumber – – Yes, see Keywords for taxpayer identification and reference numbers. Yes, see Keywords for passport numbers. Spain Canada, France, Germany, Italy, Spain, UK, US Managed data identifiers 220 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Permanent residence number Permanent Residence Number – Canada carte résident permanent , numéro carte résident permanent, numéro résident permanent , permanent resident card, permanent resident card number, permanent resident no, permanent resident no., permanent resident number, pr no, pr no., pr non, pr number, résident permanent no., résident permanent non Managed data identifiers 221 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Phone number PhoneNumber Brazil: keywords also include: cel, This includes toll-free Brazil, Canada, France, celular, fone, numbers in Germany, Italy, móvel, número the US and fax Spain, UK, US residenci al, numero residencial, telefone Others: cell, contact, fax, fax number, mobile, phone, phone number, tel, telephone , telephone number numbers. If a keyword is in proximity of the data, the number doesn’t have to include a country code. If a keyword isn’t in proximity of the data, the number has to include a country code. Postal Code PostalCode No Registro Geral (RG) RgNumber Social Insurance Number (SIN) SocialIns uranceNumber Yes, see Keywords for national identific ation numbers. canadian id, numéro d'assurance sociale, social insurance
|
sns-dg-059
|
sns-dg.pdf
| 59 |
celular, fone, numbers in Germany, Italy, móvel, número the US and fax Spain, UK, US residenci al, numero residencial, telefone Others: cell, contact, fax, fax number, mobile, phone, phone number, tel, telephone , telephone number numbers. If a keyword is in proximity of the data, the number doesn’t have to include a country code. If a keyword isn’t in proximity of the data, the number has to include a country code. Postal Code PostalCode No Registro Geral (RG) RgNumber Social Insurance Number (SIN) SocialIns uranceNumber Yes, see Keywords for national identific ation numbers. canadian id, numéro d'assurance sociale, social insurance number, sin – – – Canada Brazil Canada Managed data identifiers 222 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Social Security number (SSN) Ssn Spain – número de la seguridad – Spain, US social, social security no., social security no. número de la seguridad social, social security number, socialsec urityno#, ssn, ssn# US – social security, ss#, ssn TaxId Taxpayer identification or reference number Yes, see Keywords This includes TIN (France); France, Germany, Spain, for taxpayer Steueride UK identification ntifikati and reference onsnummer numbers. (Germany); CIF (Spain); and TRN, UTR (UK). US postal code ZipCode zip code, zip+4 – US Managed data identifiers 223 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Mailing address Address No Although a keyword Australia, Canada, France, isn't required, Germany, Italy, Spain, UK, US detection requires the address to include the name of a city or place and a ZIP or Postal Code. Electronic mail address EmailAddress email, email address, e mail, e mail address – Any Managed data identifiers 224 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Global Positioni ng System (GPS) coordinates LatLong coordinate, coordinates, lat Amazon SNS can detect GPS Any long, latitude coordinates if longitude , location, position the latitude and longitude coordinates are stored as a pair and they're in Decimal Degrees (DD) format, for example, 41.948614 ,-87.6553 11. Support doesn't include coordinates in Degrees Decimal Minutes (DDM) format, for example 41°56.9168'N 87°39.3187'W, or Degrees, Minutes, Seconds (DMS) format, for example 41°56'55. 0104"N 87°39'19. 1196"W. Managed data identifiers 225 Amazon Simple Notification Service Developer Guide Detection type Managed data identifier ID Keyword required Additional information Countries and regions Full name Name No Vehicle identific ation number VehicleId entificat Fahrgeste llnummer, niv, (VIN) ionNumber numarul de identificare, numarul seriei Any Any Amazon SNS can detect full names only. Support is limited to Latin character sets. Amazon SNS can detect VINs that consist of a 17-character sequence and de sasiu, serie adhere to the sasiu, numer ISO 3779 and VIN, Número de 3780 standards. Identificação do These standards Veículo, Número were designed de Identificación for worldwide de Automóvil use. es, numéro d'identification du véhicule, vehicle identific ation number, vin, VIN numeris Keywords for driver’s license identification numbers To detect various types of driver’s license identification numbers, Amazon SNS requires a keyword to be in proximity of the numbers. The following table lists the keywords that Amazon SNS recognizes for specific countries and regions. Managed data identifiers 226 Amazon Simple Notification Service Developer Guide Country or region Keywords Australia Austria Belgium Bulgaria Canada Croatia Cyprus dl# dl:, dl :, dlno# driver licence, driver license, driver permit, drivers lic., drivers licence, driver's licence, drivers license, driver's license, drivers permit, driver's permit, drivers permit number, driving licence, driving license, driving permit führerschein, fuhrerschein, führerschein republik österreich, fuhrerschein republik osterreich fuehrerschein, fuehrerschein- nr, fuehrersc heinnummer, fuhrerschein, führerschein, fuhrerschein- nr, führerschein- nr, fuhrersch einnummer, führerscheinnummer, numéro permis conduire, permis de conduire, rijbewijs, rijbewijsnummer превозно средство, свидетелство за управление на моторно, свидетелство за управление на мпс, сумпс, шофьорска книжка dl#, dl:, dlno#, driver licence, driver licences, driver license, driver licenses, driver permit, drivers lic., drivers licence, driver's licence, drivers licences, driver's licences, drivers license, driver's license, drivers licenses, driver's licenses, drivers permit, driver's permit, drivers permit number, driving licence, driving license, driving permit, permis de conduire vozačka dozvola άδεια οδήγησης Managed data identifiers 227 Amazon Simple Notification Service Developer Guide Country or region Keywords Czech Republic Denmark Estonia Finland France Germany Greece Hungary Ireland Italy Latvia číslo licence, císlo licence řidiče, číslo řidičskéh o průkazu, ovladače lic., povolení k jízdě, povolení řidiče, řidiči povolení, řidičský prúkaz, řidičský průkaz kørekort, kørekortnummer juhi litsentsi number, juhiloa number, juhiluba, juhiluba number ajokortin numero, ajokortti, förare lic., körkort, körkort nummer, kuljettaja lic., permis de conduire permis de conduire fuehrerschein, fuehrerschein- nr, fuehrersc heinnummer, fuhrerschein, führerschein, fuhrerschein- nr, führerschein- nr, fuhrersch einnummer, führerscheinnummer δεια οδήγησης, adeia odigisis illesztőprogramok lic, jogosítvány, jogsi, licencszám, vezető engedély, vezetői engedély ceadúnas tiomána patente di guida, patente di guida numero, patente guida, patente
|
sns-dg-060
|
sns-dg.pdf
| 60 |
Keywords Czech Republic Denmark Estonia Finland France Germany Greece Hungary Ireland Italy Latvia číslo licence, císlo licence řidiče, číslo řidičskéh o průkazu, ovladače lic., povolení k jízdě, povolení řidiče, řidiči povolení, řidičský prúkaz, řidičský průkaz kørekort, kørekortnummer juhi litsentsi number, juhiloa number, juhiluba, juhiluba number ajokortin numero, ajokortti, förare lic., körkort, körkort nummer, kuljettaja lic., permis de conduire permis de conduire fuehrerschein, fuehrerschein- nr, fuehrersc heinnummer, fuhrerschein, führerschein, fuhrerschein- nr, führerschein- nr, fuhrersch einnummer, führerscheinnummer δεια οδήγησης, adeia odigisis illesztőprogramok lic, jogosítvány, jogsi, licencszám, vezető engedély, vezetői engedély ceadúnas tiomána patente di guida, patente di guida numero, patente guida, patente guida numero autovadītāja apliecība, licences numurs, vadītāja apliecība, vadītāja apliecības numurs, vadītāja atļauja, vadītāja licences numurs, vadītāji lic. Lithuania vairuotojo pažymėjimas Managed data identifiers 228 Amazon Simple Notification Service Developer Guide Country or region Keywords Luxembourg Malta Netherlands Poland Portugal Romania Slovakia Slovenia Spain Sweden fahrerlaubnis, führerschäin liċenzja tas-sewqan permis de conduire, rijbewijs, rijbewijsnummer numer licencyjny, prawo jazdy, zezwolenie na prowadzenie carta de condução, carteira de habilitação, carteira de motorist, carteira habilitação, carteira motorist, licença condução, licença de condução, número de licença, número licença, permissão condução, permissão de condução numărul permisului de conducere, permis de conducere číslo licencie, číslo vodičského preukazu, ovládače lic., povolenia vodičov, povolenie jazdu, povolenie na jazdu, povolenie vodiča, vodičský preukaz vozniško dovoljenje carnet conducer, el carnet de conducer, licencia conducer, licencia de manejo, número carnet conducer, número de carnet de conducer, número de permiso conducer, número de permiso de conducer, número licencia conducer, número permiso conducer, permiso conducción, permiso conducer, permiso de conducción ajokortin numero, dlno# ajokortti, drivere lic., förare lic., körkort, körkort nummer, körkortsn ummer, kuljettajat lic. Managed data identifiers 229 Amazon Simple Notification Service Developer Guide Country or region Keywords UK US dl#, dl:, dlno#, driver licence, driver licences, driver license, driver licenses, driver permit, drivers lic., drivers licence, driver's licence, drivers licences, driver's licences, drivers license, driver's license, drivers licenses, driver's licenses, drivers permit, driver's permit, drivers permit number, driving licence, driving license, driving permit dl#, dl:, dlno#, driver licence, driver licences, driver license, driver licenses, driver permit, drivers lic., drivers licence, driver's licence, drivers licences, driver's licences, drivers license, driver's license, drivers licenses, driver's licenses, drivers permit, driver's permit, drivers permit number, driving licence, driving license, driving permit Keywords for national identification numbers To detect various types of national identification numbers, Amazon SNS requires a keyword to be in close proximity to the numbers. This includes Documento Nacional de Identidad (DNI) identifiers (Spain), French National Institute for Statistics and Economic Studies (INSEE) codes, German National Identity Card numbers, and Registro Geral (RG) numbers (Brazil). The following table lists the keywords that Amazon SNS recognizes for specific countries and regions. Country or region Keywords Brazil France registro geral, rg assurance sociale, carte nationale d’identit é, cni, code sécurité sociale, French social security number, fssn#, insee, insurance Managed data identifiers 230 Amazon Simple Notification Service Developer Guide Country or region Keywords Germany Italy Spain number, national id number, nationalid#, numéro d'assurance, sécurité sociale, sécurité sociale non., sécurité sociale numéro, social, social security, social security number, socialsecuritynumber, ss#, ssn, ssn# ausweisnummer, id number, identification number, identity number, insurance number, personal id, personalausweis codice fiscal, dati anagrafici, ehic, health card, health insurance card, p. iva, partita i.v.a., personal data, tax code, tessera sanitaria dni, dni#, dninúmero#, documento nacional de identidad, identidad único, identidad único#, insurance number, national identific ation number, national identity, nationalid#, nationalidno#, número nacional identidad , personal identification number, personal identity no, unique identity number, uniqueid# Keywords for passport numbers To detect various types of passport numbers, Amazon SNS requires a keyword to be in proximity of the numbers. The following table lists the keywords that Amazon SNS recognizes for specific countries and regions. Country or region Keywords Canada France passeport, passeport#, passport, passport#, passportno, passportno# numéro de passeport, passeport, passeport #, passeport #, passeportn °, passeport n °, passeportNon, passeport non Managed data identifiers 231 Amazon Simple Notification Service Developer Guide Country or region Keywords Germany Italy Spain UK US ausstellungsdatum, ausstellungsort, geburtsdatum, passport, passports, reisepass, reisepass–nr, reisepassnummer italian passport number, numéro passeport , numéro passeport italien, passaporto, passaporto italiana, passaporto numero, passport number, repubblica italiana passaporto españa pasaporte, libreta pasaporte, número pasaporte, pasaporte, passport, passport book, passport no, passport number, spain passport passeport #, passeport n °, passeportNon, passeport non, passeportn °, passport #, passport no, passport number, passport#, passportid passport, travel document Keywords for taxpayer identification and reference numbers To detect various types of taxpayer identification and reference numbers, Amazon SNS requires a keyword to be in proximity of the numbers. The following table lists the keywords that Amazon SNS recognizes for specific countries and regions. Country or region Keywords Brazil cadastro de pessoa física, cadastro de pessoa fisica, cadastro de pessoas físicas, cadastro de pessoas fisicas, cadastro nacional da pessoa
|
sns-dg-061
|
sns-dg.pdf
| 61 |
pasaporte, passport, passport book, passport no, passport number, spain passport passeport #, passeport n °, passeportNon, passeport non, passeportn °, passport #, passport no, passport number, passport#, passportid passport, travel document Keywords for taxpayer identification and reference numbers To detect various types of taxpayer identification and reference numbers, Amazon SNS requires a keyword to be in proximity of the numbers. The following table lists the keywords that Amazon SNS recognizes for specific countries and regions. Country or region Keywords Brazil cadastro de pessoa física, cadastro de pessoa fisica, cadastro de pessoas físicas, cadastro de pessoas fisicas, cadastro nacional da pessoa jurídica, cadastro nacional da pessoa juridica, cnpj, cpf Managed data identifiers 232 Amazon Simple Notification Service Developer Guide Country or region Keywords France Germany Spain UK US numéro d'identification fiscale, tax id, tax identification number, tax number, tin, tin# identifikationsnummer, steuer id, steueride ntifikationsnummer, steuernummer, tax id, tax identification number, tax number cif, cif número, cifnúmero#, nie, nif, número de contribuyente, número de identidad de extranjero, número de identificación fiscal, número de impuesto corporativo, personal tax number, tax id, tax identification number, tax number, tin, tin# paye, tax id, tax id no., tax id number, tax identification, tax identification#, tax no., tax number, tax reference, tax#, taxid#, temporary reference number, tin, trn, unique tax reference, unique taxpayer reference, utr individual taxpayer identification number, itin, i.t.i.n. Data identifier ARNs for personally identifiable information (PII) The following table lists the Amazon Resource Names (ARNs) for the data identifiers that you can add to your data protection policies. PII data identifier ARNs arn:aws:dataprotection::aws:data-identifier/Address arn:aws:dataprotection::aws:data-identifier/CepCode-BR arn:aws:dataprotection::aws:data-identifier/Cnpj-BR Managed data identifiers 233 Amazon Simple Notification Service Developer Guide PII data identifier ARNs arn:aws:dataprotection::aws:data-identifier/CpfCode-BR arn:aws:dataprotection::aws:data-identifier/DateOfBirth arn:aws:dataprotection::aws:data-identifier/DriversLicense-AT arn:aws:dataprotection::aws:data-identifier/DriversLicense-AU arn:aws:dataprotection::aws:data-identifier/DriversLicense-BE arn:aws:dataprotection::aws:data-identifier/DriversLicense-BG arn:aws:dataprotection::aws:data-identifier/DriversLicense-CA arn:aws:dataprotection::aws:data-identifier/DriversLicense-CY arn:aws:dataprotection::aws:data-identifier/DriversLicense-CZ arn:aws:dataprotection::aws:data-identifier/DriversLicense-DE arn:aws:dataprotection::aws:data-identifier/DriversLicense-DK arn:aws:dataprotection::aws:data-identifier/DriversLicense-EE arn:aws:dataprotection::aws:data-identifier/DriversLicense-ES arn:aws:dataprotection::aws:data-identifier/DriversLicense-FI arn:aws:dataprotection::aws:data-identifier/DriversLicense-FR arn:aws:dataprotection::aws:data-identifier/DriversLicense-GB arn:aws:dataprotection::aws:data-identifier/DriversLicense-GR arn:aws:dataprotection::aws:data-identifier/DriversLicense-HR arn:aws:dataprotection::aws:data-identifier/DriversLicense-HU arn:aws:dataprotection::aws:data-identifier/DriversLicense-IE Managed data identifiers 234 Amazon Simple Notification Service Developer Guide PII data identifier ARNs arn:aws:dataprotection::aws:data-identifier/DriversLicense-IT arn:aws:dataprotection::aws:data-identifier/DriversLicense-LT arn:aws:dataprotection::aws:data-identifier/DriversLicense-LU arn:aws:dataprotection::aws:data-identifier/DriversLicense-LV arn:aws:dataprotection::aws:data-identifier/DriversLicense-MT arn:aws:dataprotection::aws:data-identifier/DriversLicense-NL arn:aws:dataprotection::aws:data-identifier/DriversLicense-PL arn:aws:dataprotection::aws:data-identifier/DriversLicense-PT arn:aws:dataprotection::aws:data-identifier/DriversLicense-RO arn:aws:dataprotection::aws:data-identifier/DriversLicense-SE arn:aws:dataprotection::aws:data-identifier/DriversLicense-SI arn:aws:dataprotection::aws:data-identifier/DriversLicense-SK arn:aws:dataprotection::aws:data-identifier/DriversLicense-US arn:aws:dataprotection::aws:data-identifier/ElectoralRollNumber-GB arn:aws:dataprotection::aws:data-identifier/EmailAddress arn:aws:dataprotection::aws:data-identifier/IndividualTaxIdentificationNumber-US arn:aws:dataprotection::aws:data-identifier/InseeCode-FR arn:aws:dataprotection::aws:data-identifier/LatLong arn:aws:dataprotection::aws:data-identifier/Name arn:aws:dataprotection::aws:data-identifier/NationalIdentificationNumber-DE Managed data identifiers 235 Amazon Simple Notification Service Developer Guide PII data identifier ARNs arn:aws:dataprotection::aws:data-identifier/NationalIdentificationNumber-ES arn:aws:dataprotection::aws:data-identifier/NationalIdentificationNumber-IT arn:aws:dataprotection::aws:data-identifier/NieNumber-ES arn:aws:dataprotection::aws:data-identifier/NifNumber-ES arn:aws:dataprotection::aws:data-identifier/PassportNumber-CA arn:aws:dataprotection::aws:data-identifier/PassportNumber-DE arn:aws:dataprotection::aws:data-identifier/PassportNumber-ES arn:aws:dataprotection::aws:data-identifier/PassportNumber-FR arn:aws:dataprotection::aws:data-identifier/PassportNumber-GB arn:aws:dataprotection::aws:data-identifier/PassportNumber-IT arn:aws:dataprotection::aws:data-identifier/PassportNumber-US arn:aws:dataprotection::aws:data-identifier/PermanentResidenceNumber-CA arn:aws:dataprotection::aws:data-identifier/PhoneNumber-BR arn:aws:dataprotection::aws:data-identifier/PhoneNumber-DE arn:aws:dataprotection::aws:data-identifier/PhoneNumber-ES arn:aws:dataprotection::aws:data-identifier/PhoneNumber-FR arn:aws:dataprotection::aws:data-identifier/PhoneNumber-GB arn:aws:dataprotection::aws:data-identifier/PhoneNumber-IT arn:aws:dataprotection::aws:data-identifier/PhoneNumber-US arn:aws:dataprotection::aws:data-identifier/PostalCode-CA Managed data identifiers 236 Amazon Simple Notification Service Developer Guide PII data identifier ARNs arn:aws:dataprotection::aws:data-identifier/RgNumber-BR arn:aws:dataprotection::aws:data-identifier/SocialInsuranceNumber-CA arn:aws:dataprotection::aws:data-identifier/Ssn-ES arn:aws:dataprotection::aws:data-identifier/Ssn-US arn:aws:dataprotection::aws:data-identifier/TaxId-DE arn:aws:dataprotection::aws:data-identifier/TaxId-ES arn:aws:dataprotection::aws:data-identifier/TaxId-FR arn:aws:dataprotection::aws:data-identifier/TaxId-GB arn:aws:dataprotection::aws:data-identifier/VehicleIdentificationNumber arn:aws:dataprotection::aws:data-identifier/ZipCode-US Using custom data identifiers in Amazon SNS Custom data identifiers (CDIs) let you define your own custom regular expressions that can be used in your data protection policy. Using custom data identifiers, you can target business-specific personally identifiable information (PII) use cases that managed data identifiers can't provide. For example, you can use a custom data identifier to look for company-specific employee IDs. Custom data identifiers can be used in conjunction with managed data identifiers. What are custom data identifiers? Custom data identifiers (CDIs) let you define your own custom regular expressions that can be used in your data protection policy. Using custom data identifiers, you can target business-specific personally identifiable information (PII) use cases that managed data identifiers can't provide. For example, you can use a custom data identifier to look for company-specific employee IDs. Custom data identifiers can be used in conjunction with managed data identifiers. Custom data identifiers 237 Amazon Simple Notification Service Developer Guide Using custom data identifiers in your data protection policy The following data protection policy instructs the Amazon SNS topic to detect payloads that carry company-specific employee IDs, then mask these IDs using the hash symbol (#). 1. Create a Configuration block within your data protection policy. 2. 3. Enter a Name for your custom data identifier. For example, EmployeeId. Enter a Regex for your custom data identifier. For example, EID-\d{9}-US. 4. Refer to the following custom data identifier in a policy statement. { "Name": "__example_data_protection_policy", "Description": "Example data protection policy", "Version": "2021-06-01", "Configuration": { "CustomDataIdentifier": [ {"Name": "EmployeeId", "Regex": "EID-\d{9}-US"} ] }, "Statement": [ { "DataDirection": "Inbound", "Principal": ["*"], "DataIdentifier": [ "EmployeeId" ], "Operation": { "Deidentify": { "MaskConfig": { "MaskWithCharacter": "#" } } } } ] } 5. (Optional) Continue to add additional custom data identifiers to the Configuration block as needed. Data protection policies currently support a maximum of 10 custom data identifiers. Custom data identifiers 238 Amazon Simple Notification Service Developer Guide Custom data identifier constraints Amazon SNS custom data identifiers have the following limitations: • A maximum of 10 custom data identifiers are supported for each data protection policy. • Custom data identifier names have a maximum length of 128 characters. The following characters are supported: • Alphanumeric: (a-zA-Z0-9) • Symbols: ( '_' | '-' ) • RegEx has a maximum length of 200 characters. The following characters are supported: • Alphanumeric: (a-zA-Z0-9) • Symbols: ( '_' | '#' | '=' | '@' |'/' | ';' | ',' | '-' |
|
sns-dg-062
|
sns-dg.pdf
| 62 |
Custom data identifiers 238 Amazon Simple Notification Service Developer Guide Custom data identifier constraints Amazon SNS custom data identifiers have the following limitations: • A maximum of 10 custom data identifiers are supported for each data protection policy. • Custom data identifier names have a maximum length of 128 characters. The following characters are supported: • Alphanumeric: (a-zA-Z0-9) • Symbols: ( '_' | '-' ) • RegEx has a maximum length of 200 characters. The following characters are supported: • Alphanumeric: (a-zA-Z0-9) • Symbols: ( '_' | '#' | '=' | '@' |'/' | ';' | ',' | '-' | ' ' ) • RegEx reserved characters: ( '^' | '$' | '?' | '[' | ']' | '{' | '}' | '|' | '\\' | '*' | '+' | '.' ) • Custom data identifiers cannot share the same name as a managed data identifier. • Custom data identifiers must be specified in every data protection policy for each Amazon SNS topic. Custom data identifiers 239 Amazon Simple Notification Service Developer Guide Amazon SNS message delivery This topic describes how Amazon SNS handles message delivery across various scenarios. You'll learn about raw message delivery, where Amazon SNS delivers messages in their original, unmodified format to the endpoint. You'll also discover how to send messages from an Amazon SNS topic to an Amazon SQS queue in a different AWS account, providing insights into cross- account messaging. This topic provides information on the delivery of Amazon SNS messages to an Amazon SQS queue or a Lambda function in different AWS Regions, how cross-region delivery works, and the considerations involved. Additionally, you'll learn how to monitor and interpret message delivery status, which provides critical information on whether messages were successfully delivered or encountered issues. In cases where message delivery fails, you'll understand the message delivery retry process, including how Amazon SNS automatically attempts to redeliver messages to ensure they reach their intended destinations. This topic also discusses the use of dead-letter queues to capture messages that could not be delivered after multiple attempts, enabling you to analyze and troubleshoot these failures effectively. Amazon SNS raw message delivery To avoid having Amazon Data Firehose, Amazon SQS, and HTTP/S endpoints process the JSON formatting of messages, Amazon SNS allows raw message delivery: • When you enable raw message delivery for Amazon Data Firehose or Amazon SQS endpoints, any Amazon SNS metadata is stripped from the published message and the message is sent as is. • When you enable raw message delivery for HTTP/S endpoints, the HTTP header x-amz-sns- rawdelivery with its value set to true is added to the message, indicating that the message has been published without JSON formatting. • When you enable raw message delivery for HTTP/S endpoints, the message body, client IP, and the required headers are delivered. When you specify message attributes, it won't be sent. • When you enable raw message delivery for Firehose endpoints, the message body is delivered. When you specify message attributes, it won't be sent. Raw message delivery 240 Amazon Simple Notification Service Developer Guide To enable raw message delivery using an AWS SDK, you must use the SetSubscriptionAttribute API action and set the value of the RawMessageDelivery attribute to true. Enabling raw message delivery using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. On the Topics page, choose a topic subscribed to an Firehose, Amazon SQS, or HTTP/S endpoint. 4. On the MyTopic page, in the Subscription section, choose a subscription and choose Edit. 5. On the Edit EXAMPLE1-23bc-4567-d890-ef12g3hij456 page, in the Details section, choose Enable raw message delivery. 6. Choose Save changes. Message format examples In the following examples, the same message is sent to the same Amazon SQS queue twice. The only difference is that raw message delivery is disabled for the first message, and enabled for the second. • Raw message delivery is disabled { "Type": "Notification", "MessageId": "dc1e94d9-56c5-5e96-808d-cc7f68faa162", "TopicArn": "arn:aws:sns:us-east-2:111122223333:ExampleTopic1", "Subject": "TestSubject", "Message": "This is a test message.", "Timestamp": "2021-02-16T21:41:19.978Z", "SignatureVersion": "1", "Signature": "FMG5tlZhJNHLHUXvZgtZzlk24FzVa7oX0T4P03neeXw8ZEXZx6z35j2FOTuNYShn2h0bKNC/ zLTnMyIxEzmi2X1shOBWsJHkrW2xkR58ABZF+4uWHEE73yDVR4SyYAikP9jstZzDRm +bcVs8+T0yaLiEGLrIIIL4esi1llhIkgErCuy5btPcWXBdio2fpCRD5x9oR6gmE/ rd5O7lX1c1uvnv4r1Lkk4pqP2/iUfxFZva1xLSRvgyfm6D9hNklVyPfy +7TalMD0lzmJuOrExtnSIbZew3foxgx8GT+lbZkLd0ZdtdRJlIyPRP44eyq78sU0Eo/ LsDr0Iak4ZDpg8dXg==", Enabling raw message delivery using the AWS Management Console 241 Amazon Simple Notification Service Developer Guide "SigningCertURL": "https://sns.us-east-2.amazonaws.com/ SimpleNotificationService-010a507c1833636cd94bdb98bd93083a.pem", "UnsubscribeURL": "https://sns.us-east-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- east-2:111122223333:ExampleTopic1:e1039402-24e7-40a3-a0d4-797da162b297" } • Raw message delivery is enabled This is a test message. Message attributes and raw message delivery for Amazon SQS subscriptions Amazon SNS supports the delivery of message attributes, which allow you to provide structured metadata items, such as timestamps, geospatial data, signatures, and identifiers, about the message. For Amazon SQS subscriptions with Raw Message Delivery enabled, a maximum of 10 message attributes can be sent. To send more than 10 message attributes, you must disable Raw Message Delivery. However, Amazon SNS discards messages with more than 10 message attributes directed towards Amazon SQS subscriptions
|
sns-dg-063
|
sns-dg.pdf
| 63 |
"UnsubscribeURL": "https://sns.us-east-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- east-2:111122223333:ExampleTopic1:e1039402-24e7-40a3-a0d4-797da162b297" } • Raw message delivery is enabled This is a test message. Message attributes and raw message delivery for Amazon SQS subscriptions Amazon SNS supports the delivery of message attributes, which allow you to provide structured metadata items, such as timestamps, geospatial data, signatures, and identifiers, about the message. For Amazon SQS subscriptions with Raw Message Delivery enabled, a maximum of 10 message attributes can be sent. To send more than 10 message attributes, you must disable Raw Message Delivery. However, Amazon SNS discards messages with more than 10 message attributes directed towards Amazon SQS subscriptions with Raw Message Delivery enabled, treating them as client-side errors. Sending Amazon SNS messages to an Amazon SQS queue in a different account This document describes how to publish a notification to an Amazon SNS topic with one or more subscriptions to Amazon SQS queues in another account. You set up the topic and queues the same way you would if they were in the same account (see Fanout Amazon SNS notifications to Amazon SQS queues for asynchronous processing). The major difference is how you handle subscription confirmation, and that depends on how you subscribe the queue to the topic. It is a best practice to follow the steps referenced in the Queue owner creates subscription section when possible, because confirmation is automatic when the queue owner creates the subscription. Message attributes and raw message delivery for Amazon SQS subscriptions 242 Amazon Simple Notification Service Developer Guide Note If the Amazon SQS queue has a high volume of messages, we recommend that the queue owner creates the subscription. Queue owner creates subscription The account that created the Amazon SQS queue is the queue owner. When the queue owner creates a subscription, the subscription doesn't require confirmation. The queue begins to receive notifications from the topic as soon as the Subscribe action completes. To let the queue owner subscribe to the topic owner's topic, the topic owner must give the queue owner's account permission to call the Subscribe action on the topic. Step 1: To set the topic policy using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. Select a topic and then choose Edit. 4. On the Edit MyTopic page, expand the Access policy section. 5. Enter the following policy: { "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "111122223333" }, "Action": "sns:Subscribe", "Resource": "arn:aws:sns:us-east-2:123456789012:MyTopic" } ] } This policy gives account 111122223333 permission to call sns:Subscribe on MyTopic in account 123456789012. Queue owner creates subscription 243 Amazon Simple Notification Service Developer Guide A user with the credentials for account 111122223333 can subscribe to MyTopic. This permission allows the account ID to delegate permission to their IAM user/role. Only the root account or administrator users are allowed to call sns:Subscribe. The IAM user/role must also have sns:subscribe to allow their queue to subscribe. 6. Choose Save changes. A user with the credentials for account 111122223333 can subscribe to MyTopic. Step 2: To add an Amazon SQS queue subscription to a topic in another AWS account using the AWS Management Console Before you begin, make sure you have the ARNs for your topic and queue, and that you have given permission to the topic to send messages to the queue. 1. Sign in to the Amazon SQS console. 2. On the navigation panel, choose Queues. 3. From the list of queues, choose the queue to subscribe to the Amazon SNS topic. 4. Choose Subscribe to Amazon SNS topic. 5. From the Specify an Amazon SNS topic available for this queue menu, choose the Amazon SNS topic for your queue. 6. Choose Enter Amazon SNS topic ARN and then enter the topic's Amazon Resource Name (ARN). 7. Choose Save. Note • To be able to communicate with the service, the queue must have permissions for Amazon SNS. • Because you are the owner of the queue, you don't have to confirm the subscription. A user who does not own the queue creates a subscription Any user who creates a subscription but isn't the owner of the queue must confirm the subscription. A user who does not own the queue creates a subscription 244 Amazon Simple Notification Service Developer Guide When you use the Subscribe action, Amazon SNS sends a subscription confirmation to the queue. The subscription is displayed in the Amazon SNS console, with its subscription ID set to Pending Confirmation. To confirm the subscription, a user with permission to read messages from the queue must retrieve the subscription confirmation URL, and the subscription owner must confirm the subscription using the subscription confirmation URL. Until the subscription is confirmed, no notifications published to the topic are sent to the queue. To confirm the subscription, you can use the Amazon SQS
|
sns-dg-064
|
sns-dg.pdf
| 64 |
a subscription 244 Amazon Simple Notification Service Developer Guide When you use the Subscribe action, Amazon SNS sends a subscription confirmation to the queue. The subscription is displayed in the Amazon SNS console, with its subscription ID set to Pending Confirmation. To confirm the subscription, a user with permission to read messages from the queue must retrieve the subscription confirmation URL, and the subscription owner must confirm the subscription using the subscription confirmation URL. Until the subscription is confirmed, no notifications published to the topic are sent to the queue. To confirm the subscription, you can use the Amazon SQS console or the ReceiveMessage action. Note Before you subscribe an endpoint to the topic, make sure that the queue can receive messages from the topic by setting the sqs:SendMessage permission for the queue. For more information, see Step 2: Give permission to the Amazon SNS topic to send messages to the Amazon SQS queue. Step 1: To add an Amazon SQS queue subscription to a topic in another AWS account using the AWS Management Console Before you begin, make sure you have the ARNs for your topic and queue, and that you have given permission to the topic to send messages to the queue. 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Subscriptions. 3. On the Subscriptions page, choose Create subscription. 4. On the Create subscription page, in the Details section, do the following: a. b. c. For Topic ARN, enter the ARN of the topic. For Protocol, choose Amazon SQS. For Endpoint, enter the ARN of the queue. d. Choose Create subscription. A user who does not own the queue creates a subscription 245 Amazon Simple Notification Service Developer Guide Note • To be able to communicate with the service, the queue must have permissions for Amazon SNS. The following is an example policy statement that allows the Amazon SNS topic to send a message to the Amazon SQS queue. { "Sid": "Stmt1234", "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-west-2:111111111111:QueueName", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-west-2:555555555555:TopicName" } } } Step 2: To confirm a subscription using the AWS Management Console 1. 2. Sign in to the Amazon SQS console. Select the queue that has a pending subscription to the topic. 3. Choose Send and receive messages, and then choose Poll for messages. A message with the subscription confirmation is received in the queue. 4. In the Body column, do the following: a. b. Choose More Details. In the Message Details dialog box, find and note the SubscribeURL value. This is your subscription link (example below). For additional details on API token validation, see ConfirmSubscription in the Amazon SNS API Reference. A user who does not own the queue creates a subscription 246 Amazon Simple Notification Service Developer Guide https://sns.us-west-2.amazonaws.com/? Action=ConfirmSubscription&TopicArn=arn:aws:sns:us- east-2:123456789012:MyTopic&Token=2336412f37fb... c. Make a note of the subscription confirmation link. The URL must be passed from the queue owner to the subscription owner. The subscription owner must enter the URL into the Amazon SNS console. 5. Log in as the subscription owner to the Amazon SNS console The subscription owner performs the confirmation. 6. Choose the relevant topic. 7. Choose the relevant subscription in the topic's subscription listings table. It is labeled as "Pending confirmation". 8. Choose Confirm subscription. 9. A modal appears prompting the subscription confirmation link. Paste the subscription confirmation link. 10. Select the Confirm subscription in the modal. An XML response is displayed, for example: <ConfirmSubscriptionResponse> <ConfirmSubscriptionResult> <SubscriptionArn>arn:aws:sns:us-east-2:123456789012:MyTopic:1234a567- bc89-012d-3e45-6fg7h890123i</SubscriptionArn> </ConfirmSubscriptionResult> <ResponseMetadata> <RequestId>abcd1efg-23hi-jkl4-m5no-p67q8rstuvw9</RequestId> </ResponseMetadata> </ConfirmSubscriptionResponse> The subscribed queue is ready to receive messages from the topic. 11. (Optional) If you view the topic subscription in the Amazon SNS console, you can see that the Pending Confirmation message has been replaced by the subscription ARN in the Subscription ID column. A user who does not own the queue creates a subscription 247 Amazon Simple Notification Service Developer Guide How do I force a subscription to require authentication on unsubscribe requests? The subscription owner must set the AuthenticateOnUnsubscribe flag to true on subscription- confirmation. • AuthenticateOnUnsubscribe is automatically set to true when the queue owner creates the subscription. • AuthenticateOnUnsubscribe cannot be set to true when the subscription confirmation link is navigated to without authentication. Sending Amazon SNS messages to an Amazon SQS queue or AWS Lambda function in a different Region Amazon SNS supports cross-region deliveries, both for Regions that are enabled by default and for opt-in Regions. For the current list of AWS Regions that Amazon SNS supports, including opt-in Regions, see Amazon Simple Notification Service endpoints and quotas in the Amazon Web Services General Reference. Amazon SNS supports the cross-region delivery of notifications to Amazon SQS queues and to AWS Lambda functions. When one of the Regions is an opt-in Region, you must specify a different Amazon SNS service
|
sns-dg-065
|
sns-dg.pdf
| 65 |
to without authentication. Sending Amazon SNS messages to an Amazon SQS queue or AWS Lambda function in a different Region Amazon SNS supports cross-region deliveries, both for Regions that are enabled by default and for opt-in Regions. For the current list of AWS Regions that Amazon SNS supports, including opt-in Regions, see Amazon Simple Notification Service endpoints and quotas in the Amazon Web Services General Reference. Amazon SNS supports the cross-region delivery of notifications to Amazon SQS queues and to AWS Lambda functions. When one of the Regions is an opt-in Region, you must specify a different Amazon SNS service principal in the subscribed resource's policy. The Amazon SNS subscription command must be executed in the region where Amazon SNS is hosted, in the corresponding region. For example, if Amazon SNS is in account "A" in the us-east-1 region, and the Lambda function is in account "B" in the us-east-2 region, the subscription CLI command must be executed in account "A" in the us-east-1 region. Opt-in Regions Amazon SNS supports the following opt-in Regions: Region name Africa (Cape Town) Region Asia Pacific (Hong Kong) Region Region af-south-1 ap-east-1 How do I force a subscription to require authentication on unsubscribe requests? 248 Amazon Simple Notification Service Developer Guide Region name Region Asia Pacific (Hyderabad) Region ap-south-2 Asia Pacific (Jakarta) Region ap-southeast-3 Asia Pacific (Melbourne) Region ap-southeast-4 Europe (Milan) Region Europe (Spain) Region Europe (Zurich) Region Israel (Tel Aviv) Region Middle East (Bahrain) Region eu-south-1 eu-south-2 eu-central-2 il-central-1 me-south-1 Middle East (UAE) Region me-central-1 For information on enabling an opt-in Region, see Managing AWS Regions in the Amazon Web Services General Reference. When you use Amazon SNS to deliver messages from opt-in Regions to Regions that are enabled by default, you must alter the resource policy created for the queue. Replace the principal sns.amazonaws.com with sns.<opt-in-region>.amazonaws.com. For example: • To subscribe an Amazon SQS queue in US East (N. Virginia) to an Amazon SNS topic in Asia Pacific (Hong Kong), change the principal in the queue policy to sns.ap- east-1.amazonaws.com. Opt-in regions include any regions launched after March 20, 2019, which includes Asia Pacific (Hong Kong), Asia Pacific (Jakarta), Middle East (Bahrain), Europe (Milan), and Africa (Cape Town). Regions launched prior to March 20, 2019 are enabled by default. Opt-in Regions 249 Amazon Simple Notification Service Developer Guide Cross-region delivery support to Amazon SQS Cross-region delivery type Default-enabled Region to opt-in Region Opt-in Region to default-enabled Region Opt-in Region to opt-in Region Supported/Not supported Supported using sns.<opt-in-region >.amazonaws.com principal for the queue in the service Supported using sns.<opt-in-region >.amazonaws.com principal for the queue in the service Not supported The following is an example of an access policy statement that allows an Amazon SNS topic in an opt-in Region (af-south-1) to deliver to an Amazon SQS queue in an enabled-by-default Region (us-east-1). It contains the necessary regionalized service principal configuration under the path Statement/Principal/Service. { "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "allow_sns_arn:aws:sns:af-south-1:111111111111:source_topic_name", "Effect": "Allow", "Principal": { "Service": "sns.af-south-1.amazonaws.com" }, "Action": "SQS:SendMessage", "Resource": "arn:aws:sqs:us-east-1:111111111111:destination_queue_name", "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:sns:af-south-1:111111111111:source_topic_name" } } Opt-in Regions 250 Amazon Simple Notification Service Developer Guide }, ... ] } • To subscribe an AWS Lambda function in US East (N. Virginia) to an Amazon SNS topic in Asia Pacific (Hong Kong), change the principal in the AWS Lambda function policy to sns.ap- east-1.amazonaws.com. Opt-in regions include any regions launched after March 20, 2019, which includes Asia Pacific (Hong Kong), Asia Pacific (Jakarta), Middle East (Bahrain), Europe (Milan), and Africa (Cape Town). Regions launched prior to March 20, 2019 are enabled by default. Cross-region delivery support to AWS Lambda Cross-region delivery type Default-enabled Region to opt-in Region Opt-in Region to default-enabled Region Opt-in Region to opt-in Region Supported/Not supported Not supported Supported using sns.<opt-in-region >.amazonaws.com principal for the Lambda function in the service Not supported Amazon SNS message delivery status Amazon SNS provides support for logging the delivery status of notification messages sent to topics with the following Amazon SNS endpoints: • Amazon Data Firehose • Amazon Simple Queue Service • AWS Lambda • HTTPS Message delivery status 251 Amazon Simple Notification Service • Platform application endpoint Developer Guide Delivery status logs are sent to Amazon CloudWatch Logs, providing insights into message delivery operations. These logs help you: • Determine whether a message was successfully delivered to an endpoint. • Identify the response from the endpoint to Amazon SNS. • Measure message dwell time (time between publish timestamp and handoff to the endpoint). You can configure delivery status logging using the AWS Management Console, AWS SDKs, Query API, or AWS CloudFormation. Prerequisites for delivery status logging This topic outlines the necessary IAM permissions for enabling Amazon SNS to write delivery logs to CloudWatch and explains the default log group naming convention. This ensures you have the correct
|
sns-dg-066
|
sns-dg.pdf
| 66 |
Logs, providing insights into message delivery operations. These logs help you: • Determine whether a message was successfully delivered to an endpoint. • Identify the response from the endpoint to Amazon SNS. • Measure message dwell time (time between publish timestamp and handoff to the endpoint). You can configure delivery status logging using the AWS Management Console, AWS SDKs, Query API, or AWS CloudFormation. Prerequisites for delivery status logging This topic outlines the necessary IAM permissions for enabling Amazon SNS to write delivery logs to CloudWatch and explains the default log group naming convention. This ensures you have the correct setup and access to monitor and analyze message delivery logs in CloudWatch logs. Required IAM permissions The IAM role attached for delivery status logging must include the following permissions to enable Amazon SNS to write to CloudWatch Logs. You can use an existing role with these permissions or create a new role during setup. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*" } ] } Log group naming convention Prerequisites for delivery status logging 252 Amazon Simple Notification Service Developer Guide By default, Amazon SNS creates CloudWatch log groups for delivery status logs using the following naming convention. Log streams within this group correspond to the endpoint protocols (for example, Lambda, Amazon SQS). Ensure you have permissions to view these logs in the CloudWatch Logs console. sns/<region>/<account-id>/<topic-name> Configuring delivery status logging using the AWS Management Console This topic explains how to enable message delivery status logging for Amazon SNS topics, including configuring logging settings, assigning IAM roles, and verifying that CloudWatch Logs capture delivery logs for monitoring and troubleshooting. 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. 4. Select the desired topic and then choose Edit. Expand the Delivery status logging section. 5. Choose the protocol for which you want to enable logging (for example, HTTP, Lambda, Amazon SQS). 6. Enter the Success sample rate, which is the percentage of successful messages for which you want to receive CloudWatch Logs. 7. In the IAM roles section, you must configure roles for both success and failure logging: • Use an existing service role – Select an existing IAM role that has the required permissions for Amazon SNS to write logs to CloudWatch. • Create a new service role – Choose Create new roles to define the IAM roles for successful and failed deliveries in the IAM console. For permission details, see Prerequisites for delivery status logging. 8. Choose Save changes. After enabling logging, you can view and parse the CloudWatch Logs containing the message delivery status. For more information about using CloudWatch, see the CloudWatch documentation. Configuring delivery status logging using the AWS Management Console 253 Amazon Simple Notification Service Verifying log setup Developer Guide 1. 2. 3. 4. Sign into the CloudWatch Logs console. Locate the log group named sns/<region>/<account-id>/<topic-name>. Ensure log streams exist for the configured endpoint protocol. Send a test message to your topic and confirm that log entries appear, indicating successful or failed deliveries. Configuring delivery status logging using the AWS SDKs The AWS SDKs provide APIs in several languages to set topic attributes for message delivery status logging. For example, use the SetTopicAttributes API to configure: • LambdaSuccessFeedbackRoleArn – IAM role for successful message delivery to Lambda endpoints. • LambdaSuccessFeedbackSampleRate – Sampling rate for successful messages to Lambda endpoints. • LambdaFailureFeedbackRoleArn – IAM role for failed message delivery to Lambda endpoints. Example AWS CLI command aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --attribute-name LambdaSuccessFeedbackRoleArn \ --attribute-value arn:aws:iam::123456789012:role/MyFeedbackRole Topic attributes Use the following topic attribute name values for message delivery status: HTTP • HTTPSuccessFeedbackRoleArn – Successful message delivery status for an Amazon SNS topic that is subscribed to an HTTP endpoint. • HTTPSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an HTTP endpoint. Configuring delivery status logging using the AWS SDKs 254 Amazon Simple Notification Service Developer Guide • HTTPFailureFeedbackRoleArn – Failed message delivery status for an Amazon SNS topic that is subscribed to an HTTP endpoint. Amazon Data Firehose • FirehoseSuccessFeedbackRoleArn – Successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint. • FirehoseSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint. • FirehoseFailureFeedbackRoleArn – Failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint. AWS Lambda • LambdaSuccessFeedbackRoleArn – Successful message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint. • LambdaSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Lambda endpoint. • LambdaFailureFeedbackRoleArn
|
sns-dg-067
|
sns-dg.pdf
| 67 |
that is subscribed to an Amazon Kinesis Data Firehose endpoint. • FirehoseSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint. • FirehoseFailureFeedbackRoleArn – Failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint. AWS Lambda • LambdaSuccessFeedbackRoleArn – Successful message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint. • LambdaSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Lambda endpoint. • LambdaFailureFeedbackRoleArn – Failed message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint. Platform application endpoints • ApplicationSuccessFeedbackRoleArn – Successful message delivery status for an Amazon SNS topic that is subscribed to an AWS application endpoint. • ApplicationSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an AWS application endpoint. • ApplicationFailureFeedbackRoleArn – Failed message delivery status for an Amazon SNS topic that is subscribed to an AWS application endpoint. Note Additionally, you can configure application attributes to log delivery status directly to push notification services. For more information, see Using Amazon SNS Application Attributes for Message Delivery Status. Configuring delivery status logging using the AWS SDKs 255 Amazon Simple Notification Service Amazon SQS Developer Guide • SQSSuccessFeedbackRoleArn – Successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint. • SQSSuccessFeedbackSampleRate – Percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint. • SQSFailureFeedbackRoleArn – Failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint. Logs for platform application endpoints are written to the same CloudWatch Logs group as other endpoints. Note The <ENDPOINT>SuccessFeedbackRoleArn and <ENDPOINT>FailureFeedbackRoleArn attributes are used to give Amazon SNS write access to use CloudWatch Logs on your behalf. The <ENDPOINT>SuccessFeedbackSampleRate attribute is for specifying the sample rate percentage (0-100) of successfully delivered messages. After you configure the <ENDPOINT>FailureFeedbackRoleArn attribute, then all failed message deliveries generate CloudWatch Logs. AWS SDK examples to configure topic attributes The following code examples show how to use SetTopicAttributes. CLI AWS CLI To set an attribute for a topic The following set-topic-attributes example sets the DisplayName attribute for the specified topic. aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --attribute-name DisplayName \ AWS SDK examples to configure topic attributes 256 Amazon Simple Notification Service Developer Guide --attribute-value MyTopicDisplayName This command produces no output. • For API details, see SetTopicAttributes in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * 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 SetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <attribute> <topicArn> <value> Where: attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy . topicArn - The ARN of the topic.\s AWS SDK examples to configure topic attributes 257 Amazon Simple Notification Service Developer Guide value - The value for the attribute. """; if (args.length < 3) { System.out.println(usage); System.exit(1); } String attribute = args[0]; String topicArn = args[1]; String value = args[2]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setTopAttr(snsClient, attribute, topicArn, value); snsClient.close(); } public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) { try { SetTopicAttributesRequest request = SetTopicAttributesRequest.builder() .attributeName(attribute) .attributeValue(value) .topicArn(topicArn) .build(); SetTopicAttributesResponse result = snsClient.setTopicAttributes(request); System.out.println( "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn() + " updated " + request.attributeName() + " to " + request.attributeValue()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } AWS SDK examples to configure topic attributes 258 Amazon Simple Notification Service Developer Guide • For API details, see SetTopicAttributes in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const setTopicAttributes = async ( topicArn
|
sns-dg-068
|
sns-dg.pdf
| 68 |
GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const setTopicAttributes = async ( topicArn = "TOPIC_ARN", attributeName = "DisplayName", attributeValue = "Test Topic", ) => { const response = await snsClient.send( new SetTopicAttributesCommand({ AttributeName: attributeName, AttributeValue: attributeValue, TopicArn: topicArn, }), ); AWS SDK examples to configure topic attributes 259 Amazon Simple Notification Service Developer Guide console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SetTopicAttributes in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun setTopAttr( attribute: String?, topicArnVal: String?, value: String?, ) { val request = SetTopicAttributesRequest { attributeName = attribute attributeValue = value topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> AWS SDK examples to configure topic attributes 260 Amazon Simple Notification Service Developer Guide snsClient.setTopicAttributes(request) println("Topic ${request.topicArn} was updated.") } } • For API details, see SetTopicAttributes in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Configure the message delivery status attributes for an Amazon SNS Topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $attribute = 'Policy | DisplayName | DeliveryPolicy'; $value = 'First Topic'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { AWS SDK examples to configure topic attributes 261 Amazon Simple Notification Service Developer Guide $result = $SnSclient->setTopicAttributes([ 'AttributeName' => $attribute, 'AttributeValue' => $value, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see SetTopicAttributes in AWS SDK for PHP API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # Service class to enable an SNS resource with a specified policy class SnsResourceEnabler # Initializes the SnsResourceEnabler with an SNS resource client # # @param sns_resource [Aws::SNS::Resource] The SNS resource client def initialize(sns_resource) @sns_resource = sns_resource @logger = Logger.new($stdout) end # Sets a policy on a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource to include in the policy # @param policy_name [String] The name of the policy attribute to set def enable_resource(topic_arn, resource_arn, policy_name) policy = generate_policy(topic_arn, resource_arn) AWS SDK examples to configure topic attributes 262 Amazon Simple Notification Service Developer Guide topic = @sns_resource.topic(topic_arn) topic.set_attributes({ attribute_name: policy_name, attribute_value: policy }) @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.") rescue Aws::SNS::Errors::ServiceError => e @logger.error("Failed to set policy: #{e.message}") end private # Generates a policy string with dynamic resource ARNs # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource # @return [String] The policy as a JSON string def generate_policy(topic_arn, resource_arn) { Version: '2008-10-17', Id: '__default_policy_ID', Statement: [{ Sid: '__default_statement_ID', Effect: 'Allow', Principal: { "AWS": '*' }, Action: ['SNS:Publish'], Resource: topic_arn, Condition: { ArnEquals: { "AWS:SourceArn": resource_arn } } }] }.to_json end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = 'MY_TOPIC_ARN' # Should be replaced with a real topic ARN resource_arn = 'MY_RESOURCE_ARN' # Should be replaced with a real resource ARN policy_name = 'POLICY_NAME' # Typically, this is "Policy" AWS SDK examples to configure topic attributes 263 Amazon Simple Notification Service Developer Guide sns_resource = Aws::SNS::Resource.new enabler = SnsResourceEnabler.new(sns_resource) enabler.enable_resource(topic_arn, resource_arn, policy_name) end • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see SetTopicAttributes in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->settopicattributes( iv_topicarn = iv_topic_arn iv_attributename = iv_attribute_name iv_attributevalue
|
sns-dg-069
|
sns-dg.pdf
| 69 |
replaced with a real resource ARN policy_name = 'POLICY_NAME' # Typically, this is "Policy" AWS SDK examples to configure topic attributes 263 Amazon Simple Notification Service Developer Guide sns_resource = Aws::SNS::Resource.new enabler = SnsResourceEnabler.new(sns_resource) enabler.enable_resource(topic_arn, resource_arn, policy_name) end • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see SetTopicAttributes in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->settopicattributes( iv_topicarn = iv_topic_arn iv_attributename = iv_attribute_name iv_attributevalue = iv_attribute_value ). MESSAGE 'Set/updated SNS topic attributes.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see SetTopicAttributes in AWS SDK for SAP ABAP API reference. Configuring delivery status logging using AWS CloudFormation To configure DeliveryStatusLogging using AWS CloudFormation, use a JSON or YAML template to create an AWS CloudFormation stack. For more information, see the DeliveryStatusLogging property of the AWS::SNS::Topic resource in the AWS Configuring delivery status logging using AWS CloudFormation 264 Amazon Simple Notification Service Developer Guide CloudFormation User Guide. Below are examples of AWS CloudFormation templates in JSON and YAML to create a new topic or update an existing topic with all DeliveryStatusLogging attributes for the Amazon SQS protocol. Ensure the IAM roles referenced in SuccessFeedbackRoleArn and FailureFeedbackRoleArn have the required CloudWatch Logs permissions. JSON "Resources": { "MySNSTopic" : { "Type" : "AWS::SNS::Topic", "Properties" : { "TopicName" : "TestTopic", "DisplayName" : "TEST", "SignatureVersion" : "2", "DeliveryStatusLogging" : [{ "Protocol": "sqs", "SuccessFeedbackSampleRate": "45", "SuccessFeedbackRoleArn": "arn:aws:iam::123456789012:role/ SNSSuccessFeedback_test1", "FailureFeedbackRoleArn": "arn:aws:iam::123456789012:role/ SNSFailureFeedback_test2" }] } } } YAML Resources: MySNSTopic: Type: AWS::SNS::Topic Properties: TopicName:TestTopic DisplayName:TEST SignatureVersion:2 DeliveryStatusLogging: - Protocol: sqs SuccessFeedbackSampleRate: 45 SuccessFeedbackRoleArn: arn:aws:iam::123456789012:role/ SNSSuccessFeedback_test1 Configuring delivery status logging using AWS CloudFormation 265 Amazon Simple Notification Service Developer Guide FailureFeedbackRoleArn: arn:aws:iam::123456789012:role/ SNSFailureFeedback_test2 Amazon SNS message delivery retries Amazon SNS defines a delivery policy for each delivery protocol. The delivery policy defines how Amazon SNS retries the delivery of messages when server-side errors occur (when the system that hosts the subscribed endpoint becomes unavailable). When the delivery policy is exhausted, Amazon SNS stops retrying the delivery and discards the message—unless a dead-letter queue is attached to the subscription. For more information, see Amazon SNS dead-letter queues. Delivery protocols and policies Note • With the exception of HTTP/S, you can't change Amazon SNS-defined delivery policies. Only HTTP/S supports custom policies. See Creating an HTTP/S delivery policy. • Amazon SNS applies jittering to delivery retries. For more information, see the Exponential Backoff and Jitter post on the AWS Architecture Blog. • The total policy retry time for an HTTP/S endpoint cannot be greater than 3,600 seconds. This is a hard limit and cannot be increased. Endpoint type Delivery protocols Immediate retry (no delay) phase Pre-backo ff phase Backoff phase Post-back off phase Total attempts AWS managed endpoints Amazon Data Firehose¹ 3 times, without delay 2 times, 1 second apart AWS Lambda 100,000 times, 20 seconds apart 100,015 times, over 23 days 10 times, with exponenti al backoff, from 1 second to 20 seconds Message delivery retries 266 Amazon Simple Notification Service Developer Guide Endpoint type Delivery protocols Immediate retry (no Pre-backo ff phase Backoff phase Post-back off phase Total attempts delay) phase Customer managed endpoints Amazon SQS SMTP SMS Mobile push 0 times, without delay 2 times, 10 seconds 10 times, with 38 times, 600 50 attempts, apart exponenti seconds al backoff, (10 over 6 hours minutes) apart from 10 seconds to 600 seconds (10 minutes) ¹ For throttling errors with the Firehose protocol, Amazon SNS uses the same delivery policy as for customer managed endpoints. Delivery policy stages The following diagram shows the phases of a delivery policy. Each delivery policy is comprised of four phases. Delivery policy stages 267 Amazon Simple Notification Service Developer Guide 1. Immediate retry phase (no delay) – This phase occurs immediately after the initial delivery attempt. There is no delay between retries in this phase. 2. Pre-backoff phase – This phase follows the Immediate Retry Phase. Amazon SNS uses this phase to attempt a set of retries before applying a backoff function. This phase specifies the number of retries and the amount of delay between them. 3. Backoff phase – This phase controls the delay between retries by using the retry-backoff function. This phase sets a minimum delay, a maximum delay, and a retry-backoff function that defines how quickly the delay increases from the minimum to the maximum delay. The backoff function can be arithmetic, exponential, geometric, or linear. 4. Post-backoff phase – This phase follows the backoff phase. It specifies a number of retries and the amount of delay between them. This is the final phase. Creating an HTTP/S delivery policy You can define how Amazon SNS retries message
|
sns-dg-070
|
sns-dg.pdf
| 70 |
the amount of delay between them. 3. Backoff phase – This phase controls the delay between retries by using the retry-backoff function. This phase sets a minimum delay, a maximum delay, and a retry-backoff function that defines how quickly the delay increases from the minimum to the maximum delay. The backoff function can be arithmetic, exponential, geometric, or linear. 4. Post-backoff phase – This phase follows the backoff phase. It specifies a number of retries and the amount of delay between them. This is the final phase. Creating an HTTP/S delivery policy You can define how Amazon SNS retries message delivery to HTTP/S endpoints using a delivery policy with four phases: no-delay, pre-backoff, backoff, and post-backoff. This policy allows you to override the default retry settings and customize them to match the capacity of your HTTP server. You can define your HTTP/S delivery policy as a JSON object at either the topic or subscription level: • Topic-level policy – Applies to all HTTP/S subscriptions linked to the topic. Use the CreateTopic or SetTopicAttributes API action to set this policy. • Subscription-level policy – Applies only to a specific subscription. Use the Subscribe or SetSubscriptionAttributes API action to set this policy. Alternatively, you can also use the AWS::SNS::Subscription resource in your AWS CloudFormation templates. You should customize your delivery policy based on your HTTP/S server's capacity: • Single server for all subscriptions – If all HTTP/S subscriptions in a topic use the same server, set the delivery policy as a topic attribute to ensure consistency across all subscriptions. • Different servers for subscriptions – If subscriptions target different servers, create a unique delivery policy for each subscription, tailored to the capacity of the specific server. Creating an HTTP/S delivery policy 268 Amazon Simple Notification Service Developer Guide You can also set the Content-Type header in the request policy to specify the media type of the notification. By default, Amazon SNS sends all the notifications to HTTP/S endpoints with content type set to text/plain; charset=UTF-8. However, you can override this default using the headerContentType field in the request policy. The following JSON object defines a delivery policy with retries structured in four phases: 1. No-delay phase – Retry 3 times immediately. 2. Pre-backoff phase – Retry 2 times with a 1 second interval. 3. Backoff phase – Retry 10 times with exponential delays ranging from 1 to 60 seconds. 4. Post-backoff phase – Retry 35 times with a fixed 60-second interval. Amazon SNS makes a total of 50 attempts to deliver a message before discarding it. To retain messages that can't be delivered after all retries, configure your subscription to move undeliverable messages to a dead-letter queue (DLQ). For more information, see Amazon SNS dead-letter queues. Amazon SNS considers all 5XX errors and 429 (too many requests sent) errors as retryable. These errors are subject to the delivery policy. All other errors are considered as permanent failures and retries will not be attempted. Note This delivery policy uses the maxReceivesPerSecond property to throttle delivery traffic to an average of 10 messages per second per subscription. While this mechanism helps prevent your HTTP/S endpoint from being overwhelmed by high traffic, it's designed to maintain an average delivery rate and doesn't enforce a strict cap. Occasional delivery traffic spikes above the specified limit may occur, especially if your publishing rate is significantly higher than the throttling limit. When the publishing (inbound) traffic exceeds the delivery (outbound) rate, it can result in a message backlog and higher delivery latency. To avoid such issues, ensure the maxReceivesPerSecond value aligns with your HTTP/S server's capacity and workload requirements. The following delivery policy example overrides the default content type for HTTP/S notification to application/json. Creating an HTTP/S delivery policy 269 Amazon Simple Notification Service Developer Guide { "healthyRetryPolicy": { "minDelayTarget": 1, "maxDelayTarget": 60, "numRetries": 50, "numNoDelayRetries": 3, "numMinDelayRetries": 2, "numMaxDelayRetries": 35, "backoffFunction": "exponential" }, "throttlePolicy": { "maxReceivesPerSecond": 10 }, "requestPolicy": { "headerContentType": "application/json" } } The delivery policy is composed of a retry policy, throttle policy and a request policy. In total, there are 9 attributes in a delivery policy. Policy Description Constraint minDelayTarget maxDelayTarget numRetries The minimum delay for a retry. Unit: Seconds The maximum delay for a retry. Unit: Seconds The total number of retries, including immediate, pre- backoff, backoff, and post- backoff retries. 1 to maximum delay Default: 20 Minimum delay to 3,600 Default: 20 0 to 100 Default: 3 Creating an HTTP/S delivery policy 270 Amazon Simple Notification Service Developer Guide Policy Description numNoDelayRetries numMinDelayRetries numMaxDelayRetries The number of retries to be done immediately, with no delay between them. Constraint 0 or greater Default: 0 The number of retries in the pre-backoff phase, with the specified minimum delay 0 or greater Default: 0 between them. The number of retries in the post-backoff phase, with
|
sns-dg-071
|
sns-dg.pdf
| 71 |
a retry. Unit: Seconds The total number of retries, including immediate, pre- backoff, backoff, and post- backoff retries. 1 to maximum delay Default: 20 Minimum delay to 3,600 Default: 20 0 to 100 Default: 3 Creating an HTTP/S delivery policy 270 Amazon Simple Notification Service Developer Guide Policy Description numNoDelayRetries numMinDelayRetries numMaxDelayRetries The number of retries to be done immediately, with no delay between them. Constraint 0 or greater Default: 0 The number of retries in the pre-backoff phase, with the specified minimum delay 0 or greater Default: 0 between them. The number of retries in the post-backoff phase, with the maximum delay between them. 0 or greater Default: 0 backoffFunction The model for backoff between retries. One of four options: • arithmetic • exponential • geometric • linear Default: linear 1 or greater Default: No throttling (no limit on delivery rate) maxReceivesPerSecond The maximum average number of message deliveries per second, per subscription. Creating an HTTP/S delivery policy 271 Amazon Simple Notification Service Developer Guide Policy Description Constraint headerContentType The content type of the notification being sent to HTTP/S endpoints. If the request policy is not defined, the content type defaults to text/plain; charset=UTF-8 . When the raw message delivery is disabled for a subscription (default), or when the delivery policy is defined on the topic-level, the supported header content types are application/ json and text/plain . When the raw message delivery is enabled for a subscription, the following content types are supported: • text/css • text/csv • text/html • text/plain • text/xml • application/atom+xml • application/json • application/octet-stream • application/soap+xml • application/x-www-form- urlencoded • application/xhtml+xml • application/xml Creating an HTTP/S delivery policy 272 Amazon Simple Notification Service Developer Guide Amazon SNS uses the following formula to calculate the number of retries in the backoff phase: numRetries - numNoDelayRetries - numMinDelayRetries - numMaxDelayRetries You can control the frequency of retries during the backoff phase using three parameters: • minDelayTarget – Sets the delay for the first retry attempt in the backoff phase. • maxDelayTarget – Sets the delay for the final retry attempt in the backoff phase. • backoffFunction – Determines the algorithm Amazon SNS uses to calculate the delays for all retry attempts between the first and last retries. You can choose from four available retry- backoff functions. The following diagram illustrates how different retry backoff functions affect the delays between retries during the backoff phase. The delivery policy used for this example includes the following settings: 10 total retries, a minimum delay of 5 seconds, and a maximum delay of 260 seconds. • The vertical axis shows the delay (in seconds) for each retry attempt. • The horizontal axis represents the retry sequence, ranging from the first to the tenth attempt. Creating an HTTP/S delivery policy 273 Amazon Simple Notification Service Developer Guide Amazon SNS dead-letter queues A dead-letter queue is an Amazon SQS queue that an Amazon SNS subscription can target for messages that can't be delivered to subscribers successfully. Messages that can't be delivered due to client errors or server errors are held in the dead-letter queue for further analysis or reprocessing. For more information, see Configuring an Amazon SNS dead-letter queue for a subscription and Amazon SNS message delivery retries. Note • The Amazon SNS subscription and Amazon SQS queue must be under the same AWS account and Region. • For a FIFO topic, you can use an Amazon SQS queue as a dead-letter queue for the Amazon SNS subscription. FIFO topic subscriptions use FIFO queues, and standard topic subscriptions use standard queues. • To use an encrypted Amazon SQS queue as a dead-letter queue, you must use a custom KMS with a key policy that grants the Amazon SNS service principal access to AWS KMS API actions. For more information, see Securing Amazon SNS data with server-side encryption in this guide and Protecting Amazon SQS Data Using Server-Side Encryption (SSE) and AWS KMS in the Amazon Simple Queue Service Developer Guide. Why do message deliveries fail? In general, message delivery fails when Amazon SNS can't access a subscribed endpoint due to a client-side or server-side error. When Amazon SNS receives a client-side error, or continues to receive a server-side error for a message beyond the number of retries specified by the corresponding retry policy, Amazon SNS discards the message—unless a dead-letter queue is attached to the subscription. Failed deliveries don't change the status of your subscriptions. For more information, see Amazon SNS message delivery retries. Client-side errors Client-side errors can happen when Amazon SNS has stale subscription metadata. These errors commonly occur when an owner deletes the endpoint (for example, a Lambda function subscribed to an Amazon SNS topic) or when an owner changes the policy attached to the subscribed Dead-letter queues 274 Amazon Simple Notification Service Developer Guide endpoint in a way
|
sns-dg-072
|
sns-dg.pdf
| 72 |
beyond the number of retries specified by the corresponding retry policy, Amazon SNS discards the message—unless a dead-letter queue is attached to the subscription. Failed deliveries don't change the status of your subscriptions. For more information, see Amazon SNS message delivery retries. Client-side errors Client-side errors can happen when Amazon SNS has stale subscription metadata. These errors commonly occur when an owner deletes the endpoint (for example, a Lambda function subscribed to an Amazon SNS topic) or when an owner changes the policy attached to the subscribed Dead-letter queues 274 Amazon Simple Notification Service Developer Guide endpoint in a way that prevents Amazon SNS from delivering messages to the endpoint. Amazon SNS doesn't retry the message delivery that fails as a result of a client-side error. Server-side errors Server-side errors can happen when the system responsible for the subscribed endpoint becomes unavailable or returns an exception that indicates that it can't process a valid request from Amazon SNS. When server-side errors occur, Amazon SNS retries the failed deliveries using either a linear or exponential backoff function. For server-side errors caused by AWS managed endpoints backed by Amazon SQS or AWS Lambda, Amazon SNS retries delivery up to 100,015 times, over 23 days. Customer managed endpoints (such as HTTP, SMTP, SMS, or mobile push) can also cause server- side errors. Amazon SNS retries delivery to these types of endpoints as well. While HTTP endpoints support customer-defined retry policies, Amazon SNS sets an internal delivery retry policy to 50 times over 6 hours, for SMTP, SMS, and mobile push endpoints. How do dead-letter queues work? A dead-letter queue is attached to an Amazon SNS subscription (rather than a topic) because message deliveries happen at the subscription level. This lets you identify the original target endpoint for each message more easily. A dead-letter queue associated with an Amazon SNS subscription is an ordinary Amazon SQS queue. For more information about the message retention period, see Quotas Related to Messages in the Amazon Simple Queue Service Developer Guide. You can change the message retention period using the Amazon SQS SetQueueAttributes API action. To make your applications more resilient, we recommend setting the maximum retention period for dead-letter queues to 14 days. How are messages moved into a dead-letter queue? Your messages are moved into a dead-letter queue using a redrive policy. A redrive policy is a JSON object that refers to the ARN of the dead-letter queue. The deadLetterTargetArn attribute specifies the ARN. The ARN must point to an Amazon SQS queue in the same AWS account and Region as your Amazon SNS subscription. For more information, see Configuring an Amazon SNS dead-letter queue for a subscription. The following JSON object is a sample redrive policy, attached to an SNS subscription. { How do dead-letter queues work? 275 Amazon Simple Notification Service Developer Guide "deadLetterTargetArn": "arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue" } How can I move messages out of a dead-letter queue? You can move messages out of a dead-letter queue in two ways: • Avoid writing Amazon SQS consumer logic – Set your dead-letter queue as an event source to the Lambda function to drain your dead-letter queue. • Write Amazon SQS consumer logic – Use the Amazon SQS API, AWS SDK, or AWS CLI to write custom consumer logic for polling, processing, and deleting the messages in the dead-letter queue. How can I monitor and log dead-letter queues? You can use Amazon CloudWatch metrics to monitor dead-letter queues associated with your Amazon SNS subscriptions. All Amazon SQS queues emit CloudWatch metrics at one-minute intervals. For more information, see Available CloudWatch metrics for Amazon SQS in the Amazon Simple Queue Service Developer Guide. All Amazon SNS subscriptions with dead-letter queues also emit CloudWatch metrics. For more information, see Monitoring Amazon SNS topics using CloudWatch. To be notified of activity in your dead-letter queues, you can use CloudWatch metrics and alarms. Setting up an alarm for the NumberOfMessagesSent metric is not suitable because this metric does not capture messages sent to a DLQ as a result of failed processing attempts. Instead, use the ApproximateNumberOfMessagesVisible metric, which captures all messages currently available in the DLQ, including those moved due to processing failures. Example CloudWatch alarm setup 1. Create a CloudWatch alarm for the ApproximateNumberOfMessagesVisible metric. 2. 3. Set the alarm threshold to 1 (or another appropriate value based on your expectations and DLQ traffic). Specify an Amazon SNS topic to be notified when the alarm goes off. This Amazon SNS topic can deliver your alarm notification to any endpoint type (such as an email address, phone number, or mobile pager app). How can I move messages out of a dead-letter queue? 276 Amazon Simple Notification Service Developer Guide You can use CloudWatch Logs to investigate the exceptions that cause any Amazon SNS deliveries to fail and for messages to be
|
sns-dg-073
|
sns-dg.pdf
| 73 |
alarm for the ApproximateNumberOfMessagesVisible metric. 2. 3. Set the alarm threshold to 1 (or another appropriate value based on your expectations and DLQ traffic). Specify an Amazon SNS topic to be notified when the alarm goes off. This Amazon SNS topic can deliver your alarm notification to any endpoint type (such as an email address, phone number, or mobile pager app). How can I move messages out of a dead-letter queue? 276 Amazon Simple Notification Service Developer Guide You can use CloudWatch Logs to investigate the exceptions that cause any Amazon SNS deliveries to fail and for messages to be sent to dead-letter queues. Amazon SNS can log both successful and failed deliveries in CloudWatch. For more information, see Amazon SNS mobile app attributes. Configuring an Amazon SNS dead-letter queue for a subscription A dead-letter queue is an Amazon SQS queue that an Amazon SNS subscription can target for messages that can't be delivered to subscribers successfully. Messages that can't be delivered due to client errors or server errors are held in the dead-letter queue for further analysis or reprocessing. For more information, see Amazon SNS dead-letter queues and Amazon SNS message delivery retries. This page shows how you can use the AWS Management Console, an AWS SDK, the AWS CLI, and AWS CloudFormation to configure a dead-letter queue for an Amazon SNS subscription. Note For a FIFO topic, you can use an Amazon SQS queue as a dead-letter queue for the Amazon SNS subscription. FIFO topic subscriptions use FIFO queues, and standard topic subscriptions use standard queues. Prerequisites Before you configure a dead-letter queue, complete the following prerequisites: 1. Create an Amazon SNS topic named MyTopic. 2. Create an Amazon SQS queue named MyEndpoint, to be used as the endpoint for the Amazon SNS subscription. 3. (Skip for AWS CloudFormation) Subscribe the queue to the topic. 4. Create another Amazon SQS queue named MyDeadLetterQueue, to be used as the dead- letter queue for the Amazon SNS subscription. 5. To give Amazon SNS principal access to the Amazon SQS API action, set the following queue policy for MyDeadLetterQueue. { "Version": "2012-10-17", Configuring a dead-letter queue 277 Amazon Simple Notification Service Developer Guide "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "SQS:SendMessage", "Resource": "arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-2:123456789012:MyTopic" } } } ] } To configure a dead-letter queue for an Amazon SNS subscription using the AWS Management Console Before your begin this tutorial, make sure you complete the prerequisites. 1. Sign in to the Amazon SQS console. 2. Create an Amazon SQS queue or use an existing queue and note the ARN of the queue on the Details tab of the queue, for example: arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue 3. Sign in to the Amazon SNS console. 4. On the navigation panel, choose Subscriptions. 5. On the Subscriptions page, select an existing subscription and then choose Edit. 6. On the Edit 1234a567-bc89-012d-3e45-6fg7h890123i page, expand the Redrive policy (dead-letter queue) section, and then do the following: a. b. Choose Enabled. Specify the ARN of an Amazon SQS queue. 7. Choose Save changes. Your subscription is configured to use a dead-letter queue. Configuring a dead-letter queue 278 Amazon Simple Notification Service Developer Guide To configure a dead-letter queue for an Amazon SNS subscription using an AWS SDK Before you run this example, make sure that you complete the prerequisites. To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide. The following code example shows how to use SetSubscriptionAttributesRedrivePolicy. Java SDK for Java 1.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. // Specify the ARN of the Amazon SNS subscription. String subscriptionArn = "arn:aws:sns:us-east-2:123456789012:MyEndpoint:1234a567- bc89-012d-3e45-6fg7h890123i"; // Specify the ARN of the Amazon SQS queue to use as a dead-letter queue. String redrivePolicy = "{\"deadLetterTargetArn\":\"arn:aws:sqs:us- east-2:123456789012:MyDeadLetterQueue\"}"; // Set the specified Amazon SQS queue as a dead-letter queue // of the specified Amazon SNS subscription by setting the RedrivePolicy attribute. SetSubscriptionAttributesRequest request = new SetSubscriptionAttributesRequest() .withSubscriptionArn(subscriptionArn) .withAttributeName("RedrivePolicy") .withAttributeValue(redrivePolicy); sns.setSubscriptionAttributes(request); Configuring a dead-letter queue 279 Amazon Simple Notification Service Developer Guide To configure a dead-letter queue for an Amazon SNS subscription using the AWS CLI Before your begin this tutorial, make sure you complete the prerequisites. 1. Install and configure the AWS CLI. For more information, see the AWS Command Line Interface User Guide. 2. Use the following command. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-2:123456789012:MyEndpoint:1234a567- bc89-012d-3e45-6fg7h890123i --attribute-name RedrivePolicy --attribute-value "{\"deadLetterTargetArn\": \"arn:aws:sqs:us- east-2:123456789012:MyDeadLetterQueue\"}" To configure a dead-letter queue for an Amazon SNS subscription using AWS CloudFormation Before your begin this tutorial, make sure you complete the prerequisites. 1. Copy the following JSON code to a file named MyDeadLetterQueue.json. { "Resources": {
|
sns-dg-074
|
sns-dg.pdf
| 74 |
Guide To configure a dead-letter queue for an Amazon SNS subscription using the AWS CLI Before your begin this tutorial, make sure you complete the prerequisites. 1. Install and configure the AWS CLI. For more information, see the AWS Command Line Interface User Guide. 2. Use the following command. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-2:123456789012:MyEndpoint:1234a567- bc89-012d-3e45-6fg7h890123i --attribute-name RedrivePolicy --attribute-value "{\"deadLetterTargetArn\": \"arn:aws:sqs:us- east-2:123456789012:MyDeadLetterQueue\"}" To configure a dead-letter queue for an Amazon SNS subscription using AWS CloudFormation Before your begin this tutorial, make sure you complete the prerequisites. 1. Copy the following JSON code to a file named MyDeadLetterQueue.json. { "Resources": { "mySubscription": { "Type" : "AWS::SNS::Subscription", "Properties" : { "Protocol": "sqs", "Endpoint": "arn:aws:sqs:us-east-2:123456789012:MyEndpoint", "TopicArn": "arn:aws:sns:us-east-2:123456789012:MyTopic", "RedrivePolicy": { "deadLetterTargetArn": "arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue" } } } } } Configuring a dead-letter queue 280 Amazon Simple Notification Service Developer Guide 2. Sign in to the AWS CloudFormation console. 3. On the Select Template page, choose Upload a template to Amazon S3, choose your MyDeadLetterQueue.json file, and then choose Next. 4. On the Specify Details page, enter MyDeadLetterQueue for Stack Name, and then choose Next. 5. On the Options page, choose Next. 6. On the Review page, choose Create. AWS CloudFormation begins to create the MyDeadLetterQueue stack and displays the CREATE_IN_PROGRESS status. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. Configuring a dead-letter queue 281 Amazon Simple Notification Service Developer Guide Amazon SNS message archiving, replay, and analytics Amazon SNS standard topics support message archiving through Amazon Data Firehose. You can fan out notifications to Firehose delivery streams, which allows you to send notifications to storage and analytics destinations that Firehose supports, including Amazon Simple Storage Service (Amazon S3), Amazon Redshift, and more. Amazon SNS FIFO topics support an in-place, no-code, message archive that lets topic owners store (or archive) messages published to a topic for up to 365 days. For topics with an active ArchivePolicy, subscribers can then create a ReplayPolicy to retrieve (or replay) the archived messages back to a subscribed endpoint. To learn more about this feature, see Amazon SNS message archiving and replay for FIFO topics. Features Standard Topics FIFO Topics Message archiving Fanout to Firehose delivery streams Amazon SNS message archiving for FIFO topic owners Message replay Replay for standard topics is not a built in feature. Many Amazon SNS message replay for FIFO topic subscribers customers build their own based on their message archive. 282 Amazon Simple Notification Service Developer Guide Resource management and optimization in Amazon SNS 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 • Amazon SNS topic tagging Amazon SNS topic tagging 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 AWS 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 AWS Resource Groups. For more information on Resource Groups, see the AWS Resource Groups User Guide. Tagging for cost allocation 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 AWS bill to reflect your own cost structure. To do this, sign up to get your AWS account bill to include the tag keys and values. For more information, see Setting Up a Monthly Cost Allocation Report in the AWS Billing and Cost Management User Guide. For example, you can add tags that represent the cost center and purpose of your Amazon SNS topics, as follows: Resource Key Topic 1 Cost Center Value 43289 Application Order processing Topic 2 Cost Center 43289 Application Payment processing Topic 3 Cost Center 76585 Tagging 283 Amazon Simple Notification Service Developer Guide Resource Key Application Value Archiving 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 AWS 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 or the AWS SDK, see Configuring tags. 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
|
sns-dg-075
|
sns-dg.pdf
| 75 |
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 or the AWS SDK, see Configuring tags. 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 in the IAM User Guide. Note Setting the IAM permission for Publish sets permission for both Publish and PublishBatch. { "Version": "2012-10-17", "Statement": [{ "Effect": "Deny", "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:*:*:*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "production" } Tagging for access control 284 Amazon Simple Notification Service Developer Guide } }, { "Effect": "Allow", "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:*:*:*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "development" } } }] } Tagging for resource searching and filtering An AWS account can have tens of thousands of Amazon SNS topics (see Amazon SNS Quotas 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(); Tagging for resource searching and filtering 285 Amazon Simple Notification Service Developer Guide // 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 This topic explains how to configure tags for an Amazon SNS topic using the AWS Management Console, an AWS SDK, or the AWS 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 AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. On the Topics page, choose a topic and then choose Edit. 4. Expand the Tags section. The tags added to the topic are listed. 5. 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. 6. Choose Save changes. Configuring tags 286 Amazon Simple Notification Service Developer Guide Adding tags to a topic using an AWS SDK To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide. The following code examples show how to use TagResource. CLI AWS 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 in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. 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; Configuring tags 287 Amazon Simple Notification Service /** Developer Guide * 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") Configuring tags 288 Amazon Simple Notification Service Developer Guide .build(); List<Tag> tagList
|
sns-dg-076
|
sns-dg.pdf
| 76 |
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") Configuring tags 288 Amazon Simple Notification Service Developer Guide .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 in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun addTopicTags(topicArn: String) { val tag = Tag { key = "Team" value = "Development" } val tag2 = Configuring tags 289 Amazon Simple Notification Service Developer Guide Tag { key = "Environment" value = "Gamma" } val tagList = mutableListOf<Tag>() tagList.add(tag) tagList.add(tag2) val request = TagResourceRequest { resourceArn = topicArn tags = tagList } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.tagResource(request) println("Tags have been added to $topicArn") } } • For API details, see TagResource in AWS SDK for Kotlin API reference. Managing tags with Amazon SNS API actions To manage tags using the Amazon SNS API, use the following API actions: • ListTagsForResource • TagResource • UntagResource API actions that support ABAC 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 AWS? in the IAM User Guide. • AddPermission • ConfirmSubscription • DeleteTopic Configuring tags 290 Amazon Simple Notification Service Developer Guide • GetDataProtectionPolicy • GetSubscriptionAttributes • GetTopicAttributes • ListSubscriptionsByTopic • ListTagsForResource • Publish • PublishBatch • PutDataProtectionPolicy • RemovePermission • SetSubscriptionAttributes • SetTopicAttributes • Subscribe • TagResource • Unsubscribe • UntagResource Configuring tags 291 Amazon Simple Notification Service Developer Guide Amazon SNS event sources and destinations Amazon SNS connects AWS services and external systems by routing event-driven notifications. Amazon SNS receives events from various AWS services, such as data pipeline updates, Amazon EC2 scaling actions, or security alerts, and publishes these events to Amazon SNS topics. These topics then send notifications to designated destinations. Amazon SNS supports two main types of destinations: Application-to-Application (A2A) and Application-to-Person (A2P). In A2A messaging, Amazon SNS can send events to Lambda to trigger custom business logic, to Amazon SQS for queuing messages, and to Amazon Kinesis Data Firehose for streaming data to storage and analytics services. For A2P messaging, Amazon SNS can send notifications via SMS, email, and push notifications to mobile devices, ensuring that users or teams receive timely alerts. By acting as a central hub, Amazon SNS routes notifications to the right places, helping you automate and manage your AWS infrastructure more effectively. This setup allows for seamless integration between services and reliable communication with users and systems. Amazon SNS event sources Amazon SNS integrates with a wide range of AWS services across various categories, allowing these services to publish events to Amazon SNS topics. This integration provides real-time notifications of key events, such as changes in infrastructure, application performance, and cost management. Note Amazon SNS introduced FIFO topics in October, 2020. Currently, most AWS services support sending events to standard topics only. Analytics services The following table describes how Amazon SNS integrates with AWS analytics services such as Athena, AWS Data Pipeline, and Amazon Redshift to provide real-time notifications for key events, including control limit breaches, pipeline status updates, and data warehouse activities. You can leverage these integrations to automate responses and maintain effective oversight of your data operations. Event sources 292 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Amazon Athena – Allows you to analyze data in Amazon S3 using standard SQL. Receive notifications when control limits are exceeded. For more information, see Setting data usage control limits in the Amazon Athena User Guide. AWS Data Pipeline – Helps automate the movement and transformation of data. Receive notifications about the status of pipeline components. For more informati on, see SnsAlarm in the AWS Data Pipeline Developer Guide. Amazon Redshift – Manages all of the work of setting up, operating, and scaling a data Receive notifications of Amazon Redshift events. For more information, see Amazon warehouse. Redshift event notifications in the Amazon Redshift Management Guide. Application integration services The following table describes how Amazon SNS integrates with application integration services
|
sns-dg-077
|
sns-dg.pdf
| 77 |
For more information, see Setting data usage control limits in the Amazon Athena User Guide. AWS Data Pipeline – Helps automate the movement and transformation of data. Receive notifications about the status of pipeline components. For more informati on, see SnsAlarm in the AWS Data Pipeline Developer Guide. Amazon Redshift – Manages all of the work of setting up, operating, and scaling a data Receive notifications of Amazon Redshift events. For more information, see Amazon warehouse. Redshift event notifications in the Amazon Redshift Management Guide. Application integration services The following table describes how Amazon SNS integrates with application integration services such as EventBridge and AWS Step Functions, enabling real-time data routing and notifications for business-critical applications. You can leverage these integrations to receive alerts from EventBridge events and orchestrate workflows using Step Functions, enhancing the automation and responsiveness of your applications. AWS service Benefit of using with Amazon SNS Amazon EventBridge – Delivers a stream of real-time data from your own applications, software-as-a-service (SaaS) applications , and AWS services and routes that data to targets, including Amazon SNS. EventBridge was formerly called CloudWatch Events. Receive notifications of EventBridge events. For more information, see Amazon EventBrid ge targets in the Amazon EventBridge User Guide. Application integration 293 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS AWS Step Functions – Lets you combine AWS Lambda functions and other AWS services to Receive notification of Step Functions events. For more information, see Call Amazon build business-critical applications. SNS with Step Functions in the AWS Step Functions Developer Guide. Billing & cost management services The following table describes how AWS Billing and Cost Management integrates with Amazon SNS to provide notifications for budgets, price changes, and cost anomalies. You can leverage this integration to set-up Amazon SNS topics to receive real-time alerts about your AWS spending, helping you monitor costs and respond to unexpected charges efficiently. AWS service Benefit of using with Amazon SNS AWS Billing and Cost Management – Provides features that help you monitor your costs and Receive budget notifications, price change notifications, and anomaly alerts. For more pay your bill. information, see the following pages in the AWS Billing User Guide: • • • Creating an Amazon SNS topic for budget notifications Setting up notifications Detecting unusual spend with AWS Cost Anomaly Detection Business applications services The following table describes how Amazon Chime integrates with Amazon SNS to send notifications for important meeting events, enabling you to stay informed about your communications and scheduling. Billing and cost management 294 Amazon Simple Notification Service Developer Guide You can leverage this integration to utilize Amazon Chime SDK event notifications to enhance your collaboration tools within and outside your organization. AWS service Benefit of using with Amazon SNS Amazon Chime – Lets you meet, chat, and place business calls inside and outside of your Receive important meeting event notificat ions. For more information, see Amazon organization. Chime SDK event notifications in the Amazon Chime Developer Guide. Compute services The following table describes how Amazon SNS integrates with various AWS compute services, enabling you to receive notifications for key events such as Auto Scaling actions, EC2 Image Builder completions, Elastic Beanstalk environment changes, Lambda function outputs, and Lightsail metric thresholds. You can leverage these integrations to efficiently manage your applications and resources by staying informed about critical updates and actions across AWS services. AWS service Benefit of using with Amazon SNS Amazon EC2 Auto Scaling – Helps you have the correct number of Amazon Elastic Receive notifications when Auto Scaling launches or terminates Amazon EC2 instances Compute Cloud (Amazon EC2) instances available for handling your application's load. EC2 Image Builder – Helps automate the creation, management, and deployment of customized, secure, and up-to-date server images that are pre-installed and pre-confi gured with software and settings to meet specific IT standards. in your Auto Scaling group. For more informati on, see Getting Amazon SNS notifications when your Auto Scaling group scales in the Amazon EC2 Auto Scaling User Guide. Receive notifications when builds are complete. For more information, see Tracking the latest server images in EC2 Image Builder pipelines on the AWS Compute Blog. Compute 295 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS AWS Elastic Beanstalk – Handles the details of capacity provisioning, load balancing, and Receive notifications of important events that affect your application. For more information, scaling for your application, and provides see Elastic Beanstalk environment notificat application health monitoring. ions with Amazon SNS in the AWS Elastic Beanstalk Developer Guide. AWS Lambda – Lets you run code without provisioning or managing servers. Receive function output data by setting an SNS topic as a Lambda dead-letter queue or a Lambda destination. For more informati on, see Asynchronous invocation in the AWS
|
sns-dg-078
|
sns-dg.pdf
| 78 |
Developer Guide AWS service Benefit of using with Amazon SNS AWS Elastic Beanstalk – Handles the details of capacity provisioning, load balancing, and Receive notifications of important events that affect your application. For more information, scaling for your application, and provides see Elastic Beanstalk environment notificat application health monitoring. ions with Amazon SNS in the AWS Elastic Beanstalk Developer Guide. AWS Lambda – Lets you run code without provisioning or managing servers. Receive function output data by setting an SNS topic as a Lambda dead-letter queue or a Lambda destination. For more informati on, see Asynchronous invocation in the AWS Lambda Developer Guide. Amazon Lightsail – Helps developers get started using AWS to build websites or web Receive notifications when a metric for one of your instances, databases, or load balancers applications. Containers services crosses a specified threshold. For more infor mation, see Adding notification contacts in Amazon Lightsail in the Amazon Lightsail Developer Guide. The following table describes how Amazon SNS integrates with AWS container services such as Amazon EKS Distro and Amazon ECS, allowing you to track updates and security patches for Amazon EKS clusters and receive notifications for new ECS-optimized AMI releases. You can leverage these integrations to maintain the security and efficiency of your container deployments by staying informed about important updates and changes. AWS service Benefit of using with Amazon SNS Amazon EKS Distro – Lets you create reliable and secure clusters wherever your appli cations are deployed. Track updates and security patches for clusters created with Amazon EKS Distro. For more information, see Introducing Amazon EKS Distro - an open source Kubernetes distrib ution used by Amazon EKS. Containers 296 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Amazon Elastic Container Service (Amazon ECS) – Enables you to run, stop, and manage Receive notifications when a new Amazon ECS-optimized AMI is available. For more containers on a cluster. information, see Subscribing to Amazon ECS- optimized AMI update notifications in the Amazon Elastic Container Service Developer Guide. Customer engagement services The following table describes how Amazon SNS enhances customer engagement services by integrating with Amazon Connect, AWS End User Messaging SMS, and Amazon Simple Email Service (SES), enabling you to receive alerts and validations, configure two-way SMS messaging, and monitor email notifications for bounces, complaints, and deliveries. These integrations help you manage customer communications across multiple channels. AWS service Benefit of using with Amazon SNS Amazon Connect – Lets you set up an omnichannel cloud contact center to engage Receive alerts and validations. For more information, see The power of AWS with with your customers. Amazon Connect in the Amazon Connect AWS End User Messaging SMS – Helps you engage your customers by sending them email, SMS and voice messages, and push notifications. Administrator Guide. Configure two-way SMS, which allows you to receive messages from your customers . For more information, see Two-way SMS messaging in the AWS End User Messaging SMS User Guide. Amazon Simple Email Service (Amazon SES) – Provides cost-effective way for you to send and receive email using your own email addresses and domains. Receive notifications of bounces, complaint s, and deliveries. For more information, see Configuring Amazon SNS notifications for Amazon SES in the Amazon Simple Email Service Developer Guide. Customer engagement 297 Amazon Simple Notification Service Database services Developer Guide The following table describes how Amazon SNS integrates with AWS database services such as AWS Database Migration Service (DMS), Amazon DynamoDB, Amazon ElastiCache, Amazon Neptune, Amazon Redshift, and Amazon Relational Database Service (RDS) to send notifications about important events such as data migrations, maintenance activities, cache updates, and database changes. These integrations help you to monitor and manage your database environments more effectively by providing timely alerts on key operational events. AWS service Benefit of using with Amazon SNS AWS Database Migration Service – Migrates data from on-premises databases into the Receive notifications when AWS DMS events occur; for example, when a replication AWS Cloud. instance is created or deleted. For more information, see Working with events an d notifications in AWS Database Migration Service in the AWS Database Migration Service User Guide. Amazon DynamoDB – Provides fast and predictable performance with seamless Receive notifications when maintenance events occur. For more information, see scalability in this fully managed NoSQL Customizing DAX cluster settings in the database service. Amazon DynamoDB Developer Guide. Amazon ElastiCache – Provides a high performance, resizeable, and cost-effective in-memory cache, while removing complexit y associated with deploying and managing a distributed cache environment. Amazon Neptune – Enables you to build and run applications that work with highly con nected datasets. Receive notifications when significant events occur. For more information, see Event notifications and Amazon SNS in the Amazon ElastiCache (Memcached) User Guide. Receive notifications when a Neptune event occurs. For
|
sns-dg-079
|
sns-dg.pdf
| 79 |
Receive notifications when maintenance events occur. For more information, see scalability in this fully managed NoSQL Customizing DAX cluster settings in the database service. Amazon DynamoDB Developer Guide. Amazon ElastiCache – Provides a high performance, resizeable, and cost-effective in-memory cache, while removing complexit y associated with deploying and managing a distributed cache environment. Amazon Neptune – Enables you to build and run applications that work with highly con nected datasets. Receive notifications when significant events occur. For more information, see Event notifications and Amazon SNS in the Amazon ElastiCache (Memcached) User Guide. Receive notifications when a Neptune event occurs. For more information, see Using Nep tune event notification in the Neptune User Guide. Database 298 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Amazon Redshift – Manages all of the work of setting up, operating, and scaling a data Receive notifications of Amazon Redshift events. For more information, see Amazon warehouse. Redshift event notifications in the Amazon Redshift Management Guide. Amazon Relational Database Service – Makes it easier to set up, operate, and scale a Receive notifications of Amazon RDS events. For more information, see Using Amazon RDS relational database in the AWS Cloud. event notification in the Amazon RDS User Guide. Developer tools services The following table describes how Amazon SNS integrates with AWS developer tools services, such as AWS CodeBuild, AWS CodeCommit, AWS CodeDeploy, Amazon CodeGuru, and AWS CodePipeline to provide notifications for critical events such as build status changes, repository updates, deployment progress, performance anomalies, and pipeline actions. These integrations helps you efficiently monitor and manage your software development workflows by receiving timely alerts on important events. AWS service Benefit of using with Amazon SNS AWS CodeBuild – Compiles your source code, runs unit tests, and produces artifacts that are ready to deploy. AWS CodeCommit – Provides version control for privately storing and managing assets in the cloud. Receive notifications when builds succeed, fail, or move from one build phase to another. For more information, see Build notification s sample for CodeBuild in the AWS CodeBuild User Guide. Receive notifications about CodeCommit repository events. For more information, see Example: Create an AWS CodeCommit trigger for an Amazon SNS topic in the AWS CodeCommit User Guide. Developer tools 299 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS AWS CodeDeploy – Automates applicati on deployments to Amazon EC2 instances, Receive notifications for CodeDeploy deployments or instance events. For more on-premises instances, serverless Lambda information, see Create a trigger for a functions, or Amazon ECS services. CodeDeploy event in the AWS CodeDeploy User Guide. Amazon CodeGuru – Collects runtime performance data from your live applications, Receive notifications when anomalies occur. For more information, see Working with and provides recommendations that can help anomalies and recommendation reports in you fine-tune your application performance. the Amazon CodeGuru User Guide. AWS CodePipeline – Automates the steps required to release software changes co Receive notifications about approval actions. For more information, see Manage approval ntinuously. actions in CodePipeline in the AWS CodePipel ine User Guide. Front-end web & mobile services The following table describes how Amazon SNS integrates with AWS End User Messaging SMS to enhance customer engagement by sending emails, SMS, voice messages, and push notifications, including the ability to configure two-way SMS for receiving customer messages. This integration allows you to interact more effectively with your customers across various communication channels. AWS service Benefit of using with Amazon SNS AWS End User Messaging SMS – Helps you engage your customers by sending them email, SMS and voice messages, and push notifications. Configure two-way SMS, which allows you to receive messages from your customers . For more information, see Two-way SMS messaging in the AWS End User Messaging SMS User Guide. Front-end web & mobile 300 Amazon Simple Notification Service Developer Guide Game development services The following table describes how Amazon SNS integrates with Amazon GameLift Servers to provide notifications for matchmaking and queue events in session-based multiplayer game servers. This integration helps game developers automate and monitor the deployment, operation, and scaling of their game servers, ensuring a seamless gaming experience. AWS service Benefit of using with Amazon SNS Amazon GameLift Servers – Provides solutions for hosting session-based multiplayer game servers in the cloud, including a fully managed Receive matchmaking and queue event notifications. For more information, see the following pages: service for deploying, operating, and scaling game servers. • • For matchmaking notifications, see Set up FlexMatch event notification in the Amazon GameLift Servers FlexMatch Developer Guide. For queue notifications, see Set up event notification for game session placement in the Amazon GameLift Servers Developer Guide. Internet of Things services The following table descrives how Amazon SNS integrates with AWS IoT services, such as AWS IoT Core, AWS IoT
|
sns-dg-080
|
sns-dg.pdf
| 80 |
GameLift Servers – Provides solutions for hosting session-based multiplayer game servers in the cloud, including a fully managed Receive matchmaking and queue event notifications. For more information, see the following pages: service for deploying, operating, and scaling game servers. • • For matchmaking notifications, see Set up FlexMatch event notification in the Amazon GameLift Servers FlexMatch Developer Guide. For queue notifications, see Set up event notification for game session placement in the Amazon GameLift Servers Developer Guide. Internet of Things services The following table descrives how Amazon SNS integrates with AWS IoT services, such as AWS IoT Core, AWS IoT Device Defender, AWS IoT Events, and AWS IoT Greengrass, to provide notifications for IoT events and alerts. These integrations allow you to effectively monitor device behavior, receive alerts for abnormal activities, and manage IoT devices with real-time updates and actions. Game development 301 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS AWS IoT Core – Provides the cloud services that connect your IoT devices to other devices Receive notifications of AWS IoT Core events. For more information, see Creating an and AWS Cloud services. Amazon SNS rule in the AWS IoT Developer Guide. AWS IoT Device Defender – Allows you to audit the configuration of your devices, m Receive alarms when a device violates a behavior. For more information, see How to onitor connected devices to detect abnormal use AWS IoT Device Defender detect in the behavior, and mitigate security risks. AWS IoT Developer Guide. AWS IoT Events – Lets you monitor your equipment or device fleets for failures or Receive notifications of AWS IoT Events events. For more information, see Amazon changes in operation, and trigger actions Simple Notification Service in the AWS IoT when such events occur. Events Developer Guide. AWS IoT Greengrass – Extends AWS onto physical devices so they can act locally on Receive notifications of AWS IoT Greengras s events. For more information, see SNS the data they generate, while still using the connector in the AWS IoT Greengrass Version 1 cloud for management, analytics, and durable Developer Guide. storage. Machine learning services The following table describes how Amazon SNS integrates with AWS machine learning services, such as Amazon CodeGuru, Amazon DevOps Guru, Amazon Lookout for Metrics, Amazon Rekognition, and Amazon SageMaker AI, to provide notifications for anomalies, operational insights, and data labeling activities. These integrations allow you to monitor application performance, receive alerts for data irregularities, and streamline the deployment of machine learning models with real-time updates. AWS service Benefit of using with Amazon SNS Amazon CodeGuru – Collects runtime performance data from your live applications, Receive notifications when anomalies occur. For more information, see Working with Machine learning 302 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS and provides recommendations that can help anomalies and recommendation reports in you fine-tune your application performance. the Amazon CodeGuru User Guide. Amazon DevOps Guru – Generates operation al insights using machine learning to help you Forward insights and confirmations. For more information, see Deliver ML-powered improve the performance of your operational operational insights to your on-call teams usi applications. ng PagerDuty with Amazon DevOps Guru on the AWS Management & Governance Blog. Amazon Lookout for Metrics – Finds anomalies in your data, determines their root causes, Receive notifications of anomalies. For more information, see Using Amazon SNS with and enables you to quickly take action. Lookout for Metrics in the Amazon Lookout for Metrics Developer Guide. Amazon Rekognition – Lets you add image and video analysis to your applications Receive notifications of request results. For more information, see Reference: Video analysis results notification in the Amazon Rekognition Developer Guide. Amazon SageMaker AI – Enables data scientist s and developers to build and train machine le Receive notifications when a data object is labeled. For more information, see Creating arning models, and then directly deploy them a streaming labeling job in the Amazon into a production-ready hosted environment. SageMaker AI Developer Guide. Management & governance services The following table describes how Amazon SNS integrates with AWS management and governance services such as Amazon Q Developer in chat applications, AWS CloudFormation, CloudTrail, CloudWatch, AWS Config, AWS Control Tower, AWS License Manager, AWS Service Catalog, and AWS Systems Manager, providing notifications for key events like infrastructure changes, compliance alerts, and operational insights. These integrations help you monitor and manage your AWS environments efficiently by delivering timely alerts and updates to relevant teams and systems. Management & governance 303 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Amazon Q Developer in chat applications – Enables DevOps and software developmen Deliver notifications to chat rooms. For more information, see Setting up Amazon Q t teams to use Amazon Chime and Slack chat Developer
|
sns-dg-081
|
sns-dg.pdf
| 81 |
Control Tower, AWS License Manager, AWS Service Catalog, and AWS Systems Manager, providing notifications for key events like infrastructure changes, compliance alerts, and operational insights. These integrations help you monitor and manage your AWS environments efficiently by delivering timely alerts and updates to relevant teams and systems. Management & governance 303 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Amazon Q Developer in chat applications – Enables DevOps and software developmen Deliver notifications to chat rooms. For more information, see Setting up Amazon Q t teams to use Amazon Chime and Slack chat Developer in chat applications in the Amazon rooms to monitor and respond to operational Q Developer in chat applications Administrator events in the AWS Cloud. Guide. AWS CloudFormation – Enables you to create and provision AWS infrastructure deploymen Receive notifications when stacks are created and updated. For more information, see ts predictably and repeatedly. Setting AWS CloudFormation stack options in the AWS CloudFormation User Guide. AWS CloudTrail – Provides event history of your AWS account activity. Receive notifications when CloudTrail publishes new log files to your Amazon S3 bucket. For more information, see Configuri ng Amazon SNS notifications for CloudTrail in the AWS CloudTrail User Guide. Amazon CloudWatch – Monitors your AWS resources and the applications you run on Receive notifications when alarms change state. For more information, see Using AWS in real time. Amazon CloudWatch alarms in the Amazon CloudWatch User Guide. AWS Config – Provides a detailed view of the configuration of AWS resources in your AWS Receive notifications when resources are updated, or when AWS Config evaluates account. AWS Control Tower – Enables you to set up and govern a secure, compliant, multi-acc ount AWS environment. custom or managed rules against your resources. For more information, see Notificat ions that AWS Config sends to an SNS topic and Example configuration item change notifications in the AWS Config Developer Guide. Use alerts to help you prevent drift within your landing zone, and receive complianc e notifications. For more information, see Tracking alerts through Amazon Simple Management & governance 304 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Notification Service in the AWS Control Tower User Guide. AWS License Manager – Helps you manage your software licenses from software vendors Receive License Manager notifications and alerts. For more information, see Settings in centrally across AWS and your on-premises License Manager in the License Manager User environments. Guide and Creating ServiceNow incidents for AWS License Manager notifications on the AWS Management & Governance Blog. AWS Service Catalog – Enables IT administr ators to create, manage, and distribute portfolios of approved products to end users, Receive notifications about stack events. For more information, see AWS Service Catalog notification constraints in the Service Catalog who can then access the products they need Administrator Guide. in a personalized portal. AWS Systems Manager – Lets you view and control your infrastructure on AWS. Receive notifications about the status of commands. For more information, see Monitoring Systems Manager status changes using Amazon SNS notifications in the AWS Systems Manager User Guide. Media services The following table describes how Amazon SNS integrates with Amazon Elastic Transcoder to send notifications when media transcoding jobs change status, enabling you to efficiently monitor and manage the conversion of media files stored in Amazon S3 into formats suitable for consumer playback devices. This integration helps you streamline media processing workflows by providing real-time alerts on job status. AWS service Benefit of using with Amazon SNS Amazon Elastic Transcoder – Lets you convert media files that you stored in Amazon S3 Receive notifications when jobs change status. For more information, see Notifications of Media 305 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS into media files in the formats required by job status in the Amazon Elastic Transcoder consumer playback devices. Developer Guide. Migration & transfer services The following table describes how Amazon SNS integrates with AWS migration and transfer services, such as AWS Application Discovery Service, AWS Database Migration Service (DMS), and AWS Snowball Edge, to provide notifications for events like server data collection, database migration activities, and data transfer jobs. These integrations help you to effectively manage and monitor your Cloud migration processes by offering real-time alerts and updates on critical migration tasks. AWS service Benefit of using with Amazon SNS AWS Application Discovery Service – Helps you plan your migration to the AWS Cloud by Receive notifications of events through AWS CloudTrail. For more information, see collecting usage and configuration data about Logging Application Discovery Service API your on-premises servers. calls with AWS CloudTrail in the Application Discovery Service User Guide. AWS Database Migration Service – Migrates data from on-premises databases into the Receive notifications when AWS
|
sns-dg-082
|
sns-dg.pdf
| 82 |
transfer jobs. These integrations help you to effectively manage and monitor your Cloud migration processes by offering real-time alerts and updates on critical migration tasks. AWS service Benefit of using with Amazon SNS AWS Application Discovery Service – Helps you plan your migration to the AWS Cloud by Receive notifications of events through AWS CloudTrail. For more information, see collecting usage and configuration data about Logging Application Discovery Service API your on-premises servers. calls with AWS CloudTrail in the Application Discovery Service User Guide. AWS Database Migration Service – Migrates data from on-premises databases into the Receive notifications when AWS DMS events occur; for example, when a replication AWS Cloud. AWS Snowball Edge – Uses physical storage devices to transfer large amounts of data between Amazon S3 and your onsite data storage location at faster-than-internet speeds. instance is created or deleted. For more information, see Working with events an d notifications in AWS Database Migration Service in the AWS Database Migration Service User Guide. Receive notifications for Snowball Edge jobs. For more information, see Notifications for Snow Family devices in the AWS Snowball Edge User Guide. Migration & transfer 306 Amazon Simple Notification Service Developer Guide Networking & content delivery services The following table describes how Amazon SNS integrates with AWS networking and content delivery services, such as Amazon API Gateway, Amazon CloudFront, AWS Direct Connect, Elastic Load Balancing, Amazon Route 53, and Amazon VPC, to send notifications for events like API messages, CloudFront metric alarms, connection state changes, load balancer events, health check statuses, and VPC endpoint activities. These integrations help you to monitor and manage your network and content delivery operations by providing timely alerts and updates. AWS service Benefit of using with Amazon SNS Amazon API Gateway – Enables you to create and deploy your own REST and WebSocket Receive messages posted to an API Gateway endpoint. For more information, see Tutorial: APIs at any scale. Build an API Gateway REST API with AWS integration in the API Gateway Developer Guide. Amazon CloudFront – Speeds up distribution of your static and dynamic web content, such Receive notifications when alarms based on specified CloudFront metrics occur. For more as .html, .css, .php, image, and media files. information, see Setting alarms to receiv AWS Direct Connect – Links your internal network to an AWS Direct Connect location over a standard Ethernet fiber-optic cable. e notifications in the Amazon CloudFront Developer Guide. Receive notifications when alarms that monitor the state of an AWS Direct Connect connection change state. For more informati on, see Creating CloudWatch alarms to monitor AWS Direct Connect connections in the AWS Direct Connect User Guide. Elastic Load Balancing – Automatically distributes your incoming traffic across multiple targets, such as Amazon EC2 instances, containers, and IP addresses, in Receive notifications of alarms you've created for load balancer events. For more informati on, see Create CloudWatch alarms for your load balancer in the User Guide for Classic more or more Availability Zones. Load Balancers. Networking & content delivery 307 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Amazon Route 53 – Provides domain registrat ion, DNS routing, and health checking. Receive notifications when health check status is unhealthy. For more information, see To receive an Amazon SNS notification when a health check status is unhealthy (console) in the Amazon Route 53 Developer Guide. Amazon Virtual Private Cloud (Amazon VPC) – Enables you to launch AWS resources into a Receive notifications for specific events that occur on interface endpoints. For more virtual network that you've defined. information, see Create and manage a notification for an endpoint service in the Amazon VPC User Guide. Security, identity, & compliance services The following table describes how Amazon SNS integrates with AWS security, identity, and compliance services, such as AWS Directory Service, Amazon GuardDuty, Amazon Inspector, and AWS Security Hub, to provide notifications for directory status changes, security findings, Inspector events, and security hub announcements. These integrations help you to maintain robust security practices by offering timely alerts and updates on security and compliance events. AWS service Benefit of using with Amazon SNS AWS Directory Service – Provides multiple ways to use Microsoft Active Directory (AD) with other AWS services. Receive email or text (SMS) messages when the status of your directory changes. For more information, see Configure directory status notifications in the AWS Directory Service Administration Guide. Amazon GuardDuty – Provides continuou s security monitoring to help to identify u nexpected and potentially unauthorized or Receive notifications about newly released finding types, updates to the existing finding types, and other functionality changes. malicious activity in your AWS environment. For more information, see Subscribing to Security, identity, & compliance 308 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS GuardDuty announcements SNS
|
sns-dg-083
|
sns-dg.pdf
| 83 |
other AWS services. Receive email or text (SMS) messages when the status of your directory changes. For more information, see Configure directory status notifications in the AWS Directory Service Administration Guide. Amazon GuardDuty – Provides continuou s security monitoring to help to identify u nexpected and potentially unauthorized or Receive notifications about newly released finding types, updates to the existing finding types, and other functionality changes. malicious activity in your AWS environment. For more information, see Subscribing to Security, identity, & compliance 308 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS GuardDuty announcements SNS topic in the Amazon GuardDuty User Guide. Amazon Inspector – Tests the network accessibility of your Amazon EC2 instances Receive notifications for Amazon Inspector events. For more information, see Setting up and the security state of your applications that an SNS topic for Amazon Inspector notificat run on those instances. ions in the Amazon Inspector User Guide. AWS Security Hub – Automates AWS security checks and centralizes security alerts. Receive notifications about AWS Security Hub announcements, including notifications about AWS Security Hub controls or standards that have been added, edited, or retired. For more information, see Subscribing to AWS Security Hub announcements with Amazon SNS. Serverless services The following table describes how Amazon SNS integrates with services like Amazon DynamoDB, Amazon EventBridge, and Lambda to send notifications for key events such as maintenance updates, real-time data streams, and Lambda function outputs. These integrations help you to efficiently monitor and manage your applications by receiving timely alerts on critical operations and automating responses to these events. AWS service Benefit of using with Amazon SNS Amazon DynamoDB – Provides fast and predictable performance with seamless scalability in this fully managed NoSQL database service. Receive notifications when maintenance events occur. For more information, see Customizing DAX cluster settings in the Amazon DynamoDB Developer Guide. Amazon EventBridge – Delivers a stream of real-time data from your own applications, software-as-a-service (SaaS) applications Receive notifications of EventBridge events. For more information, see Amazon EventBrid ge targets in the Amazon EventBridge User , and AWS services and routes that data to Guide. Serverless 309 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS targets, including Amazon SNS. EventBridge was formerly called CloudWatch Events. AWS Lambda – Lets you run code without provisioning or managing servers. Receive function output data by setting an SNS topic as a Lambda dead-letter queue or a Lambda destination. For more informati on, see Asynchronous invocation in the AWS Lambda Developer Guide. Storage services The following table describes how Amazon SNS integrates with AWS storage services like AWS Backup, Amazon Elastic File System (EFS), Amazon S3 Glacier, Amazon S3, and AWS Snowball Edge to provide notifications for various events such as backup activities, file system alarms, data retrieval jobs, bucket changes, and data transfer operations. These integrations help you to efficiently monitor and manage your storage solutions by receiving timely alerts on critical storage events. AWS service Benefit of using with Amazon SNS AWS Backup – Helps you centralize and automate the backup of data across AWS Receive notifications of AWS Backup events. For more information, see Using Amazon services in the Cloud and on premises SNS to track AWS Backup events in the AWS Amazon Elastic File System – Provides file storage for your Amazon EC2 instances. Amazon S3 Glacier – Provides storage for infrequently used data. Backup Developer Guide. Receive notifications of alarms you've created for Amazon EFS events. For more informati on, see Automated monitoring tools in the Amazon Elastic File System User Guide. Set a notification configuration on a vault so that when a job completes, a message is sent to an SNS topic. For more information, see Configuring vault notifications in Amazon S3 Storage 310 Amazon Simple Notification Service Developer Guide AWS service Benefit of using with Amazon SNS Glacier in the Amazon S3 Glacier Developer Guide. Amazon Simple Storage Service (Amazon S3) – Provides object storage. Receive notifications when changes occur to an Amazon S3 bucket or in the rare instance when objects don't replicate to their destination Region. For more information, see Walkthrough: Configure a bucket for notificat ions (SNS topic or SQS queue) and Monitoring progress with replication metrics and Amazon S3 event notifications in the Amazon Simple Storage Service User Guide. AWS Snowball Edge – Uses physical storage devices to transfer large amounts of data Receive notifications for Snowball Edge jobs. For more information, see Notifications for between Amazon S3 and your onsite data Snow Family devices in the AWS Snowball storage location at faster-than-internet Edge User Guide. speeds. Additional event sources The following table describes how Amazon SNS can be used to receive timely notifications about AWS daily feature updates and changes to AWS IP address ranges, ensuring
|
sns-dg-084
|
sns-dg.pdf
| 84 |
or SQS queue) and Monitoring progress with replication metrics and Amazon S3 event notifications in the Amazon Simple Storage Service User Guide. AWS Snowball Edge – Uses physical storage devices to transfer large amounts of data Receive notifications for Snowball Edge jobs. For more information, see Notifications for between Amazon S3 and your onsite data Snow Family devices in the AWS Snowball storage location at faster-than-internet Edge User Guide. speeds. Additional event sources The following table describes how Amazon SNS can be used to receive timely notifications about AWS daily feature updates and changes to AWS IP address ranges, ensuring that you are informed about the latest AWS service releases, instance types, VPC endpoints, and public IP address changes. These integrations help you stay up-to-date with AWS infrastructure changes and manage your resources effectively. Source Benefit of using with Amazon SNS AWS Daily Feature Updates Receive timely detailed information about releases and updates to AWS via an Amazon SNS topic. These releases include AWS Regions, AWS services, Amazon VPC endpoints Additional event sources 311 Amazon Simple Notification Service Developer Guide Source Benefit of using with Amazon SNS AWS IP address ranges , AWS services integrated with AWS Service Quotas, Amazon EC2 instance types, Amazon SageMaker AI instance types, Amazon Nimble Studio instance types, Amazon RDS databa se engine versions, and Amazon MSK Apache Kafka versions. For more information, see Subscribe to AWS Daily Feature Updates via Amazon SNS in the AWS News Blog. Receive notifications of changes to AWS IP ranges via an Amazon SNS topic. For more information, see AWS IP address ranges notifications in the Amazon Web Services General Reference, and Subscribe to AWS Public IP Address Changes via Amazon SNS in the AWS News Blog. For more information on event-driven computing, see the following sources: • What is an Event-Driven Architecture? • Event-Driven Computing with Amazon SNS and AWS Compute, Storage, Database, and Networking Services on the AWS Compute Blog • Enriching Event-Driven Architectures with AWS Event Fork Pipelines on the AWS Compute Blog Amazon SNS event destinations This topic lists all event destinations, organized by application-to-application (A2A) messaging and application-to-person (A2P) notifications. Note Amazon SNS introduced FIFO topics in October, 2020. Currently, most AWS services support receiving events from SNS standard topics only. Amazon SQS supports receiving events from both SNS standard and FIFO topics. Event destinations 312 Amazon Simple Notification Service A2A destinations Developer Guide The following table describes how Amazon SNS can deliver events to various application-to- application (A2A) destinations such as Amazon Data Firehose, Lambda, Amazon SQS, AWS Event Fork Pipelines, and HTTP/S endpoints. These integrations allow you to archive and analyze data, trigger custom business logic, facilitate application integration, and route events to external webhooks, enhancing the efficiency and flexibility of event-driven architectures. Event destination Benefit of using with Amazon SNS Amazon Data Firehose AWS Lambda Amazon SQS AWS Event Fork Pipelines Deliver events to delivery streams for archiving and analysis purposes. Through delivery streams, you can deliver events to AWS destinations like Amazon Simple Storage Service (Amazon S3), Amazon Redshift, and Amazon OpenSearch Service (OpenSearch Service), or to third-party destinations such as Datadog, New Relic, MongoDB, and Splunk. For more information, see Fanout to Firehose delivery streams. Deliver events to functions for triggering the execution of custom business logic. For more information, see Fanout Amazon SNS notificat ions to Lambda functions for automated processing. Deliver events to queues for application integration purposes. For more informati on, see Fanout Amazon SNS notifications to Amazon SQS queues for asynchronous processing. Deliver events to event backup and storage, event search and analytics, or event replay pipelines. For more information, see Fanout A2A destinations 313 Amazon Simple Notification Service Developer Guide Event destination Benefit of using with Amazon SNS Amazon SNS events to AWS Event Fork Pipelines. Deliver events to external webhooks. For more information, see Fanout Amazon SNS notificat ions to HTTPS endpoints. HTTP/S A2P destinations The following table describes how Amazon SNS delivers application-to-person (A2P) notifications to various destinations, including mobile phones via SMS and native push notifications, email inboxes, Amazon Chime chat rooms, Slack channels, and operational insights to on-call teams via PagerDuty. These integrations enhance communication and operational efficiency by enabling real-time alerts and updates across multiple platforms and communication channels. Event destination Benefit of using with Amazon SNS SMS Email Platform endpoint Amazon Q Developer in chat applications Deliver events to mobile phones as text messages. For more information, see Mobile text messaging with Amazon SNS. Deliver events to inboxes as email messages. For more information, see Amazon SNS email subscription setup and management. Deliver events to mobile phones as native push notifications. For more information, see Sending mobile push notifications with Amazon SNS. Deliver events to Amazon Chime chat rooms or Slack channels. For more information, see the following
|
sns-dg-085
|
sns-dg.pdf
| 85 |
real-time alerts and updates across multiple platforms and communication channels. Event destination Benefit of using with Amazon SNS SMS Email Platform endpoint Amazon Q Developer in chat applications Deliver events to mobile phones as text messages. For more information, see Mobile text messaging with Amazon SNS. Deliver events to inboxes as email messages. For more information, see Amazon SNS email subscription setup and management. Deliver events to mobile phones as native push notifications. For more information, see Sending mobile push notifications with Amazon SNS. Deliver events to Amazon Chime chat rooms or Slack channels. For more information, see the following pages in the Amazon Q A2P destinations 314 Amazon Simple Notification Service Developer Guide Event destination Benefit of using with Amazon SNS Developer in chat applications Administrator Guide: Setting up Amazon Q Developer in chat applications with Amazon Chime Setting up Amazon Q Developer in chat applications with Slack • • • Using Amazon Q Developer in chat applicati ons with other AWS services Deliver operational insights to on-call teams. For more information, see Deliver ML-powere d operational insights to your on-call teams via PagerDuty with Amazon DevOps Guru on the AWS Management & Governance Blog. PagerDuty Note You can deliver both native AWS events and custom events to chat apps: • Native AWS events – You can use Amazon Q Developer in chat applications to send native AWS events, through Amazon SNS topics, to Amazon Chime and Slack. The supported set of native AWS events includes events from AWS Billing and Cost Management, AWS Health, AWS CloudFormation, Amazon CloudWatch, and more. For more information, see Using Amazon Q Developer in chat applications with other services in the Amazon Q Developer in chat applications Administrator Guide. • Custom events – You can also send your custom events, through Amazon SNS topics, to Amazon Chime, Slack, and Microsoft Teams. To do this, you publish custom events to an SNS topic, which delivers the events to a subscribed Lambda function. The Lambda function then uses the chat app's webhook to deliver the events to recipients. For more information, see How do I use webhooks to publish Amazon SNS messages to Amazon Chime, Slack, or Microsoft Teams? A2P destinations 315 Amazon Simple Notification Service Developer Guide Using Amazon SNS for application-to-application messaging Amazon SNS simplifies application-to-application (A2A) messaging by separating publishers from subscribers, which supports microservices, distributed systems, and serverless applications. Messages are sent to Amazon SNS topics, where they can be filtered and delivered to subscribers like Lambda, Amazon SQS, or HTTP endpoints. If delivery fails, the messages are stored in a dead- letter queue for further analysis or reprocessing. Fanout to Firehose delivery streams You can subscribe Amazon Data Firehose delivery streams to Amazon SNS topics, allowing you to send notifications to additional storage and analytics endpoints. Messages published to an Amazon SNS topic are sent to the subscribed Firehose delivery stream, and delivered to the destination as configured in Firehose. A subscription owner can subscribe up to five Firehose delivery streams to an Amazon SNS topic. Each Firehose delivery stream has a default quota for requests and throughput per second. This limit could result in more messages published (inbound traffic) than delivered (outbound traffic). When there's more inbound than outbound traffic, your subscription can accumulate a large message backlog, causing high message delivery latency. You can request an increase in quota based on the publish rate to avoid adverse impact on your workload. Fanout to Firehose delivery streams 316 Amazon Simple Notification Service Developer Guide Through Firehose delivery streams, you can fan out Amazon SNS notifications to Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service (OpenSearch Service), and to third-party service providers such as Datadog, New Relic, MongoDB, and Splunk. For example, you can use this functionality to permanently store messages sent to a topic in an Amazon S3 bucket for compliance, archival, or other purposes. To do this, create a Firehose delivery stream with an Amazon S3 bucket destination, and subscribe that delivery stream to the Amazon SNS topic. As another example, to perform analysis on messages sent to an Amazon SNS topic, create a delivery stream with an OpenSearch Service index destination. You can then subscribe the Firehose delivery stream to the Amazon SNS topic. Amazon SNS also supports message delivery status logging for notifications sent to Firehose endpoints. For more information, see Amazon SNS message delivery status. Prerequisites for subscribing Firehose delivery streams to Amazon SNS topics To subscribe an Amazon Data Firehose delivery stream to an SNS topic, your AWS account must have: • A standard SNS topic. For more information, see Creating an Amazon SNS topic. • A Firehose delivery stream. For more information, see Creating an Amazon Data Firehose Delivery Stream and Grant Your Application Access to Your Firehose Resources in
|
sns-dg-086
|
sns-dg.pdf
| 86 |
subscribe the Firehose delivery stream to the Amazon SNS topic. Amazon SNS also supports message delivery status logging for notifications sent to Firehose endpoints. For more information, see Amazon SNS message delivery status. Prerequisites for subscribing Firehose delivery streams to Amazon SNS topics To subscribe an Amazon Data Firehose delivery stream to an SNS topic, your AWS account must have: • A standard SNS topic. For more information, see Creating an Amazon SNS topic. • A Firehose delivery stream. For more information, see Creating an Amazon Data Firehose Delivery Stream and Grant Your Application Access to Your Firehose Resources in the Amazon Data Firehose Developer Guide. • An AWS Identity and Access Management (IAM) role that trusts the Amazon SNS service principal and has permission to write to the delivery stream. You'll enter this role's Amazon Resource Name (ARN) as the SubscriptionRoleARN when you create the subscription. Amazon SNS assumes this role, which allows Amazon SNS to put records in the Firehose delivery stream. The following example policy shows the recommended permissions: { "Version": "2012-10-17", "Statement": [ { "Action": [ "firehose:DescribeDeliveryStream", "firehose:ListDeliveryStreams", "firehose:ListTagsForDeliveryStream", Prerequisites 317 Amazon Simple Notification Service Developer Guide "firehose:PutRecord", "firehose:PutRecordBatch" ], "Resource": [ "arn:aws:firehose:us-east-1:111111111111:deliverystream/firehose-sns- delivery-stream" ], "Effect": "Allow" } ] } To provide full permission for using Firehose, you can also use the AWS managed policy AmazonKinesisFirehoseFullAccess. Or, to provide stricter permissions for using Firehose, you can create your own policy. At minimum, the policy must provide permission to run the PutRecord operation on a specific delivery stream. In all cases, you must also edit the trust relationship to include the Amazon SNS service principal. For example: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } For more information on creating roles, see Creating a role to delegate permissions to an AWS service in the IAM User Guide. After you've completed these requirements, you can subscribe the delivery stream to the SNS topic. Prerequisites 318 Amazon Simple Notification Service Developer Guide Subscribing a Firehose delivery stream to an Amazon SNS topic To deliver Amazon SNS notifications to Amazon Data Firehose delivery streams, first make sure that you've addressed all the prerequisites. For a list of supported endpoints, see Amazon Data Firehose endpoints and quotas in the Amazon Web Services General Reference. To subscribe a Firehose delivery stream to a topic 1. 2. Sign in to the Amazon SNS console. In the navigation pane, choose Subscriptions. 3. On the Subscriptions page, choose Create subscription. 4. On the Create subscription page, in the Details section, do the following: a. b. c. d. e. For Topic ARN, choose the Amazon Resource Name (ARN) of a standard topic. For Protocol, choose Firehose. For Endpoint, choose the ARN of a Firehose delivery stream that can receive notifications from Amazon SNS. For Subscription role ARN, specify the ARN of the AWS Identity and Access Management (IAM) role that you created for writing to Firehose delivery streams. For more information, see Prerequisites for subscribing Firehose delivery streams to Amazon SNS topics. (Optional) To remove any Amazon SNS metadata from published messages, choose Enable raw message delivery. For more information, see Amazon SNS raw message delivery. 5. 6. (Optional) To configure a filter policy, expand the Subscription filter policy section. For more information, see Amazon SNS subscription filter policies. (Optional) To configure a dead-letter queue for the subscription, expand the Redrive policy (dead-letter queue) section. For more information, see Amazon SNS dead-letter queues. 7. Choose Create subscription. The console creates the subscription and opens the subscription's Details page. Managing Amazon SNS messages across multiple delivery stream destinations Amazon Data Firehose delivery streams allow you to manage Amazon SNS messages across multiple destinations, enabling integration with Amazon S3, Amazon OpenSearch Service, Subscribing a delivery stream to a topic 319 Amazon Simple Notification Service Developer Guide Amazon Redshift, and HTTP endpoints for storage, indexing, and analysis. By properly configuring message formatting and delivery, you can store Amazon SNS notifications in Amazon S3 for later processing, analyze structured message data using Amazon Athena, index messages in OpenSearch for real-time search and visualization, and structure archives in Amazon Redshift for advanced querying. Storing and analyzing Amazon SNS messages in Amazon S3 destinations This topic explains how Amazon Data Firehose delivery streams publish data to Amazon Simple Storage Service (Amazon S3). Topics • Formatting Amazon SNS notifications for storage in Amazon S3 destinations • Analyzing Amazon SNS messages stored in Amazon S3 using Athena Formatting Amazon SNS notifications for storage in Amazon S3 destinations The following example shows an Amazon SNS notification sent to an Amazon Simple Storage Service (Amazon S3) bucket, with indentation for readability. Managing messages across multiple delivery stream destinations 320 Amazon Simple Notification Service Developer Guide Note In this example, raw message delivery is disabled for the
|
sns-dg-087
|
sns-dg.pdf
| 87 |
S3 destinations This topic explains how Amazon Data Firehose delivery streams publish data to Amazon Simple Storage Service (Amazon S3). Topics • Formatting Amazon SNS notifications for storage in Amazon S3 destinations • Analyzing Amazon SNS messages stored in Amazon S3 using Athena Formatting Amazon SNS notifications for storage in Amazon S3 destinations The following example shows an Amazon SNS notification sent to an Amazon Simple Storage Service (Amazon S3) bucket, with indentation for readability. Managing messages across multiple delivery stream destinations 320 Amazon Simple Notification Service Developer Guide Note In this example, raw message delivery is disabled for the published message. When raw message delivery is disabled, Amazon SNS adds JSON metadata to the message, including these properties: • Type • MessageId • TopicArn • Subject • Timestamp • UnsubscribeURL • MessageAttributes For more information about raw delivery, see Amazon SNS raw message delivery. { "Type": "Notification", "MessageId": "719a6bbf-f51b-5320-920f-3385b5e9aa56", "TopicArn": "arn:aws:sns:us-east-1:333333333333:my-kinesis-test-topic", "Subject": "My 1st subject", "Message": "My 1st body", "Timestamp": "2020-11-26T23:48:02.032Z", "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:333333333333:my-kinesis-test- topic:0b410f3c-ee5e-49d8-b59b-3b4aa6d8fcf5", "MessageAttributes": { "myKey1": { "Type": "String", "Value": "myValue1" }, "myKey2": { "Type": "String", "Value": "myValue2" } } } Managing messages across multiple delivery stream destinations 321 Amazon Simple Notification Service Developer Guide The following example shows three SNS messages sent through an Amazon Data Firehose delivery stream to the same Amazon S3 bucket. Buffering is applied, and line breaks separate each message. {"Type":"Notification","MessageId":"d7d2513e-6126-5d77- bbe2-09042bd0a03a","TopicArn":"arn:aws:sns:us-east-1:333333333333:my- kinesis-test-topic","Subject":"My 1st subject","Message":"My 1st body","Timestamp":"2020-11-27T00:30:46.100Z","UnsubscribeURL":"https:// sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- east-1:313276652360:my-kinesis-test-topic:0b410f3c-ee5e-49d8- b59b-3b4aa6d8fcf5","MessageAttributes":{"myKey1": {"Type":"String","Value":"myValue1"},"myKey2":{"Type":"String","Value":"myValue2"}}} {"Type":"Notification","MessageId":"0c0696ab-7733-5bfb-b6db- ce913c294d56","TopicArn":"arn:aws:sns:us-east-1:333333333333:my- kinesis-test-topic","Subject":"My 2nd subject","Message":"My 2nd body","Timestamp":"2020-11-27T00:31:22.151Z","UnsubscribeURL":"https:// sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- east-1:313276652360:my-kinesis-test-topic:0b410f3c-ee5e-49d8- b59b-3b4aa6d8fcf5","MessageAttributes":{"myKey1":{"Type":"String","Value":"myValue1"}}} {"Type":"Notification","MessageId":"816cd54d-8cfa-58ad-91c9-8d77c7d173aa","TopicArn":"arn:aws:sns:us- east-1:333333333333:my-kinesis-test-topic","Subject":"My 3rd subject","Message":"My 3rd body","Timestamp":"2020-11-27T00:31:39.755Z","UnsubscribeURL":"https:// sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- east-1:313276652360:my-kinesis-test-topic:0b410f3c-ee5e-49d8-b59b-3b4aa6d8fcf5"} Analyzing Amazon SNS messages stored in Amazon S3 using Athena This page explains how to analyze Amazon SNS messages that are sent through Amazon Data Firehose delivery streams to Amazon Simple Storage Service (Amazon S3) destinations. To analyze SNS messages sent through Firehose delivery streams to Amazon S3 destinations 1. Configure your Amazon S3 resources. For instructions, see Creating a bucket in the Amazon Simple Storage Service User Guide and Working with Amazon S3 Buckets in the Amazon Simple Storage Service User Guide. 2. Configure your delivery stream. For instructions, see Choose Amazon S3 for Your Destination in the Amazon Data Firehose Developer Guide. 3. Use Amazon Athena to query the Amazon S3 objects using standard SQL. For more information, see Getting Started in the Amazon Athena User Guide. Managing messages across multiple delivery stream destinations 322 Amazon Simple Notification Service Example query For this example query, assume the following: Developer Guide • Messages are stored in the notifications table in the default schema. • The notifications table includes a timestamp column with a type of string. The following query returns all SNS messages received in the specified date range: SELECT * FROM default.notifications WHERE from_iso8601_timestamp(timestamp) BETWEEN TIMESTAMP '2020-12-01 00:00:00' AND TIMESTAMP '2020-12-02 00:00:00'; Integrating Amazon SNS messages with Amazon OpenSearch Service destinations This section explains how Amazon Data Firehose delivery streams publish data to Amazon OpenSearch Service (OpenSearch Service). Topics • Storing and formatting Amazon SNS Notifications in OpenSearch Service indices • Analyzing Amazon SNS messages for OpenSearch Service destinations Managing messages across multiple delivery stream destinations 323 Amazon Simple Notification Service Developer Guide Storing and formatting Amazon SNS Notifications in OpenSearch Service indices The following example demonstrates an Amazon SNS notification sent to an Amazon OpenSearch Service (OpenSearch Service) index called my-index. This index has a time filter field on the Timestamp field. The SNS notification is placed in the _source property of the payload. Note In this example, raw message delivery is disabled for the published message. When raw message delivery is disabled, Amazon SNS adds JSON metadata to the message, including these properties: • Type • MessageId • TopicArn • Subject • Timestamp • UnsubscribeURL • MessageAttributes For more information about raw delivery, see Amazon SNS raw message delivery. { "_index": "my-index", "_type": "_doc", "_id": "49613100963111323203250405402193283794773886550985932802.0", "_version": 1, "_score": null, "_source": { "Type": "Notification", "MessageId": "bf32e294-46e3-5dd5-a6b3-bad65162e136", "TopicArn": "arn:aws:sns:us-east-1:111111111111:my-topic", "Subject": "Sample subject", "Message": "Sample message", "Timestamp": "2020-12-02T22:29:21.189Z", Managing messages across multiple delivery stream destinations 324 Amazon Simple Notification Service Developer Guide "UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:111111111111:my- topic:b5aa9bc1-9c3d-452b-b402-aca2cefc63c9", "MessageAttributes": { "my_attribute": { "Type": "String", "Value": "my_value" } } }, "fields": { "Timestamp": [ "2020-12-02T22:29:21.189Z" ] }, "sort": [ 1606948161189 ] } Analyzing Amazon SNS messages for OpenSearch Service destinations This topic explains how to analyze Amazon SNS messages sent through Amazon Data Firehose delivery streams to Amazon OpenSearch Service (OpenSearch Service) destinations. To analyze SNS messages sent through Firehose delivery streams to OpenSearch Service destinations 1. Configure your OpenSearch Service resources. For instructions, see Getting Started with Amazon OpenSearch Service in the Amazon OpenSearch Service Developer Guide. 2. Configure your delivery stream. For instructions, see Choose OpenSearch Service for Your Destination in the Amazon Data Firehose Developer Guide. 3. Run a query using OpenSearch Service queries and Kibana. For more information, see Step
|
sns-dg-088
|
sns-dg.pdf
| 88 |
SNS messages for OpenSearch Service destinations This topic explains how to analyze Amazon SNS messages sent through Amazon Data Firehose delivery streams to Amazon OpenSearch Service (OpenSearch Service) destinations. To analyze SNS messages sent through Firehose delivery streams to OpenSearch Service destinations 1. Configure your OpenSearch Service resources. For instructions, see Getting Started with Amazon OpenSearch Service in the Amazon OpenSearch Service Developer Guide. 2. Configure your delivery stream. For instructions, see Choose OpenSearch Service for Your Destination in the Amazon Data Firehose Developer Guide. 3. Run a query using OpenSearch Service queries and Kibana. For more information, see Step 3: Search Documents in an OpenSearch Service Domain and Kibana in the Amazon OpenSearch Service Developer Guide. Example query The following example queries the my-index index for all SNS messages received in the specified date range: Managing messages across multiple delivery stream destinations 325 Amazon Simple Notification Service Developer Guide POST https://search-my-domain.us-east-1.es.amazonaws.com/my-index/_search { "query": { "bool": { "filter": [ { "range": { "Timestamp": { "gte": "2020-12-08T00:00:00.000Z", "lte": "2020-12-09T00:00:00.000Z", "format": "strict_date_optional_time" } } } ] } } } Configuring Amazon SNS message delivery and analysis in Amazon Redshift destinations This topic explains how to fan out Amazon SNS notifications to an Amazon Data Firehose delivery stream, which then publishes data to Amazon Redshift. With this setup, you can connect to the Amazon Redshift database and use a SQL query tool to retrieve Amazon SNS messages that match specific criteria. Managing messages across multiple delivery stream destinations 326 Amazon Simple Notification Service Developer Guide Topics • Structuring Amazon SNS message archives in Amazon Redshift tables • Analyzing Amazon SNS messages stored in Amazon Redshift destinations Structuring Amazon SNS message archives in Amazon Redshift tables For Amazon Redshift endpoints, Amazon SNS messages are archived as rows in a table. Here's an example of how the data is stored: Note In this example, raw message delivery is disabled for the published message. When raw message delivery is disabled, Amazon SNS adds JSON metadata to the message, including these properties: • Type • MessageId • TopicArn Managing messages across multiple delivery stream destinations 327 Amazon Simple Notification Service Developer Guide • Subject • Message • Timestamp • UnsubscribeURL • MessageAttributes For more information about raw delivery, see Amazon SNS raw message delivery. Although Amazon SNS adds properties to the message using the capitalization shown in this list, column names in Amazon Redshift tables appear in all lowercase characters. To transform the JSON metadata for the Amazon Redshift endpoint, you can use the SQL COPY command. For more information, see Copy from JSON examples and Load from JSON data using the 'auto ignorecase' option in the Amazon Redshift Database Developer Guide. type messageid topicarn subject message timestamp unsubscri beurl messageat tributes Notificat ion ea544832- a0d8-581d arn:aws:s ns:us-eas Sample subject Sample message 2020-12-0 2T00:33:3 https://s ns.us-eas {\"my_att ribute\": -9275-108 t-1:11111 243c46103 1111111:m y-topic 2.272Z t-1.amazo {\"Type\" naws.com/ :\"String ? \",\"Valu Action=U e\": nsubscrib \"my_ e&Subscri value\"}} ptionArn= arn:aws:s ns:us-eas t-1:11111 1111111:m y-topic:3 26deeeb- c bf4-45da- b92b- Managing messages across multiple delivery stream destinations 328 Amazon Simple Notification Service type messageid topicarn subject message timestamp unsubscri beurl ca77 a247813b Developer Guide messageat tributes Notificat ion ab124832- a0d8-581d arn:aws:s ns:us-eas Sample subject 2 Sample message 2020-12-0 3T00:18:1 https://s ns.us-eas {\"my_att ribute2\" -9275-108 t-1:11111 243c46114 1111111:m y-topic 2 1.129Z t-1.amazo :{\"Type naws.com/ \":\"Strin ? g\",\"Val Action=U ue\": nsubscrib \"my e&Subscri _value\"} ptionArn= } arn:aws:s ns:us-eas t-1:11111 1111111:m y-topic:3 26deeeb- c bf4-45da- b92b- ca77 a247813b Managing messages across multiple delivery stream destinations 329 Amazon Simple Notification Service type messageid topicarn subject message timestamp unsubscri beurl Developer Guide messageat tributes Notificat ion ce644832- a0d8-581d arn:aws:s ns:us-eas Sample subject 3 Sample message 2020-12-0 9T00:08:4 https://s ns.us-eas {\"my_att ribute3\" -9275-108 t-1:11111 243c46125 1111111:m y-topic 3 4.405Z t-1.amazo :{\"Type naws.com/ \":\"Strin ? g\",\"Val Action=U ue\": nsubscrib \"my e&Subscri _value\"} ptionArn= } arn:aws:s ns:us-eas t-1:11111 1111111:m y-topic:3 26deeeb- c bf4-45da- b92b- ca77 a247813b For more information about fanning out notifications to Amazon Redshift endpoints, see Configuring Amazon SNS message delivery and analysis in Amazon Redshift destinations. Analyzing Amazon SNS messages stored in Amazon Redshift destinations This topic describes how to analyze Amazon SNS messages that are sent through Amazon Data Firehose delivery streams to Amazon Redshift destinations. To analyze SNS messages sent through Firehose delivery streams to Amazon Redshift destinations 1. Configure your Amazon Redshift resources. For instructions, see Getting started with Amazon Redshift in the Amazon Redshift Getting Started Guide. Managing messages across multiple delivery stream destinations 330 Amazon Simple Notification Service Developer Guide 2. Configure your delivery stream. For instructions, see Choose Amazon Redshift for Your Destination in the Amazon Data Firehose Developer Guide. 3. Run a query. For more information, see Querying a database using the query editor in the Amazon Redshift Management Guide. Example query For this example query, assume the following:
|
sns-dg-089
|
sns-dg.pdf
| 89 |
destinations. To analyze SNS messages sent through Firehose delivery streams to Amazon Redshift destinations 1. Configure your Amazon Redshift resources. For instructions, see Getting started with Amazon Redshift in the Amazon Redshift Getting Started Guide. Managing messages across multiple delivery stream destinations 330 Amazon Simple Notification Service Developer Guide 2. Configure your delivery stream. For instructions, see Choose Amazon Redshift for Your Destination in the Amazon Data Firehose Developer Guide. 3. Run a query. For more information, see Querying a database using the query editor in the Amazon Redshift Management Guide. Example query For this example query, assume the following: • Messages are stored in the notifications table in the default public schema. • The Timestamp property from the SNS message is stored in the table's timestamp column with a column data type of timestamptz. Note To transform the JSON metadata for the Amazon Redshift endpoint, you can use the SQL COPY command. For more information, see Copy from JSON examples and Load from JSON data using the 'auto ignorecase' option in the Amazon Redshift Database Developer Guide. The following query returns all SNS messages received in the specified date range: SELECT * FROM public.notifications WHERE timestamp > '2020-12-01T09:00:00.000Z' AND timestamp < '2020-12-02T09:00:00.000Z'; Configuring Amazon SNS message delivery to HTTP destinations using Amazon Data Firehose This topic explains how Amazon Data Firehose delivery streams publish data to HTTP endpoints. Managing messages across multiple delivery stream destinations 331 Amazon Simple Notification Service Developer Guide Topics • Amazon SNS notification format for delivery to HTTP destinations Amazon SNS notification format for delivery to HTTP destinations Here’s an example of an HTTP POST request body from Amazon SNS, sent through an Amazon Data Firehose delivery stream to an HTTP endpoint. The Amazon SNS notification is encoded as a base64 payload within the records property. Note In this example, raw message delivery is disabled for the published message. For more information about raw delivery, see Amazon SNS raw message delivery. "body": { "requestId": "ebc9e8b2-fce3-4aef-a8f1-71698bf8175f", "timestamp": 1606255960435, "records": [ Managing messages across multiple delivery stream destinations 332 Amazon Simple Notification Service { Developer Guide "data": "eyJUeXBlIjoiTm90aWZpY2F0aW9uIiwiTWVzc2FnZUlkIjoiMjFkMmUzOGQtMmNhYi01ZjYxLTliYTItYmJiYWFhYzg0MGY2IiwiVG9waWNBcm4iOiJhcm46YXdzOnNuczp1cy1lYXN0LTE6MTExMTExMTExMTExOm15LXRvcGljIiwiTWVzc2FnZSI6IlNhbXBsZSBtZXNzYWdlIGZvciBBbWF6b24gS2luZXNpcyBEYXRhIEZpcmVob3NlIGVuZHBvaW50cyIsIlRpbWVzdGFtcCI6IjIwMjAtMTEtMjRUMjI6MDc6MzEuNjY3WiIsIlVuc3Vic2NyaWJlVVJMIjoiaHR0cHM6Ly9zbnMudXMtZWFzdC0xLmFtYXpvbmF3cy5jb20vP0FjdGlvbj1VbnN1YnNjcmliZSZTdWJzY3JpcHRpb25Bcm49YXJuOmF3czpzbnM6MTExMTExMTExMTExOm15LXRvcGljOjAxYjY5MTJjLTAwNzAtNGQ4Yi04YjEzLTU1NWJmYjc2ZTdkNCJ9" } ] } Amazon SNS message archiving and analytics: An example use case for airline ticketing platforms This topic provides a tutorial for a common use case of archiving and analyzing Amazon SNS messages. The setting of this use case is an airline ticketing platform that operates in a regulated environment. 1. The platform is subject to a compliance framework that requires the company to archive all ticket sales for at least five years. 2. To meet the compliance goal on data retention, the company subscribes an Amazon Data Firehose delivery stream to an existing Amazon SNS topic. 3. The destination for the delivery stream is an Amazon Simple Storage Service (Amazon S3) bucket. With this configuration, all events published to the SNS topic are archived in the Amazon S3 bucket. The following diagram shows the architecture of this configuration: Message archiving and analytics example use case 333 Amazon Simple Notification Service Developer Guide To run analytics and gain insights on ticket sales, the company runs SQL queries using Amazon Athena. For example, the company can query to learn about the most popular destinations and the most frequent flyers. To create the AWS resources for this use case, you can use the AWS Management Console or an AWS CloudFormation template. Topics • Setting-up initial AWS resources for Amazon SNS message archiving and analytics • Setting-up a Firehose delivery stream for Amazon SNS message archiving • Subscribing the Firehose delivery stream to the Amazon SNS topic • Testing and querying an Amazon SNS configuration for effective data management • Automating Amazon SNS message archiving with an AWS CloudFormation template Message archiving and analytics example use case 334 Amazon Simple Notification Service Developer Guide Setting-up initial AWS resources for Amazon SNS message archiving and analytics This topic describes how to create the resources needed for the message archiving and analytics example use case: • An Amazon Simple Storage Service (Amazon S3) bucket • Two Amazon Simple Queue Service (Amazon SQS) queues • An Amazon SNS topic • Two Amazon SQS subscriptions to the Amazon SNS topic To create the initial resources 1. Create the Amazon S3 bucket: a. Open the Amazon S3 console. b. Choose Create bucket. c. For Bucket name, enter a globally unique name. Keep the other fields as the defaults. d. Choose Create bucket. For more information about Amazon S3 buckets, see Creating a bucket in the Amazon Simple Storage Service User Guide and Working with Amazon S3 Buckets in the Amazon Simple Storage Service User Guide. 2. Create the two Amazon SQS queues: a. Open the Amazon SQS console. b. Choose Create queue. c. d. For Type, choose Standard. For Name, enter ticketPaymentQueue. e. Under Access policy,
|
sns-dg-090
|
sns-dg.pdf
| 90 |
1. Create the Amazon S3 bucket: a. Open the Amazon S3 console. b. Choose Create bucket. c. For Bucket name, enter a globally unique name. Keep the other fields as the defaults. d. Choose Create bucket. For more information about Amazon S3 buckets, see Creating a bucket in the Amazon Simple Storage Service User Guide and Working with Amazon S3 Buckets in the Amazon Simple Storage Service User Guide. 2. Create the two Amazon SQS queues: a. Open the Amazon SQS console. b. Choose Create queue. c. d. For Type, choose Standard. For Name, enter ticketPaymentQueue. e. Under Access policy, for Choose method, choose Advanced. f. In the JSON policy box, paste the following policy: { "Version": "2008-10-17", "Statement": [ { "Effect": "Allow", Message archiving and analytics example use case 335 Amazon Simple Notification Service Developer Guide "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "*", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-1:123456789012:ticketTopic" } } } ] } In this access policy, replace the AWS account number (123456789012) with your own, and change the AWS Region (us-east-1) accordingly. g. Choose Create queue. h. Repeat these steps to create a second SQS queue named ticketFraudQueue. For more information on creating SQS queues, see Creating an Amazon SQS queue (console) in the Amazon Simple Queue Service Developer Guide. 3. Create the SNS topic: a. Open the Topics page of the Amazon SNS console. b. Choose Create topic. c. Under Details, for Type, choose Standard. d. e. For Name, enter ticketTopic. Choose Create topic. For more information on creating SNS topics, see Creating an Amazon SNS topic. 4. Subscribe both SQS queues to the SNS topic: a. In the Amazon SNS console, on the ticketTopic topic's details page, choose Create subscription. b. Under Details, for Protocol, choose Amazon SQS. Message archiving and analytics example use case 336 Amazon Simple Notification Service Developer Guide c. For Endpoint, choose the Amazon Resource Name (ARN) of the ticketPaymentQueue queue. d. Choose Create subscription. e. Repeat these steps to create a second subscription using the ARN of the ticketFraudQueue queue. For more information on subscribing to SNS topics, see Creating a subscription to an Amazon SNS topic. You can also subscribe SQS queues to SNS topics from the Amazon SQS console. For more information, see Subscribing an Amazon SQS queue to an Amazon SNS topic (console) in the Amazon Simple Queue Service Developer Guide. You've created the initial resources for this example use case. To continue, see Setting-up a Firehose delivery stream for Amazon SNS message archiving. Setting-up a Firehose delivery stream for Amazon SNS message archiving This topic explains how to create the Amazon Data Firehose delivery stream for the message archiving and analytics example use case. To create the Firehose delivery stream 1. Open the Amazon Kinesis services console. 2. Choose Firehose and then choose Create delivery stream. 3. On the New delivery stream page, for Delivery stream name, enter ticketUploadStream, and then choose Next. 4. On the Process records page, choose Next. 5. On the Choose a destination page, do the following: a. For Destination, choose Amazon S3. b. Under S3 destination, for S3 bucket, choose the S3 bucket that you created initially. c. Choose Next. 6. On the Configure settings page, for S3 buffer conditions, do the following: • For Buffer size, enter 1. • For Buffer interval, enter 60. Message archiving and analytics example use case 337 Amazon Simple Notification Service Developer Guide Using these values for the Amazon S3 buffer lets you quickly test the configuration. The first condition that is satisfied triggers data delivery to the S3 bucket. 7. On the Configure settings page, for Permissions, choose to create an AWS Identity and Access Management (IAM) role with the required permissions assigned automatically. Then choose Next. 8. On the Review page, choose Create delivery stream. 9. From the Kinesis Data Firehose delivery streams page, choose the delivery stream you just created (ticketUploadStream). On the Details tab, note the stream's Amazon Resource Name (ARN) for later. For more information on creating delivery streams, see Creating an Amazon Data Firehose Delivery Stream in the Amazon Data Firehose Developer Guide. For more information on creating IAM roles, see Creating a role to delegate permissions to an AWS service in the IAM User Guide. You've created the Firehose delivery stream with the required permissions. To continue, see Subscribing the Firehose delivery stream to the Amazon SNS topic. Subscribing the Firehose delivery stream to the Amazon SNS topic This topic explains how to create the following resources for the message archiving and analytics example use case: • The AWS Identity and Access Management (IAM) role that allows the Amazon SNS subscription to put records on the Amazon Data Firehose delivery stream. • The Firehose delivery stream subscription to the Amazon SNS topic. To create the IAM
|
sns-dg-091
|
sns-dg.pdf
| 91 |
to an AWS service in the IAM User Guide. You've created the Firehose delivery stream with the required permissions. To continue, see Subscribing the Firehose delivery stream to the Amazon SNS topic. Subscribing the Firehose delivery stream to the Amazon SNS topic This topic explains how to create the following resources for the message archiving and analytics example use case: • The AWS Identity and Access Management (IAM) role that allows the Amazon SNS subscription to put records on the Amazon Data Firehose delivery stream. • The Firehose delivery stream subscription to the Amazon SNS topic. To create the IAM role for the Amazon SNS subscription 1. Open the Roles page of the IAM console. 2. Choose Create role. 3. 4. For Select type of trusted entity, choose AWS service. For Choose a use case, choose SNS. Then choose Next: Permissions. 5. Choose Next: Tags. 6. Choose Next: Review. Message archiving and analytics example use case 338 Amazon Simple Notification Service Developer Guide 7. On the Review page, for Role name, enter ticketUploadStreamSubscriptionRole. Then choose Create role. 8. When the role is created, choose its name (ticketUploadStreamSubscriptionRole). 9. On the role's Summary page, choose Add inline policy. 10. On the Create policy page, choose the JSON tab, and then paste the following policy into the box: { "Version": "2012-10-17", "Statement": [ { "Action": [ "firehose:DescribeDeliveryStream", "firehose:ListDeliveryStreams", "firehose:ListTagsForDeliveryStream", "firehose:PutRecord", "firehose:PutRecordBatch" ], "Resource": [ "arn:aws:firehose:us-east-1:123456789012:deliverystream/ ticketUploadStream" ], "Effect": "Allow" } ] } In this policy, replace the AWS account number (123456789012) with your own, and change the AWS Region (us-east-1) accordingly. 11. Choose Review policy. 12. On the Review policy page, for Name, enter FirehoseSnsPolicy. Then choose Create policy. 13. On the role's Summary page, note the Role ARN for later. For more information on creating IAM roles, see Creating a role to delegate permissions to an AWS service in the IAM User Guide. Message archiving and analytics example use case 339 Amazon Simple Notification Service Developer Guide To subscribe the Firehose delivery stream to the SNS topic 1. Open the Topics page of the Amazon SNS console. 2. On the Subscriptions, tab, choose Create subscription. 3. Under Details, for Protocol, choose Amazon Data Firehose. 4. 5. For Endpoint, enter the Amazon Resource Name (ARN) of the ticketUploadStream delivery stream that you created earlier. For example, enter arn:aws:firehose:us- east-1:123456789012:deliverystream/ticketUploadStream. For Subscription role ARN, enter the ARN of the ticketUploadStreamSubscriptionRole IAM role that you created earlier. For example, enter arn:aws:iam::123456789012:role/ ticketUploadStreamSubscriptionRole. 6. Select the Enable raw message delivery check box. 7. Choose Create subscription. You've created the IAM role and SNS topic subscription. To continue, see Testing and querying an Amazon SNS configuration for effective data management. Testing and querying an Amazon SNS configuration for effective data management This topic explains how to test the message archiving and analytics example use case by publishing a message to the Amazon SNS topic. The instructions include an example query that you can run and adapt to your own needs. To test your configuration 1. Open the Topics page of the Amazon SNS console. 2. Choose the ticketTopic topic. 3. Choose Publish message. 4. On the Publish message to topic page, enter the following for the message body. Add a newline character at the end of the message. {"BookingDate":"2020-12-15","BookingTime":"2020-12-15 04:15:05","Destination":"Miami","FlyingFrom":"Vancouver","TicketNumber":"abcd1234"} Keep all other options as their defaults. Message archiving and analytics example use case 340 Amazon Simple Notification Service 5. Choose Publish message. Developer Guide For more information on publishing messages, see Publishing an Amazon SNS message. 6. After the delivery stream interval of 60 seconds, open the Amazon Simple Storage Service (Amazon S3) console and choose the Amazon S3 bucket that you created initially. The published message appears in the bucket. To query the data 1. Open the Amazon Athena console. 2. Run a query. For example, assume that the notifications table in the default schema contains the following data: {"BookingDate":"2020-12-15","BookingTime":"2020-12-15 04:15:05","Destination":"Miami","FlyingFrom":"Vancouver","TicketNumber":"abcd1234"} {"BookingDate":"2020-12-15","BookingTime":"2020-12-15 11:30:15","Destination":"Miami","FlyingFrom":"Omaha","TicketNumber":"efgh5678"} {"BookingDate":"2020-12-15","BookingTime":"2020-12-15 3:30:10","Destination":"Miami","FlyingFrom":"NewYork","TicketNumber":"ijkl9012"} {"BookingDate":"2020-12-15","BookingTime":"2020-12-15 12:30:05","Destination":"Delhi","FlyingFrom":"Omaha","TicketNumber":"mnop3456"} To find the top destination, run the following query: SELECT destination FROM default.notifications GROUP BY destination ORDER BY count(*) desc LIMIT 1; To query for tickets sold during a specific date and time range, run a query like the following: SELECT * FROM default.notifications WHERE bookingtime BETWEEN TIMESTAMP '2020-12-15 10:00:00' Message archiving and analytics example use case 341 Amazon Simple Notification Service Developer Guide AND TIMESTAMP '2020-12-15 12:00:00'; You can adapt both sample queries for your own needs. For more information on using Athena to run queries, see Getting Started in the Amazon Athena User Guide. Cleaning up To avoid incurring usage charges after you're done testing, delete the following resources that you created during the tutorial: • Amazon SNS subscriptions • Amazon SNS topic • Amazon Simple Queue Service (Amazon SQS) queues • Amazon S3 bucket • Amazon Data Firehose delivery stream • AWS Identity and
|
sns-dg-092
|
sns-dg.pdf
| 92 |
TIMESTAMP '2020-12-15 10:00:00' Message archiving and analytics example use case 341 Amazon Simple Notification Service Developer Guide AND TIMESTAMP '2020-12-15 12:00:00'; You can adapt both sample queries for your own needs. For more information on using Athena to run queries, see Getting Started in the Amazon Athena User Guide. Cleaning up To avoid incurring usage charges after you're done testing, delete the following resources that you created during the tutorial: • Amazon SNS subscriptions • Amazon SNS topic • Amazon Simple Queue Service (Amazon SQS) queues • Amazon S3 bucket • Amazon Data Firehose delivery stream • AWS Identity and Access Management (IAM) roles and policies Automating Amazon SNS message archiving with an AWS CloudFormation template To automate the deployment of the Amazon SNS message archiving and analytics example use case, you can use the following YAML template: --- AWSTemplateFormatVersion: '2010-09-09' Description: Template for creating an SNS archiving use case Resources: ticketUploadStream: DependsOn: - ticketUploadStreamRolePolicy Type: AWS::KinesisFirehose::DeliveryStream Properties: S3DestinationConfiguration: BucketARN: !Sub 'arn:${AWS::Partition}:s3:::${ticketArchiveBucket}' BufferingHints: IntervalInSeconds: 60 SizeInMBs: 1 CompressionFormat: UNCOMPRESSED RoleARN: !GetAtt ticketUploadStreamRole.Arn Message archiving and analytics example use case 342 Amazon Simple Notification Service Developer Guide ticketArchiveBucket: Type: AWS::S3::Bucket ticketTopic: Type: AWS::SNS::Topic ticketPaymentQueue: Type: AWS::SQS::Queue ticketFraudQueue: Type: AWS::SQS::Queue ticketQueuePolicy: Type: AWS::SQS::QueuePolicy Properties: PolicyDocument: Statement: Effect: Allow Principal: Service: sns.amazonaws.com Action: - sqs:SendMessage Resource: '*' Condition: ArnEquals: aws:SourceArn: !Ref ticketTopic Queues: - !Ref ticketPaymentQueue - !Ref ticketFraudQueue ticketUploadStreamSubscription: Type: AWS::SNS::Subscription Properties: TopicArn: !Ref ticketTopic Endpoint: !GetAtt ticketUploadStream.Arn Protocol: firehose SubscriptionRoleArn: !GetAtt ticketUploadStreamSubscriptionRole.Arn ticketPaymentQueueSubscription: Type: AWS::SNS::Subscription Properties: TopicArn: !Ref ticketTopic Endpoint: !GetAtt ticketPaymentQueue.Arn Protocol: sqs ticketFraudQueueSubscription: Type: AWS::SNS::Subscription Properties: TopicArn: !Ref ticketTopic Endpoint: !GetAtt ticketFraudQueue.Arn Protocol: sqs Message archiving and analytics example use case 343 Amazon Simple Notification Service Developer Guide ticketUploadStreamRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Sid: '' Effect: Allow Principal: Service: firehose.amazonaws.com Action: sts:AssumeRole ticketUploadStreamRolePolicy: Type: AWS::IAM::Policy Properties: PolicyName: FirehoseticketUploadStreamRolePolicy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - s3:AbortMultipartUpload - s3:GetBucketLocation - s3:GetObject - s3:ListBucket - s3:ListBucketMultipartUploads - s3:PutObject Resource: - !Sub 'arn:aws:s3:::${ticketArchiveBucket}' - !Sub 'arn:aws:s3:::${ticketArchiveBucket}/*' Roles: - !Ref ticketUploadStreamRole ticketUploadStreamSubscriptionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - sns.amazonaws.com Action: - sts:AssumeRole Policies: Message archiving and analytics example use case 344 Amazon Simple Notification Service Developer Guide - PolicyName: SNSKinesisFirehoseAccessPolicy PolicyDocument: Version: '2012-10-17' Statement: - Action: - firehose:DescribeDeliveryStream - firehose:ListDeliveryStreams - firehose:ListTagsForDeliveryStream - firehose:PutRecord - firehose:PutRecordBatch Effect: Allow Resource: - !GetAtt ticketUploadStream.Arn Fanout Amazon SNS notifications to Lambda functions for automated processing Amazon SNS integrates with AWS Lambda, allowing you to trigger Lambda functions in response to Amazon SNS notifications. When a message is published to an SNS topic that has a Lambda function subscribed to it, the Lambda function is invoked with the payload of the published message. The Lambda function receives the message payload as an input parameter and can manipulate the information in the message, publish the message to other SNS topics, or send the message to other AWS services. Amazon SNS also supports message delivery status attributes for message notifications sent to Lambda endpoints. For more information, see Amazon SNS message delivery status. Topics • Prerequisites for integrating Amazon SNS with Lambda functions across regions • Subscribing a Lambda function to an Amazon SNS topic Prerequisites for integrating Amazon SNS with Lambda functions across regions To invoke Lambda functions using Amazon SNS notifications, you need the following: • A Lambda function • An Amazon SNS topic Fanout to Lambda functions 345 Amazon Simple Notification Service Developer Guide For information about creating a Lambda function to use with Amazon SNS, see Using Lambda with Amazon SNS. For information about creating an Amazon SNS topic, see Create a topic. When you use Amazon SNS to deliver messages from opt-in regions to regions which are enabled by default, you must alter the policy created in the AWS Lambda function by replacing the principal sns.amazonaws.com with sns.<opt-in-region>.amazonaws.com. For example, if you want to subscribe a Lambda function in US East (N. Virginia) to an SNS topic in Asia Pacific (Hong Kong), change the principal in the AWS Lambda function policy to sns.ap- east-1.amazonaws.com. Opt-in regions include any regions launched after March 20, 2019, which includes Asia Pacific (Hong Kong), Middle East (Bahrain), EU (Milano), and Africa (Cape Town). Regions launched prior to March 20, 2019 are enabled by default. Note AWS doesn't support cross-region delivery to Lambda from a region that is enabled by default to an opt-in region. Also, cross-region forwarding of SNS messages from opt-in regions to other opt-in regions is not supported. Subscribing a Lambda function to an Amazon SNS topic This topic explains how to subscribe a Lambda function to an Amazon SNS topic, enabling the function to be triggered by published messages. 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. On the Topics page, choose a topic.
|
sns-dg-093
|
sns-dg.pdf
| 93 |
prior to March 20, 2019 are enabled by default. Note AWS doesn't support cross-region delivery to Lambda from a region that is enabled by default to an opt-in region. Also, cross-region forwarding of SNS messages from opt-in regions to other opt-in regions is not supported. Subscribing a Lambda function to an Amazon SNS topic This topic explains how to subscribe a Lambda function to an Amazon SNS topic, enabling the function to be triggered by published messages. 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. On the Topics page, choose a topic. 4. In the Subscriptions section, choose Create subscription. 5. On the Create subscription page, in the Details section, do the following: a. Verify the chosen Topic ARN. b. c. For Protocol choose AWS Lambda. For Endpoint enter the ARN of a function. d. Choose Create subscription. Subscribing a function to a topic 346 Amazon Simple Notification Service Developer Guide When a message is published to an SNS topic that has a Lambda function subscribed to it, the Lambda function is invoked with the payload of the published message. For information about how to use AWS Lambda with Amazon SNS, including a tutorial, see Using AWS Lambda with Amazon SNS. Fanout Amazon SNS notifications to Amazon SQS queues for asynchronous processing Amazon SNS works closely with Amazon Simple Queue Service (Amazon SQS). These services provide different benefits for developers. Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates. Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available. Using Amazon SNS and Amazon SQS together, messages can be delivered to applications that require immediate notification of an event, and also persisted in an Amazon SQS queue for other applications to process at a later time. When you subscribe an Amazon SQS queue to an Amazon SNS topic, you can publish a message to the topic and Amazon SNS sends an Amazon SQS message to the subscribed queue. The Amazon SQS message contains the subject and message that were published to the topic along with metadata about the message in a JSON document. The Amazon SQS message will look similar to the following JSON document. { "Type" : "Notification", "MessageId" : "63a3f6b6-d533-4a47-aef9-fcf5cf758c76", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "Testing publish to subscribed queues", "Message" : "Hello world!", "Timestamp" : "2012-03-29T05:12:16.901Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEnTrFPa3...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService- f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:c7fe3a54- ab0e-4ec2-88e0-db410a0f2bee" } Fanout to Amazon SQS queues 347 Amazon Simple Notification Service Developer Guide Subscribing an Amazon SQS queue to an Amazon SNS topic To enable an Amazon SNS topic to send messages to an Amazon SQS queue, choose one of the following: • Use the Amazon SQS console, which simplifies the process. For more information, see Subscribing an Amazon SQS queue to an Amazon SNS topic in the Amazon Simple Queue Service Developer Guide. • Use the following steps: 1. Get the Amazon Resource Name (ARN) of the queue you want to send messages to and the topic to which you want to subscribe the queue. 2. Give sqs:SendMessage permission to the Amazon SNS topic so that it can send messages to the queue. 3. Subscribe the queue to the Amazon SNS topic. 4. Give IAM users or AWS accounts the appropriate permissions to publish to the Amazon SNS topic and read messages from the Amazon SQS queue. 5. Test it out by publishing a message to the topic and reading the message from the queue. To learn about how to set up a topic to send messages to a queue that is in a different AWS- account, see Sending Amazon SNS messages to an Amazon SQS queue in a different account. To see an AWS CloudFormation template that creates a topic that sends messages to two queues, see Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation. Step 1: Get the ARN of the queue and topic When subscribing a queue to your topic, you'll need a copy of the ARN for the queue. Similarly, when giving permission for the topic to send messages to the queue, you'll need a copy of the ARN for the topic. To get the queue ARN, you can use the Amazon SQS console or the GetQueueAttributes API action. To get the queue ARN from the Amazon SQS console 1. Sign in to the AWS Management Console and open the Amazon SQS console at https:// console.aws.amazon.com/sqs/. 2. Select the box for the queue whose ARN you want to get. Subscribing a queue to a topic 348 Amazon Simple Notification Service
|
sns-dg-094
|
sns-dg.pdf
| 94 |
need a copy of the ARN for the queue. Similarly, when giving permission for the topic to send messages to the queue, you'll need a copy of the ARN for the topic. To get the queue ARN, you can use the Amazon SQS console or the GetQueueAttributes API action. To get the queue ARN from the Amazon SQS console 1. Sign in to the AWS Management Console and open the Amazon SQS console at https:// console.aws.amazon.com/sqs/. 2. Select the box for the queue whose ARN you want to get. Subscribing a queue to a topic 348 Amazon Simple Notification Service Developer Guide 3. From the Details section, copy the ARN value so that you can use it to subscribe to the Amazon SNS topic. To get the topic ARN, you can use the Amazon SNS console, the sns-get-topic-attributes command, or the GetQueueAttributes API action. To get the topic ARN from the Amazon SNS console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose the topic whose ARN you want to get. 3. From the Details section, copy the ARN value so that you can use it to give permission for the Amazon SNS topic to send messages to the queue. Step 2: Give permission to the Amazon SNS topic to send messages to the Amazon SQS queue For an Amazon SNS topic to be able to send messages to a queue, you must set a policy on the queue that allows the Amazon SNS topic to perform the sqs:SendMessage action. Before you subscribe a queue to a topic, you need a topic and a queue. If you haven't already created a topic or queue, create them now. For more information, see Creating a topic, and see Create a queue in the Amazon Simple Queue Service Developer Guide. To set a policy on a queue, you can use the Amazon SQS console or the SetQueueAttributes API action. Before you start, make sure you have the ARN for the topic that you want to allow to send messages to the queue. If you are subscribing a queue to multiple topics, your policy must contain one Statement element for each topic. To set a SendMessage policy on a queue using the Amazon SQS console 1. Sign in to the AWS Management Console and open the Amazon SQS console at https:// console.aws.amazon.com/sqs/. 2. Select the box for the queue whose policy you want to set, choose the Access policy tab, and then choose Edit. 3. In the Access policy section, define who can access your queue. • Add a condition that allows the action for the topic. Subscribing a queue to a topic 349 Amazon Simple Notification Service Developer Guide • Set Principal to be the Amazon SNS service, as shown in the example below. • Use the aws:SourceArn or aws:SourceAccount global condition keys to protect against the confused deputy scenario. To use these condition keys, set the value to the ARN of your topic. If your queue is subscribed to multiple topics, you can use aws:SourceAccount instead. For example, the following policy allows MyTopic to send messages to MyQueue. { "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-east-2:123456789012:MyQueue", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-2:123456789012:MyTopic" } } } ] } Step 3: Subscribe the queue to the Amazon SNS topic To send messages to a queue through a topic, you must subscribe the queue to the Amazon SNS topic. You specify the queue by its ARN. To subscribe to a topic, you can use the Amazon SNS console, the sns-subscribe CLI command, or the Subscribe API action. Before you start, make sure you have the ARN for the queue that you want to subscribe. 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. On the Topics page, choose a topic. 4. On the MyTopic page, in the Subscriptions page, choose Create subscription. 5. On the Create subscription page, in the Details section, do the following: Subscribing a queue to a topic 350 Amazon Simple Notification Service a. Verify the Topic ARN. b. c. For Protocol, choose Amazon SQS. For Endpoint, enter the ARN of an Amazon SQS queue. d. Choose Create Subscription. Developer Guide When the subscription is confirmed, your new subscription's Subscription ID displays its subscription ID. If the owner of the queue creates the subscription, the subscription is automatically confirmed and the subscription should be active almost immediately. Usually, you'll be subscribing your own queue to your own topic in your own account. However, you can also subscribe a queue from a different account to your topic. If the user who creates the subscription is not the owner of the queue (for example, if a user from account A subscribes a queue from account
|
sns-dg-095
|
sns-dg.pdf
| 95 |
SQS queue. d. Choose Create Subscription. Developer Guide When the subscription is confirmed, your new subscription's Subscription ID displays its subscription ID. If the owner of the queue creates the subscription, the subscription is automatically confirmed and the subscription should be active almost immediately. Usually, you'll be subscribing your own queue to your own topic in your own account. However, you can also subscribe a queue from a different account to your topic. If the user who creates the subscription is not the owner of the queue (for example, if a user from account A subscribes a queue from account B to a topic in account A), the subscription must be confirmed. For more information about subscribing a queue from a different account and confirming the subscription, see Sending Amazon SNS messages to an Amazon SQS queue in a different account. Step 4: Give users permissions to the appropriate topic and queue actions You should use AWS Identity and Access Management (IAM) to allow only appropriate users to publish to the Amazon SNS topic and to read/delete messages from the Amazon SQS queue. For more information about controlling actions on topics and queues for IAM users, see Using identity- based policies with Amazon SNS, and Identity and access management in Amazon SQS in the Amazon Simple Queue Service Developer Guide. There are two ways to control access to a topic or queue: • Add a policy to an IAM user or group. The simplest way to give users permissions to topics or queues is to create a group and add the appropriate policy to the group and then add users to that group. It's much easier to add and remove users from a group than to keep track of which policies you set on individual users. • Add a policy to topic or queue. If you want to give permissions to a topic or queue to another AWS account, the only way you can do that is by adding a policy that has as its principal the AWS account you want to give permissions to. Subscribing a queue to a topic 351 Amazon Simple Notification Service Developer Guide You should use the first method for most cases (apply policies to groups and manage permissions for users by adding or removing the appropriate users to the groups). If you need to give permissions to a user in another account, you should use the second method. Adding a policy to an IAM user or group If you added the following policy to an IAM user or group, you would give that user or members of that group permission to perform the sns:Publish action on the topic MyTopic. { "Statement": [ { "Effect": "Allow", "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-2:123456789012:MyTopic" } ] } If you added the following policy to an IAM user or group, you would give that user or members of that group permission to perform the sqs:ReceiveMessage and sqs:DeleteMessage actions on the queues MyQueue1 and MyQueue2. { "Statement": [ { "Effect": "Allow", "Action": [ "sqs:ReceiveMessage", "sqs:DeleteMessage" ], "Resource": [ "arn:aws:sqs:us-east-2:123456789012:MyQueue1", "arn:aws:sqs:us-east-2:123456789012:MyQueue2" ] } ] } Subscribing a queue to a topic 352 Amazon Simple Notification Service Developer Guide Adding a policy to a topic or queue The following example policies show how to give another account permissions to a topic and queue. Note When you give another AWS account access to a resource in your account, you are also giving IAM users who have admin-level access (wildcard access) permissions to that resource. All other IAM users in the other account are automatically denied access to your resource. If you want to give specific IAM users in that AWS account access to your resource, the account or an IAM user with admin-level access must delegate permissions for the resource to those IAM users. For more information about cross-account delegation, see Enabling Cross-Account Access in the Using IAM Guide. If you added the following policy to a topic MyTopic in account 123456789012, you would give account 111122223333 permission to perform the sns:Publish action on that topic. { "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "111122223333" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-2:123456789012:MyTopic" } ] } If you added the following policy to a queue MyQueue in account 123456789012, you would give account 111122223333 permission to perform the sqs:ReceiveMessage and sqs:DeleteMessage actions on that queue. { "Statement": [ { "Effect": "Allow", Subscribing a queue to a topic 353 Amazon Simple Notification Service Developer Guide "Principal": { "AWS": "111122223333" }, "Action": [ "sqs:DeleteMessage", "sqs:ReceiveMessage" ], "Resource": [ "arn:aws:sqs:us-east-2:123456789012:MyQueue" ] } ] } Step 5: Test the topic's queue subscriptions You can test a topic's queue subscriptions by publishing to the topic and viewing the message that the topic sends to the queue. To publish to a topic using the Amazon SNS console 1. Using the credentials of
|
sns-dg-096
|
sns-dg.pdf
| 96 |
in account 123456789012, you would give account 111122223333 permission to perform the sqs:ReceiveMessage and sqs:DeleteMessage actions on that queue. { "Statement": [ { "Effect": "Allow", Subscribing a queue to a topic 353 Amazon Simple Notification Service Developer Guide "Principal": { "AWS": "111122223333" }, "Action": [ "sqs:DeleteMessage", "sqs:ReceiveMessage" ], "Resource": [ "arn:aws:sqs:us-east-2:123456789012:MyQueue" ] } ] } Step 5: Test the topic's queue subscriptions You can test a topic's queue subscriptions by publishing to the topic and viewing the message that the topic sends to the queue. To publish to a topic using the Amazon SNS console 1. Using the credentials of the AWS account or IAM user with permission to publish to the topic, sign in to the AWS Management Console and open the Amazon SNS console at https:// console.aws.amazon.com/sns/. 2. On the navigation panel, choose the topic and choose Publish to Topic. 3. In the Subject box, enter a subject (for example, Testing publish to queue) in the Message box, enter some text (for example, Hello world!), and choose Publish Message. The following message appears: Your message has been successfully published. To view the message from the topic using the Amazon SQS console 1. Using the credentials of the AWS account or IAM user with permission to view messages in the queue, sign in to the AWS Management Console and open the Amazon SQS console at https:// console.aws.amazon.com/sqs/. 2. Choose a queue that is subscribed to the topic. 3. Choose Send and receive messages, and then choose Poll for messages. A message with a type of Notification appears. Subscribing a queue to a topic 354 Amazon Simple Notification Service Developer Guide 4. In the Body column, choose More Details. The Message Details box contains a JSON document that contains the subject and message that you published to the topic. The message looks similar to the following JSON document. { "Type" : "Notification", "MessageId" : "63a3f6b6-d533-4a47-aef9-fcf5cf758c76", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "Testing publish to subscribed queues", "Message" : "Hello world!", "Timestamp" : "2012-03-29T05:12:16.901Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEnTrFPa3...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/ SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- west-2:123456789012:MyTopic:c7fe3a54-ab0e-4ec2-88e0-db410a0f2bee" } 5. Choose Close. You have successfully published to a topic that sends notification messages to a queue. Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation AWS CloudFormation enables you to use a template file to create and configure a collection of AWS resources together as a single unit. This section has an example template that makes it easy to deploy topics that publish to queues. The templates take care of the setup steps for you by creating two queues, creating a topic with subscriptions to the queues, adding a policy to the queues so that the topic can send messages to the queues, and creating IAM users and groups to control access to those resources. For more information about deploying AWS resources using an AWS CloudFormation template, see Get Started in the AWS CloudFormation User Guide. Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 355 Amazon Simple Notification Service Developer Guide Using an AWS CloudFormation template to set up topics and queues within an AWS account The example template creates an Amazon SNS topic that can send messages to two Amazon SQS queues with appropriate permissions for members of one IAM group to publish to the topic and another to read messages from the queues. The template also creates IAM users that are added to each group. You copy the template contents into a file. You can also download the template from the AWS CloudFormation Templates page. On the templates page, choose Browse sample templates by AWS serviceand then choose Amazon Simple Queue Service. MySNSTopic is set up to publish to two subscribed endpoints, which are two Amazon SQS queues (MyQueue1 and MyQueue2). MyPublishTopicGroup is an IAM group whose members have permission to publish to MySNSTopic using the Publish API action or sns-publish command. The template creates the IAM users MyPublishUser and MyQueueUser and gives them login profiles and access keys. The user who creates a stack with this template specifies the passwords for the login profiles as input parameters. The template creates access keys for the two IAM users with MyPublishUserKey and MyQueueUserKey. AddUserToMyPublishTopicGroup adds MyPublishUser to the MyPublishTopicGroup so that the user will have the permissions assigned to the group. MyRDMessageQueueGroup is an IAM group whose members have permission to read and delete messages from the two Amazon SQS queues using the ReceiveMessage and DeleteMessage API actions. AddUserToMyQueueGroup adds MyQueueUser to the MyRDMessageQueueGroup so that the user will have the permissions assigned to the group. MyQueuePolicy assigns permission for MySNSTopic to publish its notifications to the two queues. The following listing shows the AWS CloudFormation template contents. { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template SNSToSQS: This Template creates an SNS topic that can
|
sns-dg-097
|
sns-dg.pdf
| 97 |
the MyPublishTopicGroup so that the user will have the permissions assigned to the group. MyRDMessageQueueGroup is an IAM group whose members have permission to read and delete messages from the two Amazon SQS queues using the ReceiveMessage and DeleteMessage API actions. AddUserToMyQueueGroup adds MyQueueUser to the MyRDMessageQueueGroup so that the user will have the permissions assigned to the group. MyQueuePolicy assigns permission for MySNSTopic to publish its notifications to the two queues. The following listing shows the AWS CloudFormation template contents. { "AWSTemplateFormatVersion" : "2010-09-09", "Description" : "AWS CloudFormation Sample Template SNSToSQS: This Template creates an SNS topic that can send messages to two SQS queues with appropriate permissions for one IAM user to publish to the topic and another to read messages from the queues. MySNSTopic is set up to publish to two subscribed endpoints, which are two SQS queues (MyQueue1 and MyQueue2). MyPublishUser is an IAM user that can publish to MySNSTopic using the Publish API. MyTopicPolicy assigns that permission to MyPublishUser. MyQueueUser is an IAM user Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 356 Amazon Simple Notification Service Developer Guide that can read messages from the two SQS queues. MyQueuePolicy assigns those permissions to MyQueueUser. It also assigns permission for MySNSTopic to publish its notifications to the two queues. The template creates access keys for the two IAM users with MyPublishUserKey and MyQueueUserKey. ***Warning*** you will be billed for the AWS resources used if you create a stack from this template.", "Parameters": { "MyPublishUserPassword": { "NoEcho": "true", "Type": "String", "Description": "Password for the IAM user MyPublishUser", "MinLength": "1", "MaxLength": "41", "AllowedPattern": "[a-zA-Z0-9]*", "ConstraintDescription": "must contain only alphanumeric characters." }, "MyQueueUserPassword": { "NoEcho": "true", "Type": "String", "Description": "Password for the IAM user MyQueueUser", "MinLength": "1", "MaxLength": "41", "AllowedPattern": "[a-zA-Z0-9]*", "ConstraintDescription": "must contain only alphanumeric characters." } }, "Resources": { "MySNSTopic": { "Type": "AWS::SNS::Topic", "Properties": { "Subscription": [{ "Endpoint": { "Fn::GetAtt": ["MyQueue1", "Arn"] }, "Protocol": "sqs" }, { "Endpoint": { "Fn::GetAtt": ["MyQueue2", "Arn"] }, "Protocol": "sqs" Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 357 Amazon Simple Notification Service Developer Guide } ] } }, "MyQueue1": { "Type": "AWS::SQS::Queue" }, "MyQueue2": { "Type": "AWS::SQS::Queue" }, "MyPublishUser": { "Type": "AWS::IAM::User", "Properties": { "LoginProfile": { "Password": { "Ref": "MyPublishUserPassword" } } } }, "MyPublishUserKey": { "Type": "AWS::IAM::AccessKey", "Properties": { "UserName": { "Ref": "MyPublishUser" } } }, "MyPublishTopicGroup": { "Type": "AWS::IAM::Group", "Properties": { "Policies": [{ "PolicyName": "MyTopicGroupPolicy", "PolicyDocument": { "Statement": [{ "Effect": "Allow", "Action": [ "sns:Publish" ], "Resource": { "Ref": "MySNSTopic" } }] } Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 358 Amazon Simple Notification Service Developer Guide }] } }, "AddUserToMyPublishTopicGroup": { "Type": "AWS::IAM::UserToGroupAddition", "Properties": { "GroupName": { "Ref": "MyPublishTopicGroup" }, "Users": [{ "Ref": "MyPublishUser" }] } }, "MyQueueUser": { "Type": "AWS::IAM::User", "Properties": { "LoginProfile": { "Password": { "Ref": "MyQueueUserPassword" } } } }, "MyQueueUserKey": { "Type": "AWS::IAM::AccessKey", "Properties": { "UserName": { "Ref": "MyQueueUser" } } }, "MyRDMessageQueueGroup": { "Type": "AWS::IAM::Group", "Properties": { "Policies": [{ "PolicyName": "MyQueueGroupPolicy", "PolicyDocument": { "Statement": [{ "Effect": "Allow", "Action": [ "sqs:DeleteMessage", "sqs:ReceiveMessage" ], Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 359 Amazon Simple Notification Service Developer Guide "Resource": [{ "Fn::GetAtt": ["MyQueue1", "Arn"] }, { "Fn::GetAtt": ["MyQueue2", "Arn"] } ] }] } }] } }, "AddUserToMyQueueGroup": { "Type": "AWS::IAM::UserToGroupAddition", "Properties": { "GroupName": { "Ref": "MyRDMessageQueueGroup" }, "Users": [{ "Ref": "MyQueueUser" }] } }, "MyQueuePolicy": { "Type": "AWS::SQS::QueuePolicy", "Properties": { "PolicyDocument": { "Statement": [{ "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": ["sqs:SendMessage"], "Resource": "*", "Condition": { "ArnEquals": { "aws:SourceArn": { "Ref": "MySNSTopic" } } } }] }, "Queues": [{ Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 360 Amazon Simple Notification Service Developer Guide "Ref": "MyQueue1" }, { "Ref": "MyQueue2" }] } } }, "Outputs": { "MySNSTopicTopicARN": { "Value": { "Ref": "MySNSTopic" } }, "MyQueue1Info": { "Value": { "Fn::Join": [ " ", [ "ARN:", { "Fn::GetAtt": ["MyQueue1", "Arn"] }, "URL:", { "Ref": "MyQueue1" } ] ] } }, "MyQueue2Info": { "Value": { "Fn::Join": [ " ", [ "ARN:", { "Fn::GetAtt": ["MyQueue2", "Arn"] }, "URL:", { "Ref": "MyQueue2" } ] Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 361 Amazon Simple Notification Service Developer Guide ] } }, "MyPublishUserInfo": { "Value": { "Fn::Join": [ " ", [ "ARN:", { "Fn::GetAtt": ["MyPublishUser", "Arn"] }, "Access Key:", { "Ref": "MyPublishUserKey" }, "Secret Key:", { "Fn::GetAtt": ["MyPublishUserKey", "SecretAccessKey"] } ] ] } }, "MyQueueUserInfo": { "Value": { "Fn::Join": [ " ", [ "ARN:", { "Fn::GetAtt": ["MyQueueUser", "Arn"] }, "Access Key:", { "Ref": "MyQueueUserKey" }, "Secret Key:", { "Fn::GetAtt": ["MyQueueUserKey", "SecretAccessKey"] } ] ] } Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 362 Amazon Simple Notification Service Developer Guide } } } Fanout Amazon SNS notifications to HTTPS endpoints You can use Amazon SNS to send notification messages to one or more HTTP or
|
sns-dg-098
|
sns-dg.pdf
| 98 |
[ " ", [ "ARN:", { "Fn::GetAtt": ["MyPublishUser", "Arn"] }, "Access Key:", { "Ref": "MyPublishUserKey" }, "Secret Key:", { "Fn::GetAtt": ["MyPublishUserKey", "SecretAccessKey"] } ] ] } }, "MyQueueUserInfo": { "Value": { "Fn::Join": [ " ", [ "ARN:", { "Fn::GetAtt": ["MyQueueUser", "Arn"] }, "Access Key:", { "Ref": "MyQueueUserKey" }, "Secret Key:", { "Fn::GetAtt": ["MyQueueUserKey", "SecretAccessKey"] } ] ] } Automate Amazon SNS to Amazon SQS messaging with AWS CloudFormation 362 Amazon Simple Notification Service Developer Guide } } } Fanout Amazon SNS notifications to HTTPS endpoints You can use Amazon SNS to send notification messages to one or more HTTP or HTTPS endpoints. When you subscribe an endpoint to a topic, you can publish a notification to the topic and Amazon SNS sends an HTTP POST request delivering the contents of the notification to the subscribed endpoint. When you subscribe the endpoint, you choose whether Amazon SNS uses HTTP or HTTPS to send the POST request to the endpoint. If you use HTTPS, then you can take advantage of the support in Amazon SNS for the following: • Server Name Indication (SNI)—This allows Amazon SNS to support HTTPS endpoints that require SNI, such as a server requiring multiple certificates for hosting multiple domains. For more information about SNI, see Server Name Indication. • Basic and Digest Access Authentication—This allows you to specify a username and password in the HTTPS URL for the HTTP POST request, such as https://user:password@domain.com or https://user@domain.com The username and password are encrypted over the SSL connection established when using HTTPS. Only the domain name is sent in plaintext. For more information about Basic and Digest Access Authentication, see RFC-2617. Important Amazon SNS does not currently support private HTTP(S) endpoints. HTTPS URLs are only retrievable from the Amazon SNS GetSubscriptionAttributes API action, for principals to which you have granted API access. Note The client service must be able to support the HTTP/1.1 401 Unauthorized header response Fanout notifications to HTTPS endpoints 363 Amazon Simple Notification Service Developer Guide The request contains the subject and message that were published to the topic along with metadata about the notification in a JSON document. The request will look similar to the following HTTP POST request. For details about the HTTP header and the JSON format of the request body, see HTTP/HTTPS headers and HTTP/HTTPS notification JSON format. Note Amazon SNS considers all 5XX errors and 429 (too many requests sent) errors as retryable. These errors are subject to the delivery policy. All other errors are considered as permanent failures and retries will not be attempted. POST / HTTP/1.1 x-amz-sns-message-type: Notification x-amz-sns-message-id: da41e39f-ea4d-435a-b922-c6aae3915ebe x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55 Content-Length: 761 Content-Type: text/plain; charset=UTF-8 Host: ec2-50-17-44-49.compute-1.amazonaws.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "Notification", "MessageId" : "da41e39f-ea4d-435a-b922-c6aae3915ebe", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "test", "Message" : "test message", "Timestamp" : "2012-04-25T21:49:25.719Z", "SignatureVersion" : "1", "Signature" : "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService- f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55" } Fanout notifications to HTTPS endpoints 364 Amazon Simple Notification Service Developer Guide Subscribing an HTTPS endpoint to an Amazon SNS topic This topic explains how to subscribe HTTP/S endpoints to Amazon SNS topics. Topics • Step 1: Make sure your endpoint is ready to process Amazon SNS messages • Step 2: Subscribe the HTTP/HTTPS endpoint to the Amazon SNS topic • Step 3: Confirm your Amazon SNS subscription • Step 4: Optional - Set the delivery policy for the Amazon SNS subscription • Step 5: Optional - Give users permissions to publish to the Amazon SNS topic • Step 6: Send Amazon SNS messages to the HTTP/HTTPS endpoint Step 1: Make sure your endpoint is ready to process Amazon SNS messages Before you subscribe your HTTP or HTTPS endpoint to a topic, you must make sure that the HTTP or HTTPS endpoint has the capability to handle the HTTP POST requests that Amazon SNS uses to send the subscription confirmation and notification messages. Usually, this means creating and deploying a web application (for example, a Java servlet if your endpoint host is running Linux with Apache and Tomcat) that processes the HTTP requests from Amazon SNS. When you subscribe an HTTP endpoint, Amazon SNS sends it a subscription confirmation request. Your endpoint must be prepared to receive and process this request when you create the subscription because Amazon SNS sends this request at that time. Amazon SNS will not send notifications to the endpoint until you confirm the subscription. Once you confirm the subscription, Amazon SNS will send notifications to the endpoint when a publish action is performed on the subscribed topic. To set up your endpoint to process subscription confirmation and notification messages 1. Your code should read the HTTP headers of the HTTP POST requests that Amazon SNS sends to your endpoint. Your code should look for the header field x-amz-sns-message-
|
sns-dg-099
|
sns-dg.pdf
| 99 |
be prepared to receive and process this request when you create the subscription because Amazon SNS sends this request at that time. Amazon SNS will not send notifications to the endpoint until you confirm the subscription. Once you confirm the subscription, Amazon SNS will send notifications to the endpoint when a publish action is performed on the subscribed topic. To set up your endpoint to process subscription confirmation and notification messages 1. Your code should read the HTTP headers of the HTTP POST requests that Amazon SNS sends to your endpoint. Your code should look for the header field x-amz-sns-message- type, which tells you the type of message that Amazon SNS has sent to you. By looking at the header, you can determine the message type without having to parse the body of the HTTP request. There are two types that you need to handle: SubscriptionConfirmation and Notification. The UnsubscribeConfirmation message is used only when the subscription is deleted from the topic. For details about the HTTP header, see HTTP/HTTPS headers. The following HTTP POST request is an example of a subscription confirmation message. Subscribing an endpoint to a topic 365 Amazon Simple Notification Service Developer Guide POST / HTTP/1.1 x-amz-sns-message-type: SubscriptionConfirmation x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic Content-Length: 1336 Content-Type: text/plain; charset=UTF-8 Host: example.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "SubscriptionConfirmation", "MessageId" : "165545c9-2a5c-472c-8df2-7ff2be2b3b1b", "Token" : "2336412f37f...", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Message" : "You have chosen to subscribe to the topic arn:aws:sns:us- west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.", "SubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=ConfirmSubscription&TopicArn=arn:aws:sns:us- west-2:123456789012:MyTopic&Token=2336412f37...", "Timestamp" : "2012-04-26T20:45:04.751Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEpH+...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/ SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem" } 2. Your code should parse the JSON document in the body of the HTTP POST request and content-type text/plain to read the name-value pairs that make up the Amazon SNS message. Use a JSON parser that handles converting the escaped representation of control characters back to their ASCII character values (for example, converting \n to a newline character). You can use an existing JSON parser such as the Jackson JSON Processor or write your own. In order to send the text in the subject and message fields as valid JSON, Amazon SNS must convert some control characters to escaped representations that can be included in the JSON document. When you receive the JSON document in the body of the POST request sent to your endpoint, you must convert the escaped characters back to their original character values if you want an exact representation of the original subject and messages published to the topic. This is critical if you want to verify the signature of a notification because the signature uses the message and subject in their original forms as part of the string to sign. Subscribing an endpoint to a topic 366 Amazon Simple Notification Service Developer Guide 3. Your code should verify the authenticity of a notification, subscription confirmation, or unsubscribe confirmation message sent by Amazon SNS. Using information contained in the Amazon SNS message, your endpoint can recreate the signature so that you can verify the contents of the message by matching your signature with the signature that Amazon SNS sent with the message. For more information about verifying the signature of a message, see Verifying the signatures of Amazon SNS messages. 4. Based on the type specified by the header field x-amz-sns-message-type, your code should read the JSON document contained in the body of the HTTP request and process the message. Here are the guidelines for handling the two primary types of messages: SubscriptionConfirmation Read the value for SubscribeURL and visit that URL. To confirm the subscription and start receiving notifications at the endpoint, you must visit the SubscribeURLURL (for example, by sending an HTTP GET request to the URL). See the example HTTP request in the previous step to see what the SubscribeURL looks like. For more information about the format of the SubscriptionConfirmation message, see HTTP/HTTPS subscription confirmation JSON format. When you visit the URL, you will get back a response that looks like the following XML document. The document returns the subscription ARN for the endpoint within the ConfirmSubscriptionResult element. <ConfirmSubscriptionResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/"> <ConfirmSubscriptionResult> <SubscriptionArn>arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55</ SubscriptionArn> </ConfirmSubscriptionResult> <ResponseMetadata> <RequestId>075ecce8-8dac-11e1-bf80-f781d96e9307</RequestId> </ResponseMetadata> </ConfirmSubscriptionResponse> As an alternative to visiting the SubscribeURL, you can confirm the subscription using the ConfirmSubscription action with the Token set to its corresponding value in the SubscriptionConfirmation message. If you want to allow only the topic owner and subscription owner to be able to unsubscribe the endpoint, you call the ConfirmSubscription action with an AWS signature. Subscribing an endpoint to a topic 367 Amazon Simple Notification Service Notification Developer Guide Read the values for Subject and Message to get the notification information that was published to the topic. For details about the format of the Notification message, see
|
sns-dg-100
|
sns-dg.pdf
| 100 |
</ResponseMetadata> </ConfirmSubscriptionResponse> As an alternative to visiting the SubscribeURL, you can confirm the subscription using the ConfirmSubscription action with the Token set to its corresponding value in the SubscriptionConfirmation message. If you want to allow only the topic owner and subscription owner to be able to unsubscribe the endpoint, you call the ConfirmSubscription action with an AWS signature. Subscribing an endpoint to a topic 367 Amazon Simple Notification Service Notification Developer Guide Read the values for Subject and Message to get the notification information that was published to the topic. For details about the format of the Notification message, see HTTP/HTTPS headers. The following HTTP POST request is an example of a notification message sent to the endpoint example.com. POST / HTTP/1.1 x-amz-sns-message-type: Notification x-amz-sns-message-id: 22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324 x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us- west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96 Content-Length: 773 Content-Type: text/plain; charset=UTF-8 Host: example.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "Notification", "MessageId" : "22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "My First Message", "Message" : "Hello world!", "Timestamp" : "2012-05-02T00:54:06.655Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEw6JRN...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/ SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96" } 5. Make sure that your endpoint responds to the HTTP POST message from Amazon SNS with the appropriate status code. The connection will time out in approximately 15 seconds. If your endpoint does not respond before the connection times out, or if your endpoint returns a status code outside the range of 200–4xx, Amazon SNS will consider the delivery of the message as a failed attempt. Subscribing an endpoint to a topic 368 Amazon Simple Notification Service Developer Guide 6. Make sure that your code can handle message delivery retries from Amazon SNS. If Amazon SNS doesn't receive a successful response from your endpoint, it attempts to deliver the message again. This applies to all messages, including the subscription confirmation message. By default, if the initial delivery of the message fails, Amazon SNS attempts up to three retries with a delay between failed attempts set at 20 seconds. Note The message request times out after approximately 15 seconds. This means that, if the message delivery failure is caused by a timeout, Amazon SNS retries for approximately 35 seconds after the previous delivery attempt. You can set a different delivery policy for the endpoint. Amazon SNS uses the x-amz-sns-message-id header field to uniquely identify each message published to an Amazon SNS topic. By comparing the IDs of the messages you have processed with incoming messages, you can determine whether the message is a retry attempt. 7. If you are subscribing an HTTPS endpoint, make sure that your endpoint has a server certificate from a trusted Certificate Authority (CA). Amazon SNS will only send messages to HTTPS endpoints that have a server certificate signed by a CA trusted by Amazon SNS. 8. Deploy the code that you have created to receive Amazon SNS messages. When you subscribe the endpoint, the endpoint must be ready to receive at least the subscription confirmation message. Step 2: Subscribe the HTTP/HTTPS endpoint to the Amazon SNS topic To send messages to an HTTP or HTTPS endpoint through a topic, you must subscribe the endpoint to the Amazon SNS topic. You specify the endpoint using its URL. To subscribe to a topic, you can use the Amazon SNS console, the sns-subscribe command, or the Subscribe API action. Before you start, make sure you have the URL for the endpoint that you want to subscribe and that your endpoint is prepared to receive the confirmation and notification messages as described in Step 1. To subscribe an HTTP or HTTPS endpoint to a topic using the Amazon SNS console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Subscriptions. Subscribing an endpoint to a topic 369 Amazon Simple Notification Service Developer Guide 3. Choose the Create subscription. 4. 5. In the Protocol drop-down list, select HTTP or HTTPS. In the Endpoint box, paste in the URL for the endpoint that you want the topic to send messages to and then choose Create subscription. 6. The confirmation message is displayed. Choose Close. Your new subscription's Subscription ID displays PendingConfirmation. When you confirm the subscription, Subscription ID will display the subscription ID. Step 3: Confirm your Amazon SNS subscription To confirm your Amazon SNS subscription, follow these steps to ensure your endpoint can successfully receive messages. This process involves setting up your endpoint to handle incoming confirmation messages, retrieving the confirmation URL, and confirming the subscription. You can confirm the subscription either automatically or manually, depending on your setup. 1. After subscribing to an Amazon SNS topic, Amazon SNS sends a confirmation message to your endpoint. This message contains a SubscribeURL that you must use to confirm the subscription. 2. Your endpoint must be set up to listen for incoming messages from
|
sns-dg-101
|
sns-dg.pdf
| 101 |
Step 3: Confirm your Amazon SNS subscription To confirm your Amazon SNS subscription, follow these steps to ensure your endpoint can successfully receive messages. This process involves setting up your endpoint to handle incoming confirmation messages, retrieving the confirmation URL, and confirming the subscription. You can confirm the subscription either automatically or manually, depending on your setup. 1. After subscribing to an Amazon SNS topic, Amazon SNS sends a confirmation message to your endpoint. This message contains a SubscribeURL that you must use to confirm the subscription. 2. Your endpoint must be set up to listen for incoming messages from Amazon SNS. When the confirmation message arrives, extract the SubscribeURL from the message. 3. Once you have the SubscribeURL, you can confirm the subscription in one of two ways: • Automatic confirmation – Your endpoint can automatically confirm the subscription by sending an HTTP GET request to the SubscribeURL. This method does not require manual intervention. • Manual confirmation – If automatic confirmation is not set up, copy the SubscribeURL from the confirmation message and paste it into your browser’s address bar. This will confirm the subscription manually. 4. You can also verify the subscription status using the Amazon SNS console: a. b. c. Sign in to the Amazon SNS console. In the navigation pane, choose Subscriptions. Find your subscription in the list. Subscribing an endpoint to a topic 370 Amazon Simple Notification Service Developer Guide • If confirmed, the SubscriptionArn will be displayed. • If still unconfirmed, it will show as PendingConfirmation. Step 4: Optional - Set the delivery policy for the Amazon SNS subscription By default, if the initial delivery of the message fails, Amazon SNS attempts up to three retries with a delay between failed attempts set at 20 seconds. As discussed in Step 1, your endpoint should have code that can handle retried messages. By setting the delivery policy on a topic or subscription, you can control the frequency and interval that Amazon SNS will retry failed messages. You can also specify the content type for your HTTP/S notifications in DeliveryPolicy. For more information, see Creating an HTTP/S delivery policy. Step 5: Optional - Give users permissions to publish to the Amazon SNS topic By default, the topic owner has permissions to publish the topic. To enable other users or applications to publish to the topic, you should use AWS Identity and Access Management (IAM) to give publish permission to the topic. For more information about giving permissions for Amazon SNS actions to IAM users, see Using identity-based policies with Amazon SNS. There are two ways to control access to a topic: • Add a policy to an IAM user or group. The simplest way to give users permissions to topics is to create a group and add the appropriate policy to the group and then add users to that group. It's much easier to add and remove users from a group than to keep track of which policies you set on individual users. • Add a policy to the topic. If you want to give permissions to a topic to another AWS account, the only way you can do that is by adding a policy that has as its principal the AWS account you want to give permissions to. You should use the first method for most cases (apply policies to groups and manage permissions for users by adding or removing the appropriate users to the groups). If you need to give permissions to a user in another account, use the second method. If you added the following policy to an IAM user or group, you would give that user or members of that group permission to perform the sns:Publish action on the topic MyTopic. { Subscribing an endpoint to a topic 371 Amazon Simple Notification Service "Statement":[{ "Sid":"AllowPublishToMyTopic", "Effect":"Allow", "Action":"sns:Publish", "Resource":"arn:aws:sns:us-east-2:123456789012:MyTopic" }] } Developer Guide The following example policy shows how to give another account permissions to a topic. Note When you give another AWS account access to a resource in your account, you are also giving IAM users who have admin-level access (wildcard access) permissions to that resource. All other IAM users in the other account are automatically denied access to your resource. If you want to give specific IAM users in that AWS account access to your resource, the account or an IAM user with admin-level access must delegate permissions for the resource to those IAM users. For more information about cross-account delegation, see Enabling Cross-Account Access in the Using IAM Guide. If you added the following policy to a topic MyTopic in account 123456789012, you would give account 111122223333 permission to perform the sns:Publish action on that topic. { "Statement":[{ "Sid":"Allow-publish-to-topic", "Effect":"Allow", "Principal":{ "AWS":"111122223333" }, "Action":"sns:Publish", "Resource":"arn:aws:sns:us-east-2:123456789012:MyTopic" }] } Step 6: Send Amazon SNS messages to the HTTP/HTTPS endpoint You can
|
sns-dg-102
|
sns-dg.pdf
| 102 |
If you want to give specific IAM users in that AWS account access to your resource, the account or an IAM user with admin-level access must delegate permissions for the resource to those IAM users. For more information about cross-account delegation, see Enabling Cross-Account Access in the Using IAM Guide. If you added the following policy to a topic MyTopic in account 123456789012, you would give account 111122223333 permission to perform the sns:Publish action on that topic. { "Statement":[{ "Sid":"Allow-publish-to-topic", "Effect":"Allow", "Principal":{ "AWS":"111122223333" }, "Action":"sns:Publish", "Resource":"arn:aws:sns:us-east-2:123456789012:MyTopic" }] } Step 6: Send Amazon SNS messages to the HTTP/HTTPS endpoint You can send a message to a topic's subscriptions by publishing to the topic. To publish to a topic, you can use the Amazon SNS console, the sns-publish CLI command, or the Publish API. Subscribing an endpoint to a topic 372 Amazon Simple Notification Service Developer Guide If you followed Step 1, the code that you deployed at your endpoint should process the notification. To publish to a topic using the Amazon SNS console 1. Using the credentials of the AWS account or IAM user with permission to publish to the topic, sign in to the AWS Management Console and open the Amazon SNS console at https:// console.aws.amazon.com/sns/. 2. On the navigation panel, choose Topics and then choose a topic. 3. Choose the Publish message button. 4. 5. In the Subject box, enter a subject (for example, Testing publish to my endpoint). In the Message box, enter some text (for example, Hello world!), and choose Publish message. The following message appears: Your message has been successfully published. Verifying the signatures of Amazon SNS messages Amazon SNS uses message signatures to confirm the authenticity of messages sent to your HTTP endpoint. To ensure message integrity and prevent spoofing, you must verify the signature before processing any Amazon SNS messages. When should you verify Amazon SNS signatures? You should verify Amazon SNS message signatures in the following scenarios: • When Amazon SNS sends a notification message to your HTTP(S) endpoint. • When Amazon SNS sends a confirmation message to your endpoint after a Subscribe or Unsubscribe API call. Amazon SNS supports two signature versions: • SignatureVersion1 – Uses an SHA1 hash of the message. • SignatureVersion2 – Uses an SHA256 hash of the message. This provides stronger security and is the recommended option. To correctly verify SNS message signatures, follow these best practices: Verifying message signatures 373 Amazon Simple Notification Service Developer Guide • Always retrieve the signing certificate using HTTPS to prevent unauthorized interception attacks. • Check that the certificate is issued by Amazon SNS. • Confirm that the certificate’s chain of trust is valid. • The certificate should come from an SNS-signed URL. • Don't trust any certificates provided in the message without validation. • Reject any message with an unexpected TopicArn to prevent spoofing. • The AWS SDKs for Amazon SNS provide built-in validation logic, reducing the risk of misimplementation. Configuring the message signature version on Amazon SNS topics Configuring the message signature version on Amazon SNS topics allows you to enhance the security and compatibility of your message verification process. Select between SignatureVersion1 (SHA1) and SignatureVersion2 (SHA256) to control the hashing algorithm used for signing messages. Amazon SNS topics default to SignatureVersion1. You can configure this setting using the SetTopicAttributes API action. Use the following example to set the topic attribute SignatureVersion using the AWS CLI: aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-east-2:123456789012:MyTopic \ --attribute-name SignatureVersion \ --attribute-value 2 Verifying the signature of an Amazon SNS message when using HTTP query- based requests Verifying the signature of an Amazon SNS message when using HTTP query-based requests ensures the message's authenticity and integrity. This process confirms that the message originates from Amazon SNS and has not been tampered with during transit. By parsing the message, constructing the correct string to sign, and validating the signature against a trusted public key, you safeguard your system against spoofing and unauthorized message alterations. 1. Extract key-value pairs from the JSON document in the HTTP POST request body sent by Amazon SNS. These fields are required to construct the string to sign. Verifying message signatures 374 Amazon Simple Notification Service Developer Guide • Message • Subject (if present) • MessageId • Timestamp • TopicArn • Type For example: MESSAGE_FILE="message.json" FIELDS=("Message" "MessageId" "Subject" "Timestamp" "TopicArn" "Type") Note If any field contains escaped characters (for example, \n), convert them to their original form to ensure an exact match. 2. Locate the SigningCertURL field in the Amazon SNS message. This certificate contains the public key needed to verify the message signature. For example: SIGNING_CERT_URL=$(jq -r '.SigningCertURL' "$MESSAGE_FILE") 3. Ensure the SigningCertURL is from a trusted AWS domain (for example, https://sns.us- east-1.amazonaws.com). Reject any URLs outside AWS domains for security reasons. 4. Download the X.509 certificate from the provided URL.
|
sns-dg-103
|
sns-dg.pdf
| 103 |
(if present) • MessageId • Timestamp • TopicArn • Type For example: MESSAGE_FILE="message.json" FIELDS=("Message" "MessageId" "Subject" "Timestamp" "TopicArn" "Type") Note If any field contains escaped characters (for example, \n), convert them to their original form to ensure an exact match. 2. Locate the SigningCertURL field in the Amazon SNS message. This certificate contains the public key needed to verify the message signature. For example: SIGNING_CERT_URL=$(jq -r '.SigningCertURL' "$MESSAGE_FILE") 3. Ensure the SigningCertURL is from a trusted AWS domain (for example, https://sns.us- east-1.amazonaws.com). Reject any URLs outside AWS domains for security reasons. 4. Download the X.509 certificate from the provided URL. For example: curl -s "$SIGNING_CERT_URL" -o signing_cert.pem 5. Extract the public key from the downloaded X.509 certificate. The public key allows you to decrypt the message's signature and verify its integrity. For example: openssl x509 -pubkey -noout -in signing_cert.pem > public_key.pem 6. Different message types require different key-value pairs in the string to sign. Identify the message type (Type field in the Amazon SNS message) to determine which key-value pairs to include: Verifying message signatures 375 Amazon Simple Notification Service Developer Guide • Notification message – Includes Message, MessageId, Subject (if present), Timestamp, TopicArn, and Type. • SubscriptionConfirmation or UnsubscribeConfirmation message – Includes Message, MessageId, SubscribeURL, Timestamp, Token, TopicArn, and Type. 7. Amazon SNS requires the string to sign to follow a strict, fixed field order for verification. Only the explicitly required fields must be included—no extra fields can be added. Optional fields, such as Subject, must be included only if present in the message and must appear in the exact position defined by the required field order. For example: KeyNameOne\nValueOne\nKeyNameTwo\nValueTwo Important Do not add a newline character at the end of the string. 8. Arrange the key-value pairs in byte-sort order (alphabetical by key name). 9. Construct the string to sign using the following format example: STRING_TO_SIGN="" for FIELD in "${FIELDS[@]}"; do VALUE=$(jq -r --arg field "$FIELD" '.[$field]' "$MESSAGE_FILE") STRING_TO_SIGN+="$FIELD\n$VALUE" # Append a newline after each field except the last one if [[ "$FIELD" != "Type" ]]; then STRING_TO_SIGN+="\n" fi done Notification message example: Message My Test Message MessageId 4d4dc071-ddbf-465d-bba8-08f81c89da64 Subject My subject Timestamp 2019-01-31T04:37:04.321Z Verifying message signatures 376 Amazon Simple Notification Service TopicArn arn:aws:sns:us-east-2:123456789012:s4-MySNSTopic-1G1WEFCOXTC0P Type Notification Developer Guide SubscriptionConfirmation example: Message Please confirm your subscription MessageId 3d891288-136d-417f-bc05-901c108273ee SubscribeURL https://sns.us-east-2.amazonaws.com/... Timestamp 2024-01-01T00:00:00.000Z Token abc123... TopicArn arn:aws:sns:us-east-2:123456789012:MyTopic Type SubscriptionConfirmation 10. The Signature field in the message is Base64-encoded. You need to decode it to compare its raw binary form with the derived hash. For example: SIGNATURE=$(jq -r '.Signature' "$MESSAGE_FILE") echo "$SIGNATURE" | base64 -d > signature.bin 11. Use the SignatureVersion field to select the hash algorithm: • For SignatureVersion1, use SHA1 (for example, -sha1). • For SignatureVersion2, use SHA256 (for example, -sha256). 12. To confirm the authenticity of the Amazon SNS message, generate a hash of the constructed string and verify the signature using the public key. openssl dgst -sha256 -verify public_key.pem -signature signature.bin <<< "$STRING_TO_SIGN" If the signature is valid, the output is Verified OK. Otherwise, the output is Verification Failure. Verifying message signatures 377 Amazon Simple Notification Service Developer Guide Example script with error handling The following example script automates the verification process: #!/bin/bash # Path to the local message file MESSAGE_FILE="message.json" # Extract the SigningCertURL and Signature from the message SIGNING_CERT_URL=$(jq -r '.SigningCertURL' "$MESSAGE_FILE") SIGNATURE=$(jq -r '.Signature' "$MESSAGE_FILE") # Fetch the X.509 certificate curl -s "$SIGNING_CERT_URL" -o signing_cert.pem # Extract the public key from the certificate openssl x509 -pubkey -noout -in signing_cert.pem > public_key.pem # Define the fields to include in the string to sign FIELDS=("Message" "MessageId" "Subject" "Timestamp" "TopicArn" "Type") # Initialize the string to sign STRING_TO_SIGN="" # Iterate over the fields to construct the string to sign for FIELD in "${FIELDS[@]}"; do VALUE=$(jq -r --arg field "$FIELD" '.[$field]' "$MESSAGE_FILE") STRING_TO_SIGN+="$FIELD\n$VALUE" # Append a newline after each field except the last one if [[ "$FIELD" != "Type" ]]; then STRING_TO_SIGN+="\n" fi done # Verify the signature echo -e "$STRING_TO_SIGN" | openssl dgst -sha256 -verify public_key.pem -signature <(echo "$SIGNATURE" | base64 -d) Parsing Amazon SNS message formats When Amazon SNS sends messages to HTTP/HTTPS endpoints, they contain both HTTP headers and a JSON message body. These messages follow a structured format that includes metadata Parsing message formats 378 Amazon Simple Notification Service Developer Guide such as the message type, topic ARN, timestamps, and digital signatures. By correctly parsing Amazon SNS messages, you can determine whether a message is a subscription confirmation, notification, or unsubscribe confirmation, extract relevant data, and verify authenticity using signature validation. HTTP/HTTPS headers When Amazon SNS sends a subscription confirmation, notification, or unsubscribe confirmation message to HTTP/HTTPS endpoints, it sends a POST message with a number of Amazon SNS- specific header values. You can use header values for such tasks as identifying the message type without having to parse the JSON message body to
|
sns-dg-104
|
sns-dg.pdf
| 104 |
378 Amazon Simple Notification Service Developer Guide such as the message type, topic ARN, timestamps, and digital signatures. By correctly parsing Amazon SNS messages, you can determine whether a message is a subscription confirmation, notification, or unsubscribe confirmation, extract relevant data, and verify authenticity using signature validation. HTTP/HTTPS headers When Amazon SNS sends a subscription confirmation, notification, or unsubscribe confirmation message to HTTP/HTTPS endpoints, it sends a POST message with a number of Amazon SNS- specific header values. You can use header values for such tasks as identifying the message type without having to parse the JSON message body to read the Type value. By default, Amazon SNS sends all the notification to HTTP/S endpoints with Content-Type set to text/ plain; charset=UTF-8. To choose a Content-Type other than text/plain (default), see headerContentType in Creating an HTTP/S delivery policy. x-amz-sns-message-type The type of message. The possible values are SubscriptionConfirmation, Notification, and UnsubscribeConfirmation. x-amz-sns-message-id A Universally Unique Identifier (UUID), unique for each message published. For a notification that Amazon SNS resends during a retry, the message ID of the original message is used. x-amz-sns-topic-arn The Amazon Resource Name (ARN) for the topic that this message was published to. x-amz-sns-subscription-arn The ARN for the subscription to this endpoint. The following HTTP POST header is an example of a header for a Notification message to an HTTP endpoint. POST / HTTP/1.1 x-amz-sns-message-type: Notification x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55 Parsing message formats 379 Amazon Simple Notification Service Content-Length: 1336 Content-Type: text/plain; charset=UTF-8 Host: myhost.example.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent Developer Guide HTTP/HTTPS subscription confirmation JSON format After you subscribe an HTTP/HTTPS endpoint, Amazon SNS sends a subscription confirmation message to the HTTP/HTTPS endpoint. This message contains a SubscribeURL value that you must visit to confirm the subscription (alternatively, you can use the Token value with the ConfirmSubscription). Note Amazon SNS doesn't send notifications to this endpoint until the subscription is confirmed The subscription confirmation message is a POST message with a message body that contains a JSON document with the following name-value pairs. Type The type of message. For a subscription confirmation, the type is SubscriptionConfirmation. MessageId A Universally Unique Identifier (UUID), unique for each message published. For a message that Amazon SNS resends during a retry, the message ID of the original message is used. Token A value you can use with the ConfirmSubscription action to confirm the subscription. Alternatively, you can simply visit the SubscribeURL. TopicArn The Amazon Resource Name (ARN) for the topic that this endpoint is subscribed to. Message A string that describes the message. For subscription confirmation, this string looks like this: Parsing message formats 380 Amazon Simple Notification Service Developer Guide You have chosen to subscribe to the topic arn:aws:sns:us- east-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message. SubscribeURL The URL that you must visit in order to confirm the subscription. Alternatively, you can instead use the Token with the ConfirmSubscription action to confirm the subscription. Timestamp The time (GMT) when the subscription confirmation was sent. SignatureVersion Version of the Amazon SNS signature used. • If the SignatureVersion is 1, Signature is a Base64-encoded SHA1withRSA signature of the Message, MessageId, Type, Timestamp, and TopicArn values. • If the SignatureVersion is 2, Signature is a Base64-encoded SHA256withRSA signature of the Message, MessageId, Type, Timestamp, and TopicArn values. Signature Base64-encoded SHA1withRSA or SHA256withRSA signature of the Message, MessageId, Type, Timestamp, and TopicArn values. SigningCertURL The URL to the certificate that was used to sign the message. The following HTTP POST message is an example of a SubscriptionConfirmation message to an HTTP endpoint. POST / HTTP/1.1 x-amz-sns-message-type: SubscriptionConfirmation x-amz-sns-message-id: 165545c9-2a5c-472c-8df2-7ff2be2b3b1b x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic Content-Length: 1336 Content-Type: text/plain; charset=UTF-8 Host: myhost.example.com Connection: Keep-Alive Parsing message formats 381 Amazon Simple Notification Service Developer Guide User-Agent: Amazon Simple Notification Service Agent { "Type" : "SubscriptionConfirmation", "MessageId" : "165545c9-2a5c-472c-8df2-7ff2be2b3b1b", "Token" : "2336412f37...", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Message" : "You have chosen to subscribe to the topic arn:aws:sns:us- west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.", "SubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=ConfirmSubscription&TopicArn=arn:aws:sns:us- west-2:123456789012:MyTopic&Token=2336412f37...", "Timestamp" : "2012-04-26T20:45:04.751Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEpH +DcEwjAPg8O9mY8dReBSwksfg2S7WKQcikcNKWLQjwu6A4VbeS0QHVCkhRS7fUQvi2egU3N858fiTDN6bkkOxYDVrY0Ad8L10Hs3zH81mtnPk5uvvolIC1CXGu43obcgFxeL3khZl8IKvO61GWB6jI9b5+gLPoBc1Q=", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService- f3ecfb7224c7233fe7bb5f59f96de52f.pem" } HTTP/HTTPS notification JSON format When Amazon SNS sends a notification to a subscribed HTTP or HTTPS endpoint, the POST message sent to the endpoint has a message body that contains a JSON document with the following name-value pairs. Type The type of message. For a notification, the type is Notification. MessageId A Universally Unique Identifier (UUID), unique for each message published. For a notification that Amazon SNS resends during a retry, the message ID of the original message is used. TopicArn The Amazon Resource Name (ARN) for the topic that this message was published to. Subject The Subject parameter specified when the notification was published to the topic. Parsing message formats 382
|
sns-dg-105
|
sns-dg.pdf
| 105 |
subscribed HTTP or HTTPS endpoint, the POST message sent to the endpoint has a message body that contains a JSON document with the following name-value pairs. Type The type of message. For a notification, the type is Notification. MessageId A Universally Unique Identifier (UUID), unique for each message published. For a notification that Amazon SNS resends during a retry, the message ID of the original message is used. TopicArn The Amazon Resource Name (ARN) for the topic that this message was published to. Subject The Subject parameter specified when the notification was published to the topic. Parsing message formats 382 Amazon Simple Notification Service Developer Guide Note This is an optional parameter. If no Subject was specified, then this name-value pair does not appear in this JSON document. Message The Message value specified when the notification was published to the topic. Timestamp The time (GMT) when the notification was published. SignatureVersion Version of the Amazon SNS signature used. • If the SignatureVersion is 1, Signature is a Base64-encoded SHA1withRSA signature of the Message, MessageId, Subject (if present), Type, Timestamp, and TopicArn values. • If the SignatureVersion is 2, Signature is a Base64-encoded SHA256withRSA signature of the Message, MessageId, Subject (if present), Type, Timestamp, and TopicArn values. Signature Base64-encoded SHA1withRSA or SHA256withRSA signature of the Message, MessageId, Subject (if present), Type, Timestamp, and TopicArn values. SigningCertURL The URL to the certificate that was used to sign the message. UnsubscribeURL A URL that you can use to unsubscribe the endpoint from this topic. If you visit this URL, Amazon SNS unsubscribes the endpoint and stops sending notifications to this endpoint. The following HTTP POST message is an example of a Notification message to an HTTP endpoint. POST / HTTP/1.1 x-amz-sns-message-type: Notification Parsing message formats 383 Amazon Simple Notification Service Developer Guide x-amz-sns-message-id: 22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324 x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us- west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96 Content-Length: 773 Content-Type: text/plain; charset=UTF-8 Host: myhost.example.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "Notification", "MessageId" : "22b80b92-fdea-4c2c-8f9d-bdfb0c7bf324", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "My First Message", "Message" : "Hello world!", "Timestamp" : "2012-05-02T00:54:06.655Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEw6JRN...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService- f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us- west-2:123456789012:MyTopic:c9135db0-26c4-47ec-8998-413945fb5a96" } HTTP/HTTPS unsubscribe confirmation JSON format After an HTTP/HTTPS endpoint is unsubscribed from a topic, Amazon SNS sends an unsubscribe confirmation message to the endpoint. The unsubscribe confirmation message is a POST message with a message body that contains a JSON document with the following name-value pairs. Type The type of message. For a unsubscribe confirmation, the type is UnsubscribeConfirmation. MessageId A Universally Unique Identifier (UUID), unique for each message published. For a message that Amazon SNS resends during a retry, the message ID of the original message is used. Parsing message formats 384 Amazon Simple Notification Service Developer Guide Token A value you can use with the ConfirmSubscription action to re-confirm the subscription. Alternatively, you can simply visit the SubscribeURL. TopicArn The Amazon Resource Name (ARN) for the topic that this endpoint has been unsubscribed from. Message A string that describes the message. For unsubscribe confirmation, this string looks like this: You have chosen to deactivate subscription arn:aws:sns:us- east-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55.\nTo cancel this operation and restore the subscription, visit the SubscribeURL included in this message. SubscribeURL The URL that you must visit in order to re-confirm the subscription. Alternatively, you can instead use the Token with the ConfirmSubscription action to re-confirm the subscription. Timestamp The time (GMT) when the unsubscribe confirmation was sent. SignatureVersion Version of the Amazon SNS signature used. • If the SignatureVersion is 1, Signature is a Base64-encoded SHA1withRSA signature of the Message, MessageId, Type, Timestamp, and TopicArn values. • If the SignatureVersion is 2, Signature is a Base64-encoded SHA256withRSA signature of the Message, MessageId, Type, Timestamp, and TopicArn values. Signature Base64-encoded SHA1withRSA or SHA256withRSA signature of the Message, MessageId, Type, Timestamp, and TopicArn values. SigningCertURL The URL to the certificate that was used to sign the message. Parsing message formats 385 Amazon Simple Notification Service Developer Guide The following HTTP POST message is an example of a UnsubscribeConfirmation message to an HTTP endpoint. POST / HTTP/1.1 x-amz-sns-message-type: UnsubscribeConfirmation x-amz-sns-message-id: 47138184-6831-46b8-8f7c-afc488602d7d x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55 Content-Length: 1399 Content-Type: text/plain; charset=UTF-8 Host: myhost.example.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "UnsubscribeConfirmation", "MessageId" : "47138184-6831-46b8-8f7c-afc488602d7d", "Token" : "2336412f37...", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Message" : "You have chosen to deactivate subscription arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55.\nTo cancel this operation and restore the subscription, visit the SubscribeURL included in this message.", "SubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=ConfirmSubscription&TopicArn=arn:aws:sns:us- west-2:123456789012:MyTopic&Token=2336412f37fb6...", "Timestamp" : "2012-04-26T20:06:41.581Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEHXgJm...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService- f3ecfb7224c7233fe7bb5f59f96de52f.pem" } SetSubscriptionAttributes delivery policy JSON format If you send a request to the SetSubscriptionAttributes action and set the AttributeName parameter to a value of DeliveryPolicy, the value of the AttributeValue parameter must be a valid JSON object. For example, the following example sets the
|
sns-dg-106
|
sns-dg.pdf
| 106 |
Agent { "Type" : "UnsubscribeConfirmation", "MessageId" : "47138184-6831-46b8-8f7c-afc488602d7d", "Token" : "2336412f37...", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Message" : "You have chosen to deactivate subscription arn:aws:sns:us- west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55.\nTo cancel this operation and restore the subscription, visit the SubscribeURL included in this message.", "SubscribeURL" : "https://sns.us-west-2.amazonaws.com/? Action=ConfirmSubscription&TopicArn=arn:aws:sns:us- west-2:123456789012:MyTopic&Token=2336412f37fb6...", "Timestamp" : "2012-04-26T20:06:41.581Z", "SignatureVersion" : "1", "Signature" : "EXAMPLEHXgJm...", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService- f3ecfb7224c7233fe7bb5f59f96de52f.pem" } SetSubscriptionAttributes delivery policy JSON format If you send a request to the SetSubscriptionAttributes action and set the AttributeName parameter to a value of DeliveryPolicy, the value of the AttributeValue parameter must be a valid JSON object. For example, the following example sets the delivery policy to 5 total retries. http://sns.us-east-2.amazonaws.com/ ?Action=SetSubscriptionAttributes Parsing message formats 386 Amazon Simple Notification Service Developer Guide &SubscriptionArn=arn%3Aaws%3Asns%3Aus-east-2%3A123456789012%3AMy-Topic %3A80289ba6-0fd4-4079-afb4-ce8c8260f0ca &AttributeName=DeliveryPolicy &AttributeValue={"healthyRetryPolicy":{"numRetries":5}} ... Use the following JSON format for the value of the AttributeValue parameter. { "healthyRetryPolicy" : { "minDelayTarget" : int, "maxDelayTarget" : int, "numRetries" : int, "numMaxDelayRetries" : int, "backoffFunction" : "linear|arithmetic|geometric|exponential" }, "throttlePolicy" : { "maxReceivesPerSecond" : int }, "requestPolicy" : { "headerContentType" : "text/plain | application/json | application/xml" } } For more information about the SetSubscriptionAttribute action, go to SetSubscriptionAttributes in the Amazon Simple Notification Service API Reference. For more information on the supported HTTP content-type headers, see Creating an HTTP/S delivery policy. SetTopicAttributes delivery policy JSON format If you send a request to the SetTopicAttributes action and set the AttributeName parameter to a value of DeliveryPolicy, the value of the AttributeValue parameter must be a valid JSON object. For example, the following example sets the delivery policy to 5 total retries. http://sns.us-east-2.amazonaws.com/ ?Action=SetTopicAttributes &TopicArn=arn%3Aaws%3Asns%3Aus-east-2%3A123456789012%3AMy-Topic &AttributeName=DeliveryPolicy &AttributeValue={"http":{"defaultHealthyRetryPolicy":{"numRetries":5}}} ... Use the following JSON format for the value of the AttributeValue parameter. Parsing message formats 387 Amazon Simple Notification Service Developer Guide { "http" : { "defaultHealthyRetryPolicy" : { "minDelayTarget": int, "maxDelayTarget": int, "numRetries": int, "numMaxDelayRetries": int, "backoffFunction": "linear|arithmetic|geometric|exponential" }, "disableSubscriptionOverrides" : Boolean, "defaultThrottlePolicy" : { "maxReceivesPerSecond" : int }, "defaultRequestPolicy" : { "headerContentType" : "text/plain | application/json | application/xml" } } } For more information about the SetTopicAttribute action, go to SetTopicAttributes in the Amazon Simple Notification Service API Reference. For more information on the supported HTTP content-type headers, see Creating an HTTP/S delivery policy. Fanout Amazon SNS events to AWS Event Fork Pipelines For event archiving and analytics, Amazon SNS now recommends using its native integration with Amazon Data Firehose. You can subscribe Firehose delivery streams to SNS topics, which allows you to send notifications to archiving and analytics endpoints such as Amazon Simple Storage Service (Amazon S3) buckets, Amazon Redshift tables, Amazon OpenSearch Service (OpenSearch Service), and more. Using Amazon SNS with Firehose delivery streams is a fully- managed and codeless solution that doesn't require you to use AWS Lambda functions. For more information, see Fanout to Firehose delivery streams. You can use Amazon SNS to build event-driven applications which use subscriber services to perform work automatically in response to events triggered by publisher services. This architectural pattern can make services more reusable, interoperable, and scalable. However, it can be labor- intensive to fork the processing of events into pipelines that address common event handling requirements, such as event storage, backup, search, analytics, and replay. Fanout events to AWS Event Fork Pipelines 388 Amazon Simple Notification Service Developer Guide To accelerate the development of your event-driven applications, you can subscribe event-handling pipelines—powered by AWS Event Fork Pipelines—to Amazon SNS topics. AWS Event Fork Pipelines is a suite of open-source nested applications, based on the AWS Serverless Application Model (AWS SAM), which you can deploy directly from the AWS Event Fork Pipelines suite (choose Show apps that create custom IAM roles or resource policies) into your AWS account. For an AWS Event Fork Pipelines use case, see Deploying and testing the Amazon SNS event fork pipelines sample application. Topics • How AWS Event Fork Pipelines works • Deploying AWS Event Fork Pipelines • Deploying and testing the Amazon SNS event fork pipelines sample application • Subscribing AWS Event Fork Pipelines to an Amazon SNS topic How AWS Event Fork Pipelines works AWS Event Fork Pipelines is a serverless design pattern. However, it is also a suite of nested serverless applications based on AWS SAM (which you can deploy directly from the AWS Serverless Application Repository (AWS SAR) to your AWS account in order to enrich your event-driven platforms). You can deploy these nested applications individually, as your architecture requires. Topics • The event storage and backup pipeline • The event search and analytics pipeline • The event replay pipeline The following diagram shows an AWS Event Fork Pipelines application supplemented by three nested applications. You can deploy any of the pipelines from the AWS Event Fork Pipelines suite on the AWS SAR independently, as your architecture requires. How AWS Event Fork Pipelines works 389 Amazon Simple Notification Service Developer Guide Each pipeline is subscribed to the
|
sns-dg-107
|
sns-dg.pdf
| 107 |
SAR) to your AWS account in order to enrich your event-driven platforms). You can deploy these nested applications individually, as your architecture requires. Topics • The event storage and backup pipeline • The event search and analytics pipeline • The event replay pipeline The following diagram shows an AWS Event Fork Pipelines application supplemented by three nested applications. You can deploy any of the pipelines from the AWS Event Fork Pipelines suite on the AWS SAR independently, as your architecture requires. How AWS Event Fork Pipelines works 389 Amazon Simple Notification Service Developer Guide Each pipeline is subscribed to the same Amazon SNS topic, allowing itself to process events in parallel as these events are published to the topic. Each pipeline is independent and can set its own Subscription Filter Policy. This allows a pipeline to process only a subset of the events that it is interested in (rather than all events published to the topic). Note Because you place the three AWS Event Fork Pipelines alongside your regular event processing pipelines (possibly already subscribed to your Amazon SNS topic), you don’t need to change any portion of your current message publisher to take advantage of AWS Event Fork Pipelines in your existing workloads. The event storage and backup pipeline The following diagram shows the Event Storage and Backup Pipeline. You can subscribe this pipeline to your Amazon SNS topic to automatically back up the events flowing through your system. How AWS Event Fork Pipelines works 390 Amazon Simple Notification Service Developer Guide This pipeline is comprised of an Amazon SQS queue that buffers the events delivered by the Amazon SNS topic, an AWS Lambda function that automatically polls for these events in the queue and pushes them into an Amazon Data Firehose stream, and an Amazon S3 bucket that durably backs up the events loaded by the stream. To fine-tune the behavior of your Firehose stream, you can configure it to buffer, transform, and compress your events prior to loading them into the bucket. As events are loaded, you can use Amazon Athena to query the bucket using standard SQL queries. You can also configure the pipeline to reuse an existing Amazon S3 bucket or create a new one. The event search and analytics pipeline The following diagram shows the Event Search and Analytics Pipeline. You can subscribe this pipeline to your Amazon SNS topic to index the events that flow through your system in a search domain and then run analytics on them. This pipeline is comprised of an Amazon SQS queue that buffers the events delivered by the Amazon SNS topic, an AWS Lambda function that polls events from the queue and pushes them into an Amazon Data Firehose stream, an Amazon OpenSearch Service domain that indexes the events loaded by the Firehose stream, and an Amazon S3 bucket that stores the dead-letter events that can’t be indexed in the search domain. How AWS Event Fork Pipelines works 391 Amazon Simple Notification Service Developer Guide To fine-tune your Firehose stream in terms of event buffering, transformation, and compression, you can configure this pipeline. You can also configure whether the pipeline should reuse an existing OpenSearch domain in your AWS account or create a new one for you. As events are indexed in the search domain, you can use Kibana to run analytics on your events and update visual dashboards in real-time. The event replay pipeline The following diagram shows the Event Replay Pipeline. To record the events that have been processed by your system for the past 14 days (for example when your platform needs to recover from failure), you can subscribe this pipeline to your Amazon SNS topic and then reprocess the events. This pipeline is comprised of an Amazon SQS queue that buffers the events delivered by the Amazon SNS topic, and an AWS Lambda function that polls events from the queue and redrives them into your regular event processing pipeline, which is also subscribed to your topic. How AWS Event Fork Pipelines works 392 Amazon Simple Notification Service Developer Guide Note By default, the replay function is disabled, not redriving your events. If you need to reprocess events, you must enable the Amazon SQS replay queue as an event source for the AWS Lambda replay function. Deploying AWS Event Fork Pipelines The AWS Event Fork Pipelines suite (choose Show apps that create custom IAM roles or resource policies) is available as a group of public applications in the AWS Serverless Application Repository, from where you can deploy and test them manually using the AWS Lambda console. For information about deploying pipelines using the AWS Lambda console, see Subscribing AWS Event Fork Pipelines to an Amazon SNS topic. In a production scenario, we recommend embedding AWS Event Fork Pipelines within your overall application's AWS SAM
|
sns-dg-108
|
sns-dg.pdf
| 108 |
replay queue as an event source for the AWS Lambda replay function. Deploying AWS Event Fork Pipelines The AWS Event Fork Pipelines suite (choose Show apps that create custom IAM roles or resource policies) is available as a group of public applications in the AWS Serverless Application Repository, from where you can deploy and test them manually using the AWS Lambda console. For information about deploying pipelines using the AWS Lambda console, see Subscribing AWS Event Fork Pipelines to an Amazon SNS topic. In a production scenario, we recommend embedding AWS Event Fork Pipelines within your overall application's AWS SAM template. The nested-application feature lets you do this by adding the resource AWS::Serverless::Application to your AWS SAM template, referencing the AWS SAR ApplicationId and the SemanticVersion of the nested application. Deploying AWS Event Fork Pipelines 393 Amazon Simple Notification Service Developer Guide For example, you can use the Event Storage and Backup Pipeline as a nested application by adding the following YAML snippet to the Resources section of your AWS SAM template. Backup: Type: AWS::Serverless::Application Properties: Location: ApplicationId: arn:aws:serverlessrepo:us-east-2:123456789012:applications/fork- event-storage-backup-pipeline SemanticVersion: 1.0.0 Parameters: #The ARN of the Amazon SNS topic whose messages should be backed up to the Amazon S3 bucket. TopicArn: !Ref MySNSTopic When you specify parameter values, you can use AWS CloudFormation intrinsic functions to reference other resources in your template. For example, in the YAML snippet above, the TopicArn parameter references the AWS::SNS::Topic resource MySNSTopic, defined elsewhere in the AWS SAM template. For more information, see the Intrinsic Function Reference in the AWS CloudFormation User Guide. Note The AWS Lambda console page for your AWS SAR application includes the Copy as SAM Resource button, which copies the YAML required for nesting an AWS SAR application to the clipboard. Deploying and testing the Amazon SNS event fork pipelines sample application To accelerate the development of your event-driven applications, you can subscribe event-handling pipelines—powered by AWS Event Fork Pipelines—to Amazon SNS topics. AWS Event Fork Pipelines is a suite of open-source nested applications, based on the AWS Serverless Application Model (AWS SAM), which you can deploy directly from the AWS Event Fork Pipelines suite (choose Show apps that create custom IAM roles or resource policies) into your AWS account. For more information, see How AWS Event Fork Pipelines works. Deploying and testing the event fork pipelines sample application 394 Amazon Simple Notification Service Developer Guide This page shows how you can use the AWS Management Console to deploy and test the AWS Event Fork Pipelines sample application. Important To avoid incurring unwanted costs after you finish deploying the AWS Event Fork Pipelines sample application, delete its AWS CloudFormation stack. For more information, see Deleting a Stack on the AWS CloudFormation Console in the AWS CloudFormation User Guide. AWS Event Fork Pipelines use case example The following scenario describes an event-driven, serverless e-commerce application that uses AWS Event Fork Pipelines. You can use this example e-commerce application in the AWS Serverless Application Repository and then deploy it in your AWS account using the AWS Lambda console, where you can test it and examine its source code in GitHub. This e-commerce application takes orders from buyers through a RESTful API hosted by API Gateway and backed by the AWS Lambda function CheckoutApiBackendFunction. This Deploying and testing the event fork pipelines sample application 395 Amazon Simple Notification Service Developer Guide function publishes all received orders to an Amazon SNS topic named CheckoutEventsTopic which, in turn, fans out the orders to four different pipelines. The first pipeline is the regular checkout-processing pipeline designed and implemented by the owner of the e-commerce application. This pipeline has the Amazon SQS queue CheckoutQueue that buffers all received orders, an AWS Lambda function named CheckoutFunction that polls the queue to process these orders, and the DynamoDB table CheckoutTable that securely saves all placed orders. Applying AWS Event Fork Pipelines The components of the e-commerce application handle the core business logic. However, the e- commerce application owner also needs to address the following: • Compliance—secure, compressed backups encrypted at rest and sanitization of sensitive information • Resiliency—replay of most recent orders in case of the disruption of the fulfillment process • Searchability—running analytics and generating metrics on placed orders Instead of implementing this event processing logic, the application owner can subscribe AWS Event Fork Pipelines to the CheckoutEventsTopic Amazon SNS topic • The event storage and backup pipeline is configured to transform data to remove credit card details, buffer data for 60 seconds, compress it using GZIP, and encrypt it using the default customer managed key for Amazon S3. This key is managed by AWS and powered by the AWS Key Management Service (AWS KMS). For more information, see Choose Amazon S3 For Your Destination, Amazon Data Firehose Data Transformation, and Configure Settings in the Amazon Data Firehose
|
sns-dg-109
|
sns-dg.pdf
| 109 |
orders Instead of implementing this event processing logic, the application owner can subscribe AWS Event Fork Pipelines to the CheckoutEventsTopic Amazon SNS topic • The event storage and backup pipeline is configured to transform data to remove credit card details, buffer data for 60 seconds, compress it using GZIP, and encrypt it using the default customer managed key for Amazon S3. This key is managed by AWS and powered by the AWS Key Management Service (AWS KMS). For more information, see Choose Amazon S3 For Your Destination, Amazon Data Firehose Data Transformation, and Configure Settings in the Amazon Data Firehose Developer Guide. • The event search and analytics pipeline is configured with an index retry duration of 30 seconds, a bucket for storing orders that fail to be indexed in the search domain, and a filter policy to restrict the set of indexed orders. For more information, see Choose OpenSearch Service for your Destination in the Amazon Data Firehose Developer Guide. • The event replay pipeline is configured with the Amazon SQS queue part of the regular order- processing pipeline designed and implemented by the e-commerce application owner. Deploying and testing the event fork pipelines sample application 396 Amazon Simple Notification Service Developer Guide For more information, see Queue Name and URL in the Amazon Simple Queue Service Developer Guide. The following JSON filter policy is set in the configuration for the Event Search and Analytics Pipeline. It matches only incoming orders in which the total amount is $100 or higher. For more information, see Amazon SNS message filtering. { "amount": [{ "numeric": [ ">=", 100 ] }] } Using the AWS Event Fork Pipelines pattern, the e-commerce application owner can avoid the development overhead that often follows coding undifferentiating logic for event handling. Instead, she can deploy AWS Event Fork Pipelines directly from the AWS Serverless Application Repository into her AWS account. Step 1: Deploying the sample Amazon SNS application 1. Sign in to the AWS Lambda console. 2. On the navigation panel, choose Functions and then choose Create function. 3. On the Create function page, do the following: a. Choose Browse serverless app repository, Public applications, Show apps that create custom IAM roles or resource policies. b. Search for fork-example-ecommerce-checkout-api and then choose the application. 4. On the fork-example-ecommerce-checkout-api page, do the following: a. In the Application settings section, enter an Application name (for example, fork- example-ecommerce-my-app). Note • To find your resources easily later, keep the prefix fork-example-ecommerce. • For each deployment, the application name must be unique. If you reuse an application name, the deployment will update only the previously deployed AWS CloudFormation stack (rather than create a new one). Deploying and testing the event fork pipelines sample application 397 Amazon Simple Notification Service Developer Guide b. (Optional) Enter one of the following LogLevel settings for the execution of your application's Lambda function: • DEBUG • ERROR • INFO (default) • WARNING 5. Choose I acknowledge that this app creates custom IAM roles, resource policies and deploys nested applications. and then, at the bottom of the page, choose Deploy. On the Deployment status for fork-example-ecommerce-my-app page, Lambda displays the Your application is being deployed status. In the Resources section, AWS CloudFormation begins to create the stack and displays the CREATE_IN_PROGRESS status for each resource. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. Note It might take 20-30 minutes for all resources to be deployed. When the deployment is complete, Lambda displays the Your application has been deployed status. Step 2: Executing the SNS-linked sample application 1. In the AWS Lambda console, on the navigation panel, choose Applications. 2. On the Applications page, in the search field, search for serverlessrepo-fork-example- ecommerce-my-app and then choose the application. 3. In the Resources section, do the following: a. To find the resource whose type is ApiGateway RestApi, sort the resources by Type, for example ServerlessRestApi, and then expand the resource. b. Two nested resources are displayed, of types ApiGateway Deployment and ApiGateway Stage. Deploying and testing the event fork pipelines sample application 398 Amazon Simple Notification Service Developer Guide c. Copy the link Prod API endpoint and append /checkout to it, for example: https://abcdefghij.execute-api.us-east-2.amazonaws.com/Prod/checkout 4. Copy the following JSON to a file named test_event.json. { "id": 15311, "date": "2019-03-25T23:41:11-08:00", "status": "confirmed", "customer": { "id": 65144, "quantity": 2, "price": 25.00, "subtotal": 50.00 }] } 5. To send an HTTPS request to your API endpoint, pass the sample event payload as input by executing a curl command, for example: curl -d "$(cat test_event.json)" https://abcdefghij.execute-api.us- east-2.amazonaws.com/Prod/checkout The API returns the following empty response, indicating a successful execution: { } Step 3: Verifying Amazon SNS application and pipeline performance Step 1: Verifying the execution of the sample checkout pipeline 1. Sign in to the Amazon DynamoDB console. 2. On the navigation
|
sns-dg-110
|
sns-dg.pdf
| 110 |
following JSON to a file named test_event.json. { "id": 15311, "date": "2019-03-25T23:41:11-08:00", "status": "confirmed", "customer": { "id": 65144, "quantity": 2, "price": 25.00, "subtotal": 50.00 }] } 5. To send an HTTPS request to your API endpoint, pass the sample event payload as input by executing a curl command, for example: curl -d "$(cat test_event.json)" https://abcdefghij.execute-api.us- east-2.amazonaws.com/Prod/checkout The API returns the following empty response, indicating a successful execution: { } Step 3: Verifying Amazon SNS application and pipeline performance Step 1: Verifying the execution of the sample checkout pipeline 1. Sign in to the Amazon DynamoDB console. 2. On the navigation panel, choose Tables. 3. Search for serverlessrepo-fork-example and choose CheckoutTable. 4. On the table details page, choose Items and then choose the created item. The stored attributes are displayed. Deploying and testing the event fork pipelines sample application 399 Amazon Simple Notification Service Developer Guide Step 2: Verifying the execution of the event storage and backup pipeline 1. Sign in to the Amazon S3 console. 2. On the navigation panel, choose Buckets. 3. Search for serverlessrepo-fork-example and then choose CheckoutBucket. 4. Navigate the directory hierarchy until you find a file with the extension .gz. 5. 6. To download the file, choose Actions, Open. The pipeline is configured with a Lambda function that sanitizes credit card information for compliance reasons. To verify that the stored JSON payload doesn't contain any credit card information, decompress the file. Step 3: Verifying the execution of the event search and analytics pipeline 1. Sign in to the OpenSearch Service console. 2. On the navigation panel, under My domains, choose the domain prefixed with serverl- analyt. 3. The pipeline is configured with an Amazon SNS subscription filter policy that sets a numeric matching condition. To verify that the event is indexed because it refers to an order whose value is higher than USD $100, on the serverl-analyt-abcdefgh1ijk page, choose Indices, checkout_events. Step 4: Verifying the execution of the event replay pipeline 1. 2. Sign in to the Amazon SQS console. In the list of queues, search for serverlessrepo-fork-example and choose ReplayQueue. 3. Choose Send and receive messages. 4. 5. In the Send and receive messages in fork-example-ecommerce-my-app...ReplayP- ReplayQueue-123ABCD4E5F6 dialog box, choose Poll for messages. To verify that the event is enqueued, choose More Details next to the message that appears in the queue. Deploying and testing the event fork pipelines sample application 400 Amazon Simple Notification Service Developer Guide Step 4: Simulating an issue and replay events for recovery Step 1: Enable the simulated issue and send a second API request 1. Sign in to the AWS Lambda console. 2. On the navigation panel, choose Functions. 3. Search for serverlessrepo-fork-example and choose CheckoutFunction. 4. On the fork-example-ecommerce-my-app-CheckoutFunction-ABCDEF... page, in the Environment variables section, set the BUG_ENABLED variable to true and then choose Save. 5. Copy the following JSON to a file named test_event_2.json. { "id": 9917, "date": "2019-03-26T21:11:10-08:00", "status": "confirmed", "customer": { "id": 56999, "quantity": 1, "price": 75.00, "subtotal": 75.00 }] } 6. To send an HTTPS request to your API endpoint, pass the sample event payload as input by executing a curl command, for example: curl -d "$(cat test_event_2.json)" https://abcdefghij.execute-api.us- east-2.amazonaws.com/Prod/checkout The API returns the following empty response, indicating a successful execution: { } Step 2: Verify simulated data corruption 1. Sign in to the Amazon DynamoDB console. 2. On the navigation panel, choose Tables. 3. Search for serverlessrepo-fork-example and choose CheckoutTable. Deploying and testing the event fork pipelines sample application 401 Amazon Simple Notification Service Developer Guide 4. On the table details page, choose Items and then choose the created item. The stored attributes are displayed, some marked as CORRUPTED! Step 3: Disable the simulated issue 1. Sign in to the AWS Lambda console. 2. On the navigation panel, choose Functions. 3. Search for serverlessrepo-fork-example and choose CheckoutFunction. 4. On the fork-example-ecommerce-my-app-CheckoutFunction-ABCDEF... page, in the Environment variables section, set the BUG_ENABLED variable to false and then choose Save. Step 4: Enable replay to recover from the issue 1. 2. 3. In the AWS Lambda console, on the navigation panel, choose Functions. Search for serverlessrepo-fork-example and choose ReplayFunction. Expand the Designer section, choose the SQS tile and then, in the SQS section, choose Enabled. Note It takes approximately 1 minute for the Amazon SQS event source trigger to become enabled. 4. Choose Save. 5. 6. To view the recovered attributes, return to the Amazon DynamoDB console. To disable replay, return to the AWS Lambda console and disable the Amazon SQS event source trigger for ReplayFunction. Subscribing AWS Event Fork Pipelines to an Amazon SNS topic To accelerate the development of your event-driven applications, you can subscribe event-handling pipelines—powered by AWS Event Fork Pipelines—to Amazon SNS topics. AWS Event Fork Pipelines is a suite of open-source nested applications, based on the AWS Serverless Application Model (AWS
|
sns-dg-111
|
sns-dg.pdf
| 111 |
It takes approximately 1 minute for the Amazon SQS event source trigger to become enabled. 4. Choose Save. 5. 6. To view the recovered attributes, return to the Amazon DynamoDB console. To disable replay, return to the AWS Lambda console and disable the Amazon SQS event source trigger for ReplayFunction. Subscribing AWS Event Fork Pipelines to an Amazon SNS topic To accelerate the development of your event-driven applications, you can subscribe event-handling pipelines—powered by AWS Event Fork Pipelines—to Amazon SNS topics. AWS Event Fork Pipelines is a suite of open-source nested applications, based on the AWS Serverless Application Model (AWS SAM), which you can deploy directly from the AWS Event Fork Pipelines suite (choose Subscribing an event pipeline to a topic 402 Amazon Simple Notification Service Developer Guide Show apps that create custom IAM roles or resource policies) into your AWS account. For more information, see How AWS Event Fork Pipelines works. This section show how you can use the AWS Management Console to deploy a pipeline and then subscribe AWS Event Fork Pipelines to an Amazon SNS topic. Before you begin, create an Amazon SNS topic. To delete the resources that comprise a pipeline, find the pipeline on the Applications page of on the AWS Lambda console, expand the SAM template section, choose CloudFormation stack, and then choose Other Actions, Delete Stack. Deploying and subscribing the Event Storage and Backup Pipeline to Amazon SNS For event archiving and analytics, Amazon SNS now recommends using its native integration with Amazon Data Firehose. You can subscribe Firehose delivery streams to SNS topics, which allows you to send notifications to archiving and analytics endpoints such as Amazon Simple Storage Service (Amazon S3) buckets, Amazon Redshift tables, Amazon OpenSearch Service (OpenSearch Service), and more. Using Amazon SNS with Firehose delivery streams is a fully- managed and codeless solution that doesn't require you to use AWS Lambda functions. For more information, see Fanout to Firehose delivery streams. This page shows how to deploy the Event Storage and Backup Pipeline and subscribe it to an Amazon SNS topic. This process automatically turns the AWS SAM template associated with the pipeline into an AWS CloudFormation stack, and then deploys the stack into your AWS account. This process also creates and configures the set of resources that comprise the Event Storage and Backup Pipeline, including the following: • Amazon SQS queue • Lambda function • Firehose delivery stream • Amazon S3 backup bucket For more information about configuring a stream with an Amazon S3 bucket as a destination, see S3DestinationConfiguration in the Amazon Data Firehose API Reference. Subscribing an event pipeline to a topic 403 Amazon Simple Notification Service Developer Guide For more information about transforming events and about configuring event buffering, event compression, and event encryption, see Creating an Amazon Data Firehose Delivery Stream in the Amazon Data Firehose Developer Guide. For more information about filtering events, see Amazon SNS subscription filter policies in this guide. 1. Sign in to the AWS Lambda console. 2. On the navigation panel, choose Functions and then choose Create function. 3. On the Create function page, do the following: a. Choose Browse serverless app repository, Public applications, Show apps that create custom IAM roles or resource policies. b. Search for fork-event-storage-backup-pipeline and then choose the application. 4. On the fork-event-storage-backup-pipeline page, do the following: a. In the Application settings section, enter an Application name (for example, my-app- backup). Note • For each deployment, the application name must be unique. If you reuse an application name, the deployment will update only the previously deployed AWS CloudFormation stack (rather than create a new one). b. c. d. (Optional) For BucketArn, enter the ARN of the Amazon S3 bucket into which incoming events are loaded. If you don't enter a value, a new Amazon S3 bucket is created in your AWS account. (Optional) For DataTransformationFunctionArn, enter the ARN of the Lambda function through which the incoming events are transformed. If you don't enter a value, data transformation is disabled. (Optional) Enter one of the following LogLevel settings for the execution of your application's Lambda function: • DEBUG • ERROR • INFO (default) Subscribing an event pipeline to a topic 404 Amazon Simple Notification Service • WARNING Developer Guide e. f. g. h. i. j. k. For TopicArn, enter the ARN of the Amazon SNS topic to which this instance of the fork pipeline is to be subscribed. (Optional) For StreamBufferingIntervalInSeconds and StreamBufferingSizeInMBs, enter the values for configuring the buffering of incoming events. If you don't enter any values, 300 seconds and 5 MB are used. (Optional) Enter one of the following StreamCompressionFormat settings for compressing incoming events: • GZIP • SNAPPY • UNCOMPRESSED (default) • ZIP (Optional) For StreamPrefix, enter the string prefix to name files stored in the Amazon S3 backup bucket.
|
sns-dg-112
|
sns-dg.pdf
| 112 |
Service • WARNING Developer Guide e. f. g. h. i. j. k. For TopicArn, enter the ARN of the Amazon SNS topic to which this instance of the fork pipeline is to be subscribed. (Optional) For StreamBufferingIntervalInSeconds and StreamBufferingSizeInMBs, enter the values for configuring the buffering of incoming events. If you don't enter any values, 300 seconds and 5 MB are used. (Optional) Enter one of the following StreamCompressionFormat settings for compressing incoming events: • GZIP • SNAPPY • UNCOMPRESSED (default) • ZIP (Optional) For StreamPrefix, enter the string prefix to name files stored in the Amazon S3 backup bucket. If you don't enter a value, no prefix is used. (Optional) For SubscriptionFilterPolicy, enter the Amazon SNS subscription filter policy, in JSON format, to be used for filtering incoming events. The filter policy decides which events are indexed in the OpenSearch Service index. If you don't enter a value, no filtering is used (all events are indexed). (Optional) For SubscriptionFilterPolicyScope, enter the string MessageBody or MessageAttributes to enable payload-based or attribute-based message filtering. Choose I acknowledge that this app creates custom IAM roles, resource policies and deploys nested applications. and then choose Deploy. On the Deployment status for my-app page, Lambda displays the Your application is being deployed status. In the Resources section, AWS CloudFormation begins to create the stack and displays the CREATE_IN_PROGRESS status for each resource. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. When the deployment is complete, Lambda displays the Your application has been deployed status. Messages published to your Amazon SNS topic are stored in the Amazon S3 backup bucket provisioned by the Event Storage and Backup pipeline automatically. Subscribing an event pipeline to a topic 405 Amazon Simple Notification Service Developer Guide Deploying and subscribing the Event Search and Analytics Pipeline to Amazon SNS For event archiving and analytics, Amazon SNS now recommends using its native integration with Amazon Data Firehose. You can subscribe Firehose delivery streams to SNS topics, which allows you to send notifications to archiving and analytics endpoints such as Amazon Simple Storage Service (Amazon S3) buckets, Amazon Redshift tables, Amazon OpenSearch Service (OpenSearch Service), and more. Using Amazon SNS with Firehose delivery streams is a fully- managed and codeless solution that doesn't require you to use AWS Lambda functions. For more information, see Fanout to Firehose delivery streams. This page shows how to deploy the Event Search and Analytics Pipeline and subscribe it to an Amazon SNS topic. This process automatically turns the AWS SAM template associated with the pipeline into an AWS CloudFormation stack, and then deploys the stack into your AWS account. This process also creates and configures the set of resources that comprise the Event Search and Analytics Pipeline, including the following: • Amazon SQS queue • Lambda function • Firehose delivery stream • Amazon OpenSearch Service domain • Amazon S3 dead-letter bucket For more information about configuring a stream with an index as a destination, see ElasticsearchDestinationConfiguration in the Amazon Data Firehose API Reference. For more information about transforming events and about configuring event buffering, event compression, and event encryption, see Creating an Amazon Data Firehose Delivery Stream in the Amazon Data Firehose Developer Guide. For more information about filtering events, see Amazon SNS subscription filter policies in this guide. 1. Sign in to the AWS Lambda console. 2. On the navigation panel, choose Functions and then choose Create function. Subscribing an event pipeline to a topic 406 Amazon Simple Notification Service Developer Guide 3. On the Create function page, do the following: a. b. Choose Browse serverless app repository, Public applications, Show apps that create custom IAM roles or resource policies. Search for fork-event-search-analytics-pipeline and then choose the application. 4. On the fork-event-search-analytics-pipeline page, do the following: a. In the Application settings section, enter an Application name (for example, my-app- search). Note For each deployment, the application name must be unique. If you reuse an application name, the deployment will update only the previously deployed AWS CloudFormation stack (rather than create a new one). (Optional) For DataTransformationFunctionArn, enter the ARN of the Lambda function used for transforming incoming events. If you don't enter a value, data transformation is disabled. (Optional) Enter one of the following LogLevel settings for the execution of your application's Lambda function: • DEBUG • ERROR • INFO (default) • WARNING (Optional) For SearchDomainArn, enter the ARN of the OpenSearch Service domain, a cluster that configures the needed compute and storage functionality. If you don't enter a value, a new domain is created with the default configuration. For TopicArn, enter the ARN of the Amazon SNS topic to which this instance of the fork pipeline is to be subscribed. For SearchIndexName, enter the name of the OpenSearch Service index for event search and analytics. b. c. d. e. f.
|
sns-dg-113
|
sns-dg.pdf
| 113 |
of the following LogLevel settings for the execution of your application's Lambda function: • DEBUG • ERROR • INFO (default) • WARNING (Optional) For SearchDomainArn, enter the ARN of the OpenSearch Service domain, a cluster that configures the needed compute and storage functionality. If you don't enter a value, a new domain is created with the default configuration. For TopicArn, enter the ARN of the Amazon SNS topic to which this instance of the fork pipeline is to be subscribed. For SearchIndexName, enter the name of the OpenSearch Service index for event search and analytics. b. c. d. e. f. Subscribing an event pipeline to a topic 407 Amazon Simple Notification Service Developer Guide Note The following quotas apply to index names: • Can't include uppercase letters • Can't include the following characters: \ / * ? " < > | ` , # • Can't begin with the following characters: - + _ • Can't be the following: . .. • Can't be longer than 80 characters • Can't be longer than 255 bytes • Can't contain a colon (from OpenSearch Service 7.0) g. (Optional) Enter one of the following SearchIndexRotationPeriod settings for the rotation period of the OpenSearch Service index: • NoRotation (default) • OneDay • OneHour • OneMonth • OneWeek Index rotation appends a timestamp to the index name, facilitating the expiration of old data. h. For SearchTypeName, enter the name of the OpenSearch Service type for organizing the events in an index. Note • OpenSearch Service type names can contain any character (except null bytes) but can't begin with _. • For OpenSearch Service 6.x, there can be only one type per index. If you specify a new type for an existing index that already has another type, Firehose returns a runtime error. Subscribing an event pipeline to a topic 408 Amazon Simple Notification Service Developer Guide i. j. k. l. (Optional) For StreamBufferingIntervalInSeconds and StreamBufferingSizeInMBs, enter the values for configuring the buffering of incoming events. If you don't enter any values, 300 seconds and 5 MB are used. (Optional) Enter one of the following StreamCompressionFormat settings for compressing incoming events: • GZIP • SNAPPY • UNCOMPRESSED (default) • ZIP (Optional) For StreamPrefix, enter the string prefix to name files stored in the Amazon S3 dead-letter bucket. If you don't enter a value, no prefix is used. (Optional) For StreamRetryDurationInSecons, enter the retry duration for cases when Firehose can't index events in the OpenSearch Service index. If you don't enter a value, then 300 seconds is used. m. (Optional) For SubscriptionFilterPolicy, enter the Amazon SNS subscription filter policy, in JSON format, to be used for filtering incoming events. The filter policy decides which events are indexed in the OpenSearch Service index. If you don't enter a value, no filtering is used (all events are indexed). n. Choose I acknowledge that this app creates custom IAM roles, resource policies and deploys nested applications. and then choose Deploy. On the Deployment status for my-app-search page, Lambda displays the Your application is being deployed status. In the Resources section, AWS CloudFormation begins to create the stack and displays the CREATE_IN_PROGRESS status for each resource. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. When the deployment is complete, Lambda displays the Your application has been deployed status. Messages published to your Amazon SNS topic are indexed in the OpenSearch Service index provisioned by the Event Search and Analytics pipeline automatically. If the pipeline can't index an event, it stores it in a Amazon S3 dead-letter bucket. Subscribing an event pipeline to a topic 409 Amazon Simple Notification Service Developer Guide Deploying the Event Replay Pipeline with Amazon SNS integration This page shows how to deploy the Event Replay Pipeline and subscribe it to an Amazon SNS topic. This process automatically turns the AWS SAM template associated with the pipeline into an AWS CloudFormation stack, and then deploys the stack into your AWS account. This process also creates and configures the set of resources that comprise the Event Replay Pipeline, including an Amazon SQS queue and a Lambda function. For more information about filtering events, see Amazon SNS subscription filter policies in this guide. 1. Sign in to the AWS Lambda console. 2. On the navigation panel, choose Functions and then choose Create function. 3. On the Create function page, do the following: a. Choose Browse serverless app repository, Public applications, Show apps that create custom IAM roles or resource policies. b. Search for fork-event-replay-pipeline and then choose the application. 4. On the fork-event-replay-pipeline page, do the following: a. In the Application settings section, enter an Application name (for example, my-app- replay). Note For each deployment, the application name must be unique. If you reuse an application name, the deployment will update only the previously deployed AWS CloudFormation
|
sns-dg-114
|
sns-dg.pdf
| 114 |
the AWS Lambda console. 2. On the navigation panel, choose Functions and then choose Create function. 3. On the Create function page, do the following: a. Choose Browse serverless app repository, Public applications, Show apps that create custom IAM roles or resource policies. b. Search for fork-event-replay-pipeline and then choose the application. 4. On the fork-event-replay-pipeline page, do the following: a. In the Application settings section, enter an Application name (for example, my-app- replay). Note For each deployment, the application name must be unique. If you reuse an application name, the deployment will update only the previously deployed AWS CloudFormation stack (rather than create a new one). b. (Optional) Enter one of the following LogLevel settings for the execution of your application's Lambda function: • DEBUG • ERROR • INFO (default) • WARNING Subscribing an event pipeline to a topic 410 Amazon Simple Notification Service Developer Guide c. d. e. f. (Optional) For ReplayQueueRetentionPeriodInSeconds, enter the amount of time, in seconds, for which the Amazon SQS replay queue keeps the message. If you don't enter a value, 1,209,600 seconds (14 days) is used. For TopicArn, enter the ARN of the Amazon SNS topic to which this instance of the fork pipeline is to be subscribed. For DestinationQueueName, enter the name of the Amazon SQS queue to which the Lambda replay function forwards messages. (Optional) For SubscriptionFilterPolicy, enter the Amazon SNS subscription filter policy, in JSON format, to be used for filtering incoming events. The filter policy decides which events are buffered for replay. If you don't enter a value, no filtering is used (all events are buffered for replay). g. Choose I acknowledge that this app creates custom IAM roles, resource policies and deploys nested applications. and then choose Deploy. On the Deployment status for my-app-replay page, Lambda displays the Your application is being deployed status. In the Resources section, AWS CloudFormation begins to create the stack and displays the CREATE_IN_PROGRESS status for each resource. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. When the deployment is complete, Lambda displays the Your application has been deployed status. Messages published to your Amazon SNS topic are buffered for replay in the Amazon SQS queue provisioned by the Event Replay Pipeline automatically. Note By default, replay is disabled. To enable replay, navigate to the function's page on the Lambda console, expand the Designer section, choose the SQS tile and then, in the SQS section, choose Enabled. Subscribing an event pipeline to a topic 411 Amazon Simple Notification Service Developer Guide Using Amazon EventBridge Scheduler with Amazon SNS Amazon EventBridge Scheduler is a serverless scheduler that allows you to create, run, and manage tasks from one central, managed service. With EventBridge Scheduler, you can create schedules using Cron and rate expressions for recurring patterns, or configure one-time invocations. You can set up flexible time windows for delivery, define retry limits, and set the maximum retention time for failed API invocations. This page explains how to use EventBridge Scheduler to publish a message from an Amazon SNS topic on a schedule. Setting-up the execution role When you create a new schedule, EventBridge Scheduler must have permission to invoke its target API operation on your behalf. You grant these permissions to EventBridge Scheduler using an execution role. The permission policy you attach to your schedule's execution role defines the required permissions. These permissions depend on the target API you want EventBridge Scheduler to invoke. When you use the EventBridge Scheduler console to create a schedule, as in the following procedure, EventBridge Scheduler automatically sets up an execution role based on your selected target. If you want to create a schedule using one of the EventBridge Scheduler SDKs, the AWS CLI, or AWS CloudFormation, you must have an existing execution role that grants the permissions EventBridge Scheduler requires to invoke a target. For more information about manually setting- up an execution role for your schedule, see Setting-up an execution role in the EventBridge Scheduler User Guide. Create a schedule To create a schedule by using the console 1. Open the Amazon EventBridge Scheduler console at https://console.aws.amazon.com/ scheduler/home. 2. On the Schedules page, choose Create schedule. 3. On the Specify schedule detail page, in the Schedule name and description section, do the following: a. For Schedule name, enter a name for your schedule. For example, MyTestSchedule. Using EventBridge Scheduler 412 Amazon Simple Notification Service Developer Guide b. c. (Optional) For Description, enter a description for your schedule. For example, My first schedule. For Schedule group, choose a schedule group from the dropdown list. If you don't have a group, choose default. To create a schedule group, choose create your own schedule. You use schedule groups to add tags to groups of schedules. 4. • Choose your schedule options. Occurrence Do this... One-time schedule For
|
sns-dg-115
|
sns-dg.pdf
| 115 |
the Schedule name and description section, do the following: a. For Schedule name, enter a name for your schedule. For example, MyTestSchedule. Using EventBridge Scheduler 412 Amazon Simple Notification Service Developer Guide b. c. (Optional) For Description, enter a description for your schedule. For example, My first schedule. For Schedule group, choose a schedule group from the dropdown list. If you don't have a group, choose default. To create a schedule group, choose create your own schedule. You use schedule groups to add tags to groups of schedules. 4. • Choose your schedule options. Occurrence Do this... One-time schedule For Date and time, do the following: A one-time schedule invokes a target only once • Enter a valid date in at the date and time that YYYY/MM/DD format. you specify. Recurring schedule A recurring schedule invokes a target at a rate that you specify using a cron expression or rate expression. • Enter a timestamp in 24- hour hh:mm format. • For Timezone, choose the timezone. a. For Schedule type, do one of the following: • To use a cron expression to define the schedule, choose Cron-based schedule and enter the cron expression. • To use a rate expression to define the schedule, choose Rate-based schedule and enter the rate expression. Create a schedule 413 Amazon Simple Notification Service Developer Guide Occurrence Do this... For more informati on about cron and rate expressions, see Schedule types on EventBridge Scheduler in the Amazon EventBridge Scheduler User Guide. b. For Flexible time window, choose Off to turn off the option, or choose one of the pre- defined time windows. For example, if you choose 15 minutes and you set a recurring schedule to invoke its target once every hour, the schedule runs within 15 minutes after the start of every hour. 5. (Optional) If you chose Recurring schedule in the previous step, in the Timeframe section, do the following: a. b. c. For Timezone, choose a timezone. For Start date and time, enter a valid date in YYYY/MM/DD format, and then specify a timestamp in 24-hour hh:mm format. For End date and time, enter a valid date in YYYY/MM/DD format, and then specify a timestamp in 24-hour hh:mm format. 6. Choose Next. 7. On the Select target page, choose the AWS API operation that EventBridge Scheduler invokes: a. Choose Amazon SNS Publish. Create a schedule 414 Amazon Simple Notification Service Developer Guide b. c. In the Publish section, select an SNS topic or choose Create new SNS topic. (Optional) Enter a JSON payload. If you don't enter a payload, EventBridge Scheduler uses an empty event to invoke the function. 8. Choose Next. 9. On the Settings page, do the following: a. b. To turn on the schedule, under Schedule state, toggle Enable schedule. To configure a retry policy for your schedule, under Retry policy and dead-letter queue (DLQ), do the following: • Toggle Retry. • For Maximum age of event, enter the maximum hour(s) and min(s) that EventBridge Scheduler must keep an unprocessed event. • The maximum time is 24 hours. • For Maximum retries, enter the maximum number of times EventBridge Scheduler retries the schedule if the target returns an error. The maximum value is 185 retries. With retry policies, if a schedule fails to invoke its target, EventBridge Scheduler re-runs the schedule. If configured, you must set the maximum retention time and retries for the schedule. c. Choose where EventBridge Scheduler stores undelivered events. Dead-letter queue (DLQ) option Do this... Don't store Choose None. Store the event in the same AWS account where you're creating the schedule a. Choose Select an Amazon SQS queue in my AWS account as a DLQ. Create a schedule 415 Amazon Simple Notification Service Developer Guide Dead-letter queue (DLQ) option Do this... b. Choose the Amazon Resource Name (ARN) of the Amazon SQS queue. Store the event in a different AWS account from where you're creating the schedule a. Choose Specify an Amazon SQS queue in other AWS accounts as a DLQ. b. Enter the Amazon Resource Name (ARN) of the Amazon SQS queue. d. To use a customer managed key to encrypt your target input, under Encryption, choose Customize encryption settings (advanced). If you choose this option, enter an existing KMS key ARN or choose Create an AWS KMS key to navigate to the AWS KMS console. For more information about how EventBridge Scheduler encrypts your data at rest, see Encryption at rest in the Amazon EventBridge Scheduler User Guide. e. To have EventBridge Scheduler create a new execution role for you, choose Create new role for this schedule. Then, enter a name for Role name. If you choose this option, EventBridge Scheduler attaches the required permissions necessary for your templated target to the role. 10. Choose Next. 11. In the Review and create
|
sns-dg-116
|
sns-dg.pdf
| 116 |
choose this option, enter an existing KMS key ARN or choose Create an AWS KMS key to navigate to the AWS KMS console. For more information about how EventBridge Scheduler encrypts your data at rest, see Encryption at rest in the Amazon EventBridge Scheduler User Guide. e. To have EventBridge Scheduler create a new execution role for you, choose Create new role for this schedule. Then, enter a name for Role name. If you choose this option, EventBridge Scheduler attaches the required permissions necessary for your templated target to the role. 10. Choose Next. 11. In the Review and create schedule page, review the details of your schedule. In each section, choose Edit to go back to that step and edit its details. 12. Choose Create schedule. You can view a list of your new and existing schedules on the Schedules page. Under the Status column, verify that your new schedule is Enabled. Related resources For more information about EventBridge Scheduler, see the following: Related resources 416 Amazon Simple Notification Service Developer Guide • EventBridge Scheduler User Guide • EventBridge Scheduler API Reference • EventBridge Scheduler Pricing Related resources 417 Amazon Simple Notification Service Developer Guide Using Amazon SNS for application-to-person messaging Amazon SNS application-to-person (A2P) messaging lets you to deliver notifications and alerts directly to your customers' mobile devices through SMS (Short Message Service). Using this feature, you can send push notifications to mobile apps, text messages to mobile phone numbers, and plain-text emails to email addresses. Additionally, you have the flexibility to distribute messages by using topics to reach multiple recipients, or publish messages directly to individual mobile endpoints for personalized communication. This topic explains how to use Amazon SNS for user notifications with subscribers such as mobile applications, mobile phone numbers, and email addresses. Mobile text messaging with Amazon SNS Important The Amazon SNS SMS Developer Guide has been updated. Amazon SNS has integrated with AWS End User Messaging SMS for the delivery of SMS messages. This guide contains the latest information on how to create, configure, and manage your Amazon SNS SMS messages. Amazon SNS mobile text messaging (SMS) is designed to facilitate message delivery to various platforms, such as web, mobile, and business applications that support SMS. Users can send messages to one or multiple phone numbers by subscribing them to a topic, simplifying the distribution process. Mobile text messaging 418 Amazon Simple Notification Service Developer Guide Amazon SNS messages are delivered by AWS End User Messaging SMS, which ensures reliable message transmission. Within Amazon SNS APIs, you can set various properties such as message types (promotional or transactional), monthly spending limits, opt-out lists, and message delivery optimization. AWS End User Messaging SMS handles the transmission of messages to the destination phone number through its global SMS supply network. It manages the routing, delivery status, and any required compliance with regional regulations. To access additional SMS features such as granular permissions, phone pools, configurations sets, SMS simulator, and country rule, see the AWS End User Messaging SMS User Guide. The following key features help you send Amazon SNS SMS messages that are scalable and easily extensible: Customize message preferences Customize SMS deliveries for your AWS account by setting up SMS preferences based on your budget and use case. For example, you can choose whether your messages prioritize cost efficiency or reliable delivery. Set spending quotas Tailor your SMS deliveries by specifying spending quotas or for individual message deliveries and monthly spending quotas for your AWS account. Where required by local laws and regulations (such as the US and Canada), SMS recipients can opt-out, which means that they choose to stop receiving SMS messages from your AWS account. After a recipient opts-out of receiving messages, you can, with limitations, opt-in the phone number again so that you can resume sending messages. Mobile text messaging 419 Amazon Simple Notification Service Send SMS messages globally Developer Guide Amazon SNS supports SMS messaging in multiple regions, allowing you to send messages to over 240 countries and regions. How does Amazon SNS deliver my SMS messages? When you request Amazon SNS to send SMS on your behalf, the messages are dispatched using AWS End User Messaging SMS. The integration between Amazon SNS and AWS End User Messaging SMS offers the following benefits: IAM policies You can leverage IAM and resource policies to control and distribute access to your SMS resources across other AWS services and regions. AWS End User Messaging SMS configurations All origination ID related configurations (creation, configuration updating, provisioning new origination IDs, changing registration templates) use AWS End User Messaging SMS. AWS End User Messaging SMS billing All SMS billing is done though AWS End User Messaging SMS. You can consolidate your AWS spend for your SMS workloads, while procuring and managing your SMS resources in one central
|
sns-dg-117
|
sns-dg.pdf
| 117 |
Amazon SNS and AWS End User Messaging SMS offers the following benefits: IAM policies You can leverage IAM and resource policies to control and distribute access to your SMS resources across other AWS services and regions. AWS End User Messaging SMS configurations All origination ID related configurations (creation, configuration updating, provisioning new origination IDs, changing registration templates) use AWS End User Messaging SMS. AWS End User Messaging SMS billing All SMS billing is done though AWS End User Messaging SMS. You can consolidate your AWS spend for your SMS workloads, while procuring and managing your SMS resources in one central location. Getting started with Amazon SNS SMS Important The Amazon SNS SMS Developer Guide has been updated. Amazon SNS has integrated with AWS End User Messaging SMS for the delivery of SMS messages. This guide contains the latest information on how to create, configure, and manage your Amazon SNS SMS messages. This topic guides you through managing your SMS sandbox and configuring IAM and resource- based policies to grant Amazon SNS the necessary permissions for accessing and utilizing the AWS End User Messaging SMS APIs. How does Amazon SNS deliver my SMS messages? 420 Amazon Simple Notification Service Prerequisites Developer Guide Amazon SNS recommends updating your IAM policy to include the following actions to ensure comprehensive control and visibility over your Amazon SNS resources: • AmazonSNSFullAccess • AmazonSNSReadOnly Using the Amazon SNS SMS sandbox Newly created Amazon SNS SMS accounts are automatically placed into the SMS sandbox to ensure the security of both AWS customers and recipients by mitigating the risk of fraud and abuse. This environment serves as a secure space for testing and development purposes. While operating within the SMS sandbox, you have access to all Amazon SNS features but are subject to certain limitations: • You can only send SMS messages to verified destination phone numbers. • You can have up to 10 verified destination phone numbers. • You can delete destination phone numbers only after a minimum of 24 hours have passed since verification, or the last verification attempt. Once your account transitions out of the sandbox, these restrictions are removed, and you can send SMS messages to any recipient. First steps New Amazon SNS SMS accounts are placed into an SMS sandbox. Use the following steps to create and manage phone numbers in your sandbox, create origination numbers and sender IDs, and register your company. 1. Add a destination phone number to the SMS sandbox. For details on adding, managing and moving phone numbers out of the Amazon SNS SMS sandbox, see Adding and verifying phone numbers in the Amazon SNS SMS sandbox. 2. Create an origination identity that your recipients see on their devices when you send them an SMS message. To learn more about origination identities, including the different types you can use, see the Origination identities for Amazon SNS SMS messages documentation. Getting started 421 Amazon Simple Notification Service Developer Guide 3. Register your company. Some countries require you to register your company's identity to be able to purchase phone numbers or sender IDs and review the messages you send to recipients in their country. For information on which countries require registration, see Supported countries and regions for SMS messaging with AWS End User Messaging SMS in the AWS End User Messaging SMS User Guide. 4. Send your messages to a topic or mobile phone. For more information, see Sending SMS messages using Amazon SNS. Adding and verifying phone numbers in the Amazon SNS SMS sandbox Before you can start sending SMS messages from your AWS account while in the SMS sandbox, you must complete the following setup steps. This ensures that your account is ready for SMS messaging and that your destination phone numbers are properly verified. 1. Create an origination ID. Similar to accounts outside of the SMS sandbox, an origination ID is necessary before you can send SMS messages to recipients in some countries or regions. 2. Add the destination phone numbers you want to send messages to within the SMS sandbox. 3. Verify the phone numbers to ensure that the destination phone numbers are valid for use in your SMS messages. Add and verify destination phone numbers 1. 2. 3. 4. Sign in to the Amazon SNS console. In the console menu, choose a region that supports SMS messaging. In the navigation pane, choose Text messaging (SMS). In the Sandbox destination phone numbers section, select Add phone number. 5. Under Destination details, provide the following information, and then select Add phone number: • Country code and phone number of the destination. • The language you want the verification message to be sent in. 6. After adding the phone number, Amazon SNS will send an OTP to the provided destination phone number. This OTP is required for verification. 7.
|
sns-dg-118
|
sns-dg.pdf
| 118 |
2. 3. 4. Sign in to the Amazon SNS console. In the console menu, choose a region that supports SMS messaging. In the navigation pane, choose Text messaging (SMS). In the Sandbox destination phone numbers section, select Add phone number. 5. Under Destination details, provide the following information, and then select Add phone number: • Country code and phone number of the destination. • The language you want the verification message to be sent in. 6. After adding the phone number, Amazon SNS will send an OTP to the provided destination phone number. This OTP is required for verification. 7. You will receive the OTP as a standard SMS message on the destination phone number you provided. Getting started 422 Amazon Simple Notification Service Developer Guide • If you don’t receive the OTP within 15 minutes, select Resend verification code in the Amazon SNS console. • You can resend the OTP up to five times in a 24-hour period. 8. Once you receive the OTP, enter it in the Verification code box and select Verify phone number. 9. Check the verification status. • After successfully verifying the phone number, the phone number and its verification status will appear in the Sandbox destination phone numbers section. • If the status is Pending, the verification was unsuccessful. This may happen if, for example, you didn’t enter the country code correctly. • You can only delete pending or verified phone numbers after 24 hours or more have passed since the last verification attempt. 10. If you wish to use the same destination phone number in other regions, repeat the previous steps for each region where you intend to use it. Troubleshooting non-receipt of an OTP text Troubleshoot common problems that may prevent a phone number from receiving OTP texts. • Amazon SNS SMS spending limit: If your AWS account has exceeded the spending limit for sending SMS messages, further messages, including OTP texts, might not be delivered until the limit is increased or the billing issue is resolved. • Phone number not opted in for SMS notifications: In some countries or regions, recipients must opt in to receive SMS messages from short codes, which are commonly used for OTP texts. If the recipient's phone number is not opted in, they will not receive the OTP text. • Carrier restrictions or filtering: Some mobile carriers may have restrictions or filtering mechanisms in place that prevent delivery of certain types of SMS messages, including OTP texts. This could be due to security policies or anti-spam measures implemented by the carrier. • Invalid or incorrect phone number: If the phone number provided by the recipient is incorrect or invalid, the OTP text will not be delivered. • Network issues: Temporary network issues or outages could prevent the delivery of SMS messages, including OTP texts, to the recipient's phone. Getting started 423 Amazon Simple Notification Service Developer Guide • Delayed delivery: In some cases, SMS messages may experience delays in delivery due to network congestion or other factors. The OTP text may eventually be delivered, but it could be delayed beyond the expected timeframe. • Account suspension or termination: If there are issues with your AWS account, such as non- payment or violation of AWS terms of service, Amazon SNS messaging capabilities, including OTP texts, may be suspended or terminated. Deleting phone numbers from the Amazon SNS SMS sandbox You can delete both pending and verified destination phone numbers from the SMS sandbox. Important You can only delete a phone number 24 hours after verifying the phone number, or 24 hours after your last verification attempt. To delete destination phone numbers from the SMS sandbox 1. 2. Sign in to the Amazon SNS console. In the console menu, choose a region that supports SMS messaging where you added a destination phone number. 3. In the navigation pane, select Text messaging (SMS). 4. On the Mobile text messaging (SMS) page, navigate to the Sandbox destination phone numbers section. 5. Choose the specific phone number you want to delete, and then choose Delete phone number. 6. To confirm that you want to delete the phone number, enter delete me, and then choose Delete. Ensure that 24 hours or more have passed since you verified or attempted to verify the destination phone number before proceeding with the deletion. 7. Repeat these steps in each Region where you added the destination phone number and no longer plan to use it. Getting started 424 Amazon Simple Notification Service Developer Guide Moving out of the Amazon SNS SMS sandbox Moving your AWS account out of the SMS sandbox requires that you first add, verify, and test destination phone numbers. After doing this, create a case with AWS Support. To request that your AWS account is moved out of the SMS sandbox 1. Verify
|
sns-dg-119
|
sns-dg.pdf
| 119 |
have passed since you verified or attempted to verify the destination phone number before proceeding with the deletion. 7. Repeat these steps in each Region where you added the destination phone number and no longer plan to use it. Getting started 424 Amazon Simple Notification Service Developer Guide Moving out of the Amazon SNS SMS sandbox Moving your AWS account out of the SMS sandbox requires that you first add, verify, and test destination phone numbers. After doing this, create a case with AWS Support. To request that your AWS account is moved out of the SMS sandbox 1. Verify phone numbers a. While your AWS account is in the SMS sandbox, open the Amazon SNS console. b. c. In the navigation pane, under Mobile, choose Text messaging (SMS). In the Sandbox destination phone numbers section, add and verify one or more destination phone numbers. This verification ensures you can successfully send and receive messages. 2. Test SMS publishing • Confirm that you are able to send and receive messages to at least one verified phone number. For more detailed instructions on how to publish SMS messages, see Publishing SMS messages to a mobile phone using Amazon SNS. 3. Initiate sandbox edit • On the Amazon SNS console's Mobile text messaging (SMS) page, under Account information, choose Exit SMS sandbox. This action redirects you to the Amazon Support Center and automatically creates a support case with the Service quota increase option selected. 4. Fill out the form • In the support form under Service quota increase, do the following: i. ii. Choose choose SNS Text Messaging as the service. Provide the website URL or app name from which you intend to send SMS messages. iii. Specify the type of messages you will send: One Time Password, Promotional, or Transactional. iv. Choose the AWS Region from which you will send SMS messages. v. List the countries or regions where you plan to send SMS messages. vi. Describe how your customers opt-in to receive messages. vii. Include any message templates you intend to use. Getting started 425 Amazon Simple Notification Service 5. Specify quota and Region • Under Requests, do the following: Developer Guide i. ii. Choose the AWS Region where you want to move your AWS account. Choose General Limits for Resource Type. iii. Choose Exit SMS Sandbox for Quota. iv. (Optional) To request additional increases or other adjustments, choose Add another request and specify the necessary details. v. For New quota value, enter the limit in USD you are requesting. 6. Additional details a. In the Case description, provide any additional details relevant to your request. b. Under Contact options, choose your preferred contact language. 7. Submit the request • Choose Submit to send your request to Support. The Support team provides an initial response to your request within 24 hours. To prevent our systems from being used to send unsolicited or malicious content, we consider each request carefully. If we can, we will grant your request within this 24-hour period. However, if we need additional information from you, it might take longer to resolve your request. If your use case doesn't align with our policies, we might be unable to grant your request. Origination identities for Amazon SNS SMS messages Important The Amazon SNS SMS Developer Guide has been updated. Amazon SNS has integrated with AWS End User Messaging SMS for the delivery of SMS messages. This guide contains the latest information on how to create, configure, and manage your Amazon SNS SMS messages. Origination identities 426 Amazon Simple Notification Service Developer Guide Origination identities for SMS messages are identifiers used to represent the sender of an SMS message. You can identify yourself to your recipients using the following types of originating identities: Origination numbers A numeric string that identifies an SMS message sender's phone number. There are several types of origination numbers, including long codes (standard phone numbers that typically have 10 or more digits), 10 digit long codes (10DLC), toll free numbers (TFN) and short codes (phone numbers that contain between four and seven digits). Support for origination numbers is not available in countries where local laws require the use of sender IDs instead of origination numbers. When you send an SMS message using an origination number, the recipient's device shows the origination number as the sender's phone number. You can specify different origination numbers by use case. For additional information, see Phone numbers in the AWS End User Messaging SMS User Guide. Tip To view a list of all existing origination numbers in your AWS account, in the navigation pane of the Amazon SNS console, choose Origination numbers. Sender IDs An alphabetic name that identifies the sender of an SMS message. When you send an SMS message using a sender ID, and the recipient is in
|
sns-dg-120
|
sns-dg.pdf
| 120 |
When you send an SMS message using an origination number, the recipient's device shows the origination number as the sender's phone number. You can specify different origination numbers by use case. For additional information, see Phone numbers in the AWS End User Messaging SMS User Guide. Tip To view a list of all existing origination numbers in your AWS account, in the navigation pane of the Amazon SNS console, choose Origination numbers. Sender IDs An alphabetic name that identifies the sender of an SMS message. When you send an SMS message using a sender ID, and the recipient is in an area where sender ID authentication is supported, your sender ID appears on the recipient’s device instead of your phone number. A sender ID provides SMS recipients with more information about the sender than a phone number, long code, or short code provides. Sender IDs are supported in several countries and regions around the world. In some places, if you're a business that sends SMS messages to individual customers, you must use a sender ID that's pre-registered with a regulatory agency or industry group. For a complete list of countries and regions that support or require sender IDs, see Supported countries and regions for SMS messaging with AWS End User Messaging SMS in the AWS End User Messaging SMS User Guide. There's no additional charge for using sender IDs. However, support and requirements for sender ID authentication varies by country. Several major markets (including Canada, China, Origination identities 427 Amazon Simple Notification Service Developer Guide and the United States) don't support using sender IDs. Some areas require that companies who send SMS messages to individual customers must use a sender ID that's pre-registered with a regulatory agency or industry group. For additional information, see Sender IDs in the AWS End User Messaging SMS User Guide. Configuring SMS messaging in Amazon SNS Important The Amazon SNS SMS Developer Guide has been updated. Amazon SNS has integrated with AWS End User Messaging SMS for the delivery of SMS messages. This guide contains the latest information on how to create, configure, and manage your Amazon SNS SMS messages. You can use the configurations in Amazon SNS SMS to set SMS preferences to suit your requirements, such as adjusting spending quotas and setting-up delivery status logging. This topic also provides details on how to publish SMS messages to topics using the Amazon SNS console and AWS SDK, efficiently handle quotas, and retrieve detailed statistics on SMS activity. Sending SMS messages using Amazon SNS This section describes how to send SMS messages using Amazon SNS, including publishing to a topic, subscribing phone numbers to topics, setting attributes on messages, and publishing directly to mobile phones. Publishing SMS messages to an Amazon SNS topic You can publish a single SMS message to many phone numbers at once by subscribing those phone numbers to an Amazon SNS topic. An SNS topic is a communication channel to which you can add subscribers and then publish messages to all of those subscribers. A subscriber receives all messages published to the topic until you cancel the subscription, or until the subscriber opts out of receiving SMS messages from your AWS account. Configurations 428 Amazon Simple Notification Service Developer Guide Sending a message to a topic using the AWS console To create a topic Complete the following steps if you don't already have a topic to which you want to send SMS messages. 1. 2. 3. Sign in to the Amazon SNS console. In the console menu, choose a region that supports SMS messaging. In the navigation pane, choose Topics. 4. On the Topics page, choose Create topic. 5. On the Create topic page, under Details, do the following: a. b. c. For Type, choose Standard. For Name, enter a topic name. (Optional) For Display name, enter a custom prefix for your SMS messages. When you send a message to the topic, Amazon SNS prepends the display name followed by a right angle bracket (>) and a space. Display names are not case sensitive, and Amazon SNS converts display names to uppercase characters. For example, if the display name of a topic is MyTopic and the message is Hello World!, the message appears as: MYTOPIC> Hello World! 6. Choose Create topic. The topic's name and Amazon Resource Name (ARN) appear on the Topics page. To create an SMS subscription You can use subscriptions to send an SMS message to multiple recipients by publishing the message only once to your topic. Note When you start using Amazon SNS to send SMS messages, your AWS account is in the SMS sandbox. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your account is in the SMS sandbox, you can
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.