id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
sns-dg-221
sns-dg.pdf
221
"serious", "sincere" }; public static SNSWrapper SnsWrapper { get; set; } = null!; public static SQSWrapper SqsWrapper { get; set; } = null!; public static bool UseConsole { get; set; } = true; static async Task Main(string[] args) { // Set up dependency injection for Amazon EventBridge. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonSQS>() .AddAWSService<IAmazonSimpleNotificationService>() Publish messages to queues 854 Amazon Simple Notification Service Developer Guide .AddTransient<SNSWrapper>() .AddTransient<SQSWrapper>() ) .Build(); ServicesSetup(host); PrintDescription(); await RunScenario(); } /// <summary> /// Populate the services for use within the console application. /// </summary> /// <param name="host">The services host.</param> private static void ServicesSetup(IHost host) { SnsWrapper = host.Services.GetRequiredService<SNSWrapper>(); SqsWrapper = host.Services.GetRequiredService<SQSWrapper>(); } /// <summary> /// Run the scenario for working with topics and queues. /// </summary> /// <returns>True if successful.</returns> public static async Task<bool> RunScenario() { try { await SetupTopic(); await SetupQueues(); await PublishMessages(); foreach (var queueUrl in _queueUrls) { var messages = await PollForMessages(queueUrl); if (messages.Any()) { await DeleteMessages(queueUrl, messages); } } Publish messages to queues 855 Amazon Simple Notification Service Developer Guide await CleanupResources(); Console.WriteLine("Messaging with topics and queues scenario is complete."); return true; } catch (Exception ex) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"There was a problem running the scenario: {ex.Message}"); await CleanupResources(); Console.WriteLine(new string('-', 80)); return false; } } /// <summary> /// Print a description for the tasks in the scenario. /// </summary> /// <returns>Async task.</returns> private static void PrintDescription() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Welcome to messaging with topics and queues."); Console.WriteLine(new string('-', 80)); Console.WriteLine($"In this scenario, you will create an SNS topic and subscribe {_queueCount} SQS queues to the topic." + $"\r\nYou can select from several options for configuring the topic and the subscriptions for the 2 queues." + $"\r\nYou can then post to the topic and see the results in the queues.\r\n"); Console.WriteLine(new string('-', 80)); } /// <summary> /// Set up the SNS topic to be used with the queues. /// </summary> /// <returns>Async task.</returns> private static async Task<string> SetupTopic() { Console.WriteLine(new string('-', 80)); Publish messages to queues 856 Amazon Simple Notification Service Developer Guide Console.WriteLine($"SNS topics can be configured as FIFO (First-In-First- Out)." + $"\r\nFIFO topics deliver messages in order and support deduplication and message filtering." + $"\r\nYou can then post to the topic and see the results in the queues.\r\n"); _useFifoTopic = GetYesNoResponse("Would you like to work with FIFO topics?"); if (_useFifoTopic) { Console.WriteLine(new string('-', 80)); _topicName = GetUserResponse("Enter a name for your SNS topic: ", "example-topic"); Console.WriteLine( "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.\r\n"); Console.WriteLine(new string('-', 80)); Console.WriteLine($"Because you have chosen a FIFO topic, deduplication is supported." + $"\r\nDeduplication IDs are either set in the message or automatically generated " + $"\r\nfrom content using a hash function.\r\n" + $"\r\nIf a message is successfully published to an SNS FIFO topic, any message " + $"\r\npublished and determined to have the same deduplication ID, " + $"\r\nwithin the five-minute deduplication interval, is accepted but not delivered.\r\n" + $"\r\nFor more information about deduplication, " + $"\r\nsee https://docs.aws.amazon.com/sns/latest/ dg/fifo-message-dedup.html."); _useContentBasedDeduplication = GetYesNoResponse("Use content-based deduplication instead of entering a deduplication ID?"); Console.WriteLine(new string('-', 80)); } _topicArn = await SnsWrapper.CreateTopicWithName(_topicName, _useFifoTopic, _useContentBasedDeduplication); Console.WriteLine($"Your new topic with the name {_topicName}" + Publish messages to queues 857 Amazon Simple Notification Service Developer Guide $"\r\nand Amazon Resource Name (ARN) {_topicArn}" + $"\r\nhas been created.\r\n"); Console.WriteLine(new string('-', 80)); return _topicArn; } /// <summary> /// Set up the queues. /// </summary> /// <returns>Async task.</returns> private static async Task SetupQueues() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Now you will create {_queueCount} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic."); // Repeat this section for each queue. for (int i = 0; i < _queueCount; i++) { var queueName = GetUserResponse("Enter a name for an Amazon SQS queue: ", $"example-queue-{i}"); if (_useFifoTopic) { // Only explain this once. if (i == 0) { Console.WriteLine( "Because you have selected a FIFO topic, '.fifo' must be appended to the queue name."); } var queueUrl = await SqsWrapper.CreateQueueWithName(queueName, _useFifoTopic); _queueUrls[i] = queueUrl; Console.WriteLine($"Your new queue with the name {queueName}" + $"\r\nand queue URL {queueUrl}" + $"\r\nhas been created.\r\n"); if (i == 0) { Console.WriteLine( Publish messages to queues 858 Amazon Simple Notification Service Developer Guide $"The queue URL is used to retrieve the queue ARN,\r\n" + $"which is used to create a subscription."); Console.WriteLine(new string('-', 80)); } var queueArn = await SqsWrapper.GetQueueArnByUrl(queueUrl); if (i == 0) { Console.WriteLine( $"An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue, enabling it to receive\r\n" + $"messages from an SNS topic"); } await SqsWrapper.SetQueuePolicyForTopic(queueArn, _topicArn, queueUrl); await SetupFilters(i, queueArn, queueName); } } Console.WriteLine(new string('-', 80)); } /// <summary> /// Set up filters with user options for a queue. /// </summary> /// <param name="queueCount">The number of this queue.</param> /// <param name="queueArn">The ARN of
sns-dg-222
sns-dg.pdf
222
Guide $"The queue URL is used to retrieve the queue ARN,\r\n" + $"which is used to create a subscription."); Console.WriteLine(new string('-', 80)); } var queueArn = await SqsWrapper.GetQueueArnByUrl(queueUrl); if (i == 0) { Console.WriteLine( $"An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue, enabling it to receive\r\n" + $"messages from an SNS topic"); } await SqsWrapper.SetQueuePolicyForTopic(queueArn, _topicArn, queueUrl); await SetupFilters(i, queueArn, queueName); } } Console.WriteLine(new string('-', 80)); } /// <summary> /// Set up filters with user options for a queue. /// </summary> /// <param name="queueCount">The number of this queue.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <param name="queueName">The name of the queue.</param> /// <returns>Async Task.</returns> public static async Task SetupFilters(int queueCount, string queueArn, string queueName) { if (_useFifoTopic) { Console.WriteLine(new string('-', 80)); // Only explain this once. if (queueCount == 0) { Console.WriteLine( "Subscriptions to a FIFO topic can have filters." + Publish messages to queues 859 Amazon Simple Notification Service Developer Guide "If you add a filter to this subscription, then only the filtered messages " + "will be received in the queue."); Console.WriteLine( "For information about message filtering, " + "see https://docs.aws.amazon.com/sns/latest/dg/sns-message- filtering.html"); Console.WriteLine( "For this example, you can filter messages by a" + "TONE attribute."); } var useFilter = GetYesNoResponse($"Filter messages for {queueName}'s subscription to the topic?"); string? filterPolicy = null; if (useFilter) { filterPolicy = CreateFilterPolicy(); } var subscriptionArn = await SnsWrapper.SubscribeTopicWithFilter(_topicArn, filterPolicy, queueArn); _subscriptionArns[queueCount] = subscriptionArn; Console.WriteLine( $"The queue {queueName} has been subscribed to the topic {_topicName} " + $"with the subscription ARN {subscriptionArn}"); Console.WriteLine(new string('-', 80)); } } /// <summary> /// Use user input to create a filter policy for a subscription. /// </summary> /// <returns>The serialized filter policy.</returns> public static string CreateFilterPolicy() { Console.WriteLine(new string('-', 80)); Console.WriteLine( $"You can filter messages by one or more of the following" + Publish messages to queues 860 Amazon Simple Notification Service Developer Guide $"TONE attributes."); List<string> filterSelections = new List<string>(); var selectionNumber = 0; do { Console.WriteLine( $"Enter a number to add a TONE filter, or enter 0 to stop adding filters."); for (int i = 0; i < _tones.Length; i++) { Console.WriteLine($"\t{i + 1}. {_tones[i]}"); } var selection = GetUserResponse("", filterSelections.Any() ? "0" : "1"); int.TryParse(selection, out selectionNumber); if (selectionNumber > 0 && ! filterSelections.Contains(_tones[selectionNumber - 1])) { filterSelections.Add(_tones[selectionNumber - 1]); } } while (selectionNumber != 0); var filters = new Dictionary<string, List<string>> { { "tone", filterSelections } }; string filterPolicy = JsonSerializer.Serialize(filters); return filterPolicy; } /// <summary> /// Publish messages using user settings. /// </summary> /// <returns>Async task.</returns> public static async Task PublishMessages() { Console.WriteLine("Now we can publish messages."); var keepSendingMessages = true; string? deduplicationId = null; string? toneAttribute = null; Publish messages to queues 861 Amazon Simple Notification Service Developer Guide while (keepSendingMessages) { Console.WriteLine(); var message = GetUserResponse("Enter a message to publish.", "This is a sample message"); if (_useFifoTopic) { Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." + "\r\nAll messages within the same group will be received in the order " + "they were published."); Console.WriteLine(); var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1"); if (!_useContentBasedDeduplication) { Console.WriteLine("Because you are not using content-based deduplication, " + "you must enter a deduplication ID."); Console.WriteLine("Enter a deduplication ID for this message."); deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1"); } if (GetYesNoResponse("Add an attribute to this message?")) { Console.WriteLine("Enter a number for an attribute."); for (int i = 0; i < _tones.Length; i++) { Console.WriteLine($"\t{i + 1}. {_tones[i]}"); } var selection = GetUserResponse("", "1"); int.TryParse(selection, out var selectionNumber); if (selectionNumber > 0 && selectionNumber < _tones.Length) { toneAttribute = _tones[selectionNumber - 1]; Publish messages to queues 862 Amazon Simple Notification Service Developer Guide } } var messageID = await SnsWrapper.PublishToTopicWithAttribute( _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId); Console.WriteLine($"Message published with id {messageID}."); } keepSendingMessages = GetYesNoResponse("Send another message?", false); } } /// <summary> /// Poll for the published messages to see the results of the user's choices. /// </summary> /// <returns>Async task.</returns> public static async Task<List<Message>> PollForMessages(string queueUrl) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Now the SQS queue at {queueUrl} will be polled to retrieve the messages." + "\r\nPress any key to continue."); if (UseConsole) { Console.ReadLine(); } var moreMessages = true; var messages = new List<Message>(); while (moreMessages) { var newMessages = await SqsWrapper.ReceiveMessagesByUrl(queueUrl, 10); moreMessages = newMessages.Any(); if (moreMessages) { messages.AddRange(newMessages); } } Publish messages to queues 863 Amazon Simple Notification Service Developer Guide Console.WriteLine($"{messages.Count} message(s) were received by the queue at {queueUrl}."); foreach (var message in messages) { Console.WriteLine("\tMessage:" + $"\n\t{message.Body}"); } Console.WriteLine(new string('-', 80)); return messages; } /// <summary> /// Delete the message using handles in a batch. /// </summary> /// <returns>Async task.</returns> public static async Task DeleteMessages(string queueUrl, List<Message> messages) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Now we can delete the messages in this
sns-dg-223
sns-dg.pdf
223
} var moreMessages = true; var messages = new List<Message>(); while (moreMessages) { var newMessages = await SqsWrapper.ReceiveMessagesByUrl(queueUrl, 10); moreMessages = newMessages.Any(); if (moreMessages) { messages.AddRange(newMessages); } } Publish messages to queues 863 Amazon Simple Notification Service Developer Guide Console.WriteLine($"{messages.Count} message(s) were received by the queue at {queueUrl}."); foreach (var message in messages) { Console.WriteLine("\tMessage:" + $"\n\t{message.Body}"); } Console.WriteLine(new string('-', 80)); return messages; } /// <summary> /// Delete the message using handles in a batch. /// </summary> /// <returns>Async task.</returns> public static async Task DeleteMessages(string queueUrl, List<Message> messages) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Now we can delete the messages in this queue in a batch."); await SqsWrapper.DeleteMessageBatchByUrl(queueUrl, messages); Console.WriteLine(new string('-', 80)); } /// <summary> /// Clean up the resources from the scenario. /// </summary> /// <returns>Async task.</returns> private static async Task CleanupResources() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Clean up resources."); try { foreach (var queueUrl in _queueUrls) { if (!string.IsNullOrEmpty(queueUrl)) { var deleteQueue = GetYesNoResponse($"Delete queue with url {queueUrl}?"); Publish messages to queues 864 Amazon Simple Notification Service Developer Guide if (deleteQueue) { await SqsWrapper.DeleteQueueByUrl(queueUrl); } } } foreach (var subscriptionArn in _subscriptionArns) { if (!string.IsNullOrEmpty(subscriptionArn)) { await SnsWrapper.UnsubscribeByArn(subscriptionArn); } } var deleteTopic = GetYesNoResponse($"Delete topic {_topicName}?"); if (deleteTopic) { await SnsWrapper.DeleteTopicByArn(_topicArn); } } catch (Exception ex) { Console.WriteLine($"Unable to clean up resources. Here's why: {ex.Message}."); } Console.WriteLine(new string('-', 80)); } /// <summary> /// Helper method to get a yes or no response from the user. /// </summary> /// <param name="question">The question string to print on the console.</ param> /// <param name="defaultAnswer">Optional default answer to use.</param> /// <returns>True if the user responds with a yes.</returns> private static bool GetYesNoResponse(string question, bool defaultAnswer = true) { if (UseConsole) { Console.WriteLine(question); var ynResponse = Console.ReadLine(); Publish messages to queues 865 Amazon Simple Notification Service Developer Guide var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase); return response; } // If not using the console, use the default. return defaultAnswer; } /// <summary> /// Helper method to get a string response from the user through the console. /// </summary> /// <param name="question">The question string to print on the console.</ param> /// <param name="defaultAnswer">Optional default answer to use.</param> /// <returns>True if the user responds with a yes.</returns> private static string GetUserResponse(string question, string defaultAnswer) { if (UseConsole) { var response = ""; while (string.IsNullOrEmpty(response)) { Console.WriteLine(question); response = Console.ReadLine(); } return response; } // If not using the console, use the default. return defaultAnswer; } } Create a class that wraps Amazon SQS operations. /// <summary> /// Wrapper for Amazon Simple Queue Service (SQS) operations. /// </summary> public class SQSWrapper { private readonly IAmazonSQS _amazonSQSClient; Publish messages to queues 866 Amazon Simple Notification Service Developer Guide /// <summary> /// Constructor for the Amazon SQS wrapper. /// </summary> /// <param name="amazonSQS">The injected Amazon SQS client.</param> public SQSWrapper(IAmazonSQS amazonSQS) { _amazonSQSClient = amazonSQS; } /// <summary> /// Create a queue with a specific name. /// </summary> /// <param name="queueName">The name for the queue.</param> /// <param name="useFifoQueue">True to use a FIFO queue.</param> /// <returns>The url for the queue.</returns> public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue) { int maxMessage = 256 * 1024; var queueAttributes = new Dictionary<string, string> { { QueueAttributeName.MaximumMessageSize, maxMessage.ToString() } }; var createQueueRequest = new CreateQueueRequest() { QueueName = queueName, Attributes = queueAttributes }; if (useFifoQueue) { // Update the name if it is not correct for a FIFO queue. if (!queueName.EndsWith(".fifo")) { createQueueRequest.QueueName = queueName + ".fifo"; } // Add an attribute for a FIFO queue. createQueueRequest.Attributes.Add( Publish messages to queues 867 Amazon Simple Notification Service Developer Guide QueueAttributeName.FifoQueue, "true"); } var createResponse = await _amazonSQSClient.CreateQueueAsync( new CreateQueueRequest() { QueueName = queueName }); return createResponse.QueueUrl; } /// <summary> /// Get the ARN for a queue from its URL. /// </summary> /// <param name="queueUrl">The URL of the queue.</param> /// <returns>The ARN of the queue.</returns> public async Task<string> GetQueueArnByUrl(string queueUrl) { var getAttributesRequest = new GetQueueAttributesRequest() { QueueUrl = queueUrl, AttributeNames = new List<string>() { QueueAttributeName.QueueArn } }; var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync( getAttributesRequest); return getAttributesResponse.QueueARN; } /// <summary> /// Set the policy attribute of a queue for a topic. /// </summary> /// <param name="queueArn">The ARN of the queue.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="queueUrl">The url for the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl) { var queuePolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + Publish messages to queues 868 Amazon Simple Notification Service Developer Guide "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": " + "\"sns.amazonaws.com\"" + "}," + "\"Action\": \"sqs:SendMessage\"," + $"\"Resource\": \"{queueArn}\"," + "\"Condition\": {" + "\"ArnEquals\": {" + $"\"aws:SourceArn\": \"{topicArn}\"" + "}" + "}" + "}]" + "}"; var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync( new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } } }); return attributesResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Receive messages
sns-dg-224
sns-dg.pdf
224
public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl) { var queuePolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + Publish messages to queues 868 Amazon Simple Notification Service Developer Guide "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": " + "\"sns.amazonaws.com\"" + "}," + "\"Action\": \"sqs:SendMessage\"," + $"\"Resource\": \"{queueArn}\"," + "\"Condition\": {" + "\"ArnEquals\": {" + $"\"aws:SourceArn\": \"{topicArn}\"" + "}" + "}" + "}]" + "}"; var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync( new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } } }); return attributesResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> /// Receive messages from a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>The list of messages.</returns> public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages) { // Setting WaitTimeSeconds to non-zero enables long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html var messageResponse = await _amazonSQSClient.ReceiveMessageAsync( new ReceiveMessageRequest() { QueueUrl = queueUrl, MaxNumberOfMessages = maxMessages, WaitTimeSeconds = 1 }); Publish messages to queues 869 Amazon Simple Notification Service Developer Guide return messageResponse.Messages; } /// <summary> /// Delete a batch of messages from a queue by its url. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages) { var deleteRequest = new DeleteMessageBatchRequest() { QueueUrl = queueUrl, Entries = new List<DeleteMessageBatchRequestEntry>() }; foreach (var message in messages) { deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry() { ReceiptHandle = message.ReceiptHandle, Id = message.MessageId }); } var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest); return deleteResponse.Failed.Any(); } /// <summary> /// Delete a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteQueueByUrl(string queueUrl) { var deleteResponse = await _amazonSQSClient.DeleteQueueAsync( new DeleteQueueRequest() { QueueUrl = queueUrl }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; Publish messages to queues 870 Amazon Simple Notification Service Developer Guide } } Create a class that wraps Amazon SNS operations. /// <summary> /// Wrapper for Amazon Simple Notification Service (SNS) operations. /// </summary> public class SNSWrapper { private readonly IAmazonSimpleNotificationService _amazonSNSClient; /// <summary> /// Constructor for the Amazon SNS wrapper. /// </summary> /// <param name="amazonSQS">The injected Amazon SNS client.</param> public SNSWrapper(IAmazonSimpleNotificationService amazonSNS) { _amazonSNSClient = amazonSNS; } /// <summary> /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de- duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic) { // Update the name if it is not correct for a FIFO topic. Publish messages to queues 871 Amazon Simple Notification Service Developer Guide if (!topicName.EndsWith(".fifo")) { createTopicRequest.Name = topicName + ".fifo"; } // Add the attributes from the method parameters. createTopicRequest.Attributes = new Dictionary<string, string> { { "FifoTopic", "true" } }; if (useContentBasedDeduplication) { createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true"); } } var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest); return createResponse.TopicArn; } /// <summary> /// Subscribe a queue to a topic with optional filters. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <returns>The ARN of the new subscription.</returns> public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn) { var subscribeRequest = new SubscribeRequest() { TopicArn = topicArn, Protocol = "sqs", Endpoint = queueArn }; if (!string.IsNullOrEmpty(filterPolicy)) { subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } }; Publish messages to queues 872 Amazon Simple Notification Service } Developer Guide var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest); return subscribeResponse.SubscriptionArn; } /// <summary> /// Publish a message to a topic with an attribute and optional deduplication and group IDs. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="message">The message to publish.</param> /// <param name="attributeName">The optional attribute for the message.</ param> /// <param name="attributeValue">The optional attribute value for the message.</param> /// <param name="deduplicationId">The optional deduplication ID for the message.</param> /// <param name="groupId">The optional group ID for the message.</param> /// <returns>The ID of the message published.</returns> public async Task<string> PublishToTopicWithAttribute( string topicArn, string message, string? attributeName = null, string? attributeValue = null, string? deduplicationId = null, string? groupId = null) { var publishRequest = new PublishRequest() { TopicArn = topicArn, Message = message, MessageDeduplicationId = deduplicationId, MessageGroupId = groupId }; if (attributeValue != null) { // Add the string attribute if it exists. publishRequest.MessageAttributes = new Dictionary<string, MessageAttributeValue> { Publish messages to queues 873 Amazon Simple Notification Service Developer Guide { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} } }; } var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest); return publishResponse.MessageId; } /// <summary> /// Unsubscribe from a topic by a subscription ARN. /// </summary> /// <param name="subscriptionArn">The ARN of the subscription.</param> /// <returns>True
sns-dg-225
sns-dg.pdf
225
= null, string? groupId = null) { var publishRequest = new PublishRequest() { TopicArn = topicArn, Message = message, MessageDeduplicationId = deduplicationId, MessageGroupId = groupId }; if (attributeValue != null) { // Add the string attribute if it exists. publishRequest.MessageAttributes = new Dictionary<string, MessageAttributeValue> { Publish messages to queues 873 Amazon Simple Notification Service Developer Guide { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} } }; } var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest); return publishResponse.MessageId; } /// <summary> /// Unsubscribe from a topic by a subscription ARN. /// </summary> /// <param name="subscriptionArn">The ARN of the subscription.</param> /// <returns>True if successful.</returns> public async Task<bool> UnsubscribeByArn(string subscriptionArn) { var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync( new UnsubscribeRequest() { SubscriptionArn = subscriptionArn }); return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK; } /// <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 the following topics in AWS SDK for .NET API Reference. Publish messages to queues 874 Amazon Simple Notification Service Developer Guide • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe 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. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Workflow for messaging with topics and queues using Amazon SNS and Amazon SQS. /*! \param clientConfig Aws client configuration. \return bool: Successful completion. */ bool AwsDoc::TopicsAndQueues::messagingWithTopicsAndQueues( const Aws::Client::ClientConfiguration &clientConfiguration) { std::cout << "Welcome to messaging with topics and queues." << std::endl; printAsterisksLine(); std::cout << "In this workflow, you will create an SNS topic and subscribe " Publish messages to queues 875 Amazon Simple Notification Service Developer Guide << NUMBER_OF_QUEUES << " SQS queues to the topic." << std::endl; std::cout << "You can select from several options for configuring the topic and the subscriptions for the " << NUMBER_OF_QUEUES << " queues." << std::endl; std::cout << "You can then post to the topic and see the results in the queues." << std::endl; Aws::SNS::SNSClient snsClient(clientConfiguration); printAsterisksLine(); std::cout << "SNS topics can be configured as FIFO (First-In-First-Out)." << std::endl; std::cout << "FIFO topics deliver messages in order and support deduplication and message filtering." << std::endl; bool isFifoTopic = askYesNoQuestion( "Would you like to work with FIFO topics? (y/n) "); bool contentBasedDeduplication = false; Aws::String topicName; if (isFifoTopic) { printAsterisksLine(); std::cout << "Because you have chosen a FIFO topic, deduplication is supported." << std::endl; std::cout << "Deduplication IDs are either set in the message or automatically generated " << "from content using a hash function." << std::endl; std::cout << "If a message is successfully published to an SNS FIFO topic, any message " << "published and determined to have the same deduplication ID, " << std::endl; std::cout << "within the five-minute deduplication interval, is accepted but not delivered." << std::endl; std::cout Publish messages to queues 876 Amazon Simple Notification Service Developer Guide << "For more information about deduplication, " << "see https://docs.aws.amazon.com/sns/latest/dg/fifo-message- dedup.html." << std::endl; contentBasedDeduplication = askYesNoQuestion( "Use content-based deduplication instead of entering a deduplication ID? (y/n) "); } printAsterisksLine(); Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::Vector<Aws::String> queueURLS; Aws::Vector<Aws::String> subscriptionARNS; Aws::String topicARN; { topicName = askQuestion("Enter a name for your SNS topic. "); // 1. Create an Amazon SNS topic, either FIFO or non-FIFO. Aws::SNS::Model::CreateTopicRequest request; if (isFifoTopic) { request.AddAttributes("FifoTopic", "true"); if (contentBasedDeduplication) { request.AddAttributes("ContentBasedDeduplication", "true"); } topicName = topicName + FIFO_SUFFIX; std::cout << "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name." << std::endl; } request.SetName(topicName); Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARN = outcome.GetResult().GetTopicArn(); std::cout << "Your new topic with the name '" << topicName Publish messages to queues 877 Amazon Simple Notification Service Developer Guide << "' and the topic Amazon Resource Name (ARN) " << std::endl; std::cout << "'" << topicARN << "' has been created." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::CreateTopic. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); std::cout << "Now you will create " << NUMBER_OF_QUEUES << " SQS queues to subscribe to the topic." << std::endl; Aws::Vector<Aws::String> queueNames; bool filteringMessages = false; bool first = true; for (int i = 1; i <= NUMBER_OF_QUEUES; ++i) { Aws::String queueURL; Aws::String queueName; { printAsterisksLine(); std::ostringstream ostringstream; ostringstream << "Enter a name for " << (first ? "an" : "the next") << " SQS queue. "; queueName = askQuestion(ostringstream.str()); // 2. Create an SQS queue. Aws::SQS::Model::CreateQueueRequest request; if (isFifoTopic) { request.AddAttributes(Aws::SQS::Model::QueueAttributeName::FifoQueue, "true"); queueName = queueName + FIFO_SUFFIX; Publish messages to
sns-dg-226
sns-dg.pdf
226
queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); std::cout << "Now you will create " << NUMBER_OF_QUEUES << " SQS queues to subscribe to the topic." << std::endl; Aws::Vector<Aws::String> queueNames; bool filteringMessages = false; bool first = true; for (int i = 1; i <= NUMBER_OF_QUEUES; ++i) { Aws::String queueURL; Aws::String queueName; { printAsterisksLine(); std::ostringstream ostringstream; ostringstream << "Enter a name for " << (first ? "an" : "the next") << " SQS queue. "; queueName = askQuestion(ostringstream.str()); // 2. Create an SQS queue. Aws::SQS::Model::CreateQueueRequest request; if (isFifoTopic) { request.AddAttributes(Aws::SQS::Model::QueueAttributeName::FifoQueue, "true"); queueName = queueName + FIFO_SUFFIX; Publish messages to queues 878 Amazon Simple Notification Service Developer Guide if (first) // Only explain this once. { std::cout << "Because you are creating a FIFO SQS queue, '.fifo' must " << "be appended to the queue name." << std::endl; } } request.SetQueueName(queueName); queueNames.push_back(queueName); Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request); if (outcome.IsSuccess()) { queueURL = outcome.GetResult().GetQueueUrl(); std::cout << "Your new SQS queue with the name '" << queueName << "' and the queue URL " << std::endl; std::cout << "'" << queueURL << "' has been created." << std::endl; } else { std::cerr << "Error with SQS::CreateQueue. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } queueURLS.push_back(queueURL); if (first) // Only explain this once. { std::cout << "The queue URL is used to retrieve the queue ARN, which is " Publish messages to queues 879 Amazon Simple Notification Service Developer Guide << "used to create a subscription." << std::endl; } Aws::String queueARN; { // 3. Get the SQS queue ARN attribute. Aws::SQS::Model::GetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn); Aws::SQS::Model::GetQueueAttributesOutcome outcome = sqsClient.GetQueueAttributes(request); if (outcome.IsSuccess()) { const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String> &attributes = outcome.GetResult().GetAttributes(); const auto &iter = attributes.find( Aws::SQS::Model::QueueAttributeName::QueueArn); if (iter != attributes.end()) { queueARN = iter->second; std::cout << "The queue ARN '" << queueARN << "' has been retrieved." << std::endl; } else { std::cerr << "Error ARN attribute not returned by GetQueueAttribute." << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } else { std::cerr << "Error with SQS::GetQueueAttributes. " << outcome.GetError().GetMessage() Publish messages to queues 880 Amazon Simple Notification Service Developer Guide << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } if (first) { std::cout << "An IAM policy must be attached to an SQS queue, enabling it to receive " "messages from an SNS topic." << std::endl; } { // 4. Set the SQS queue policy attribute with a policy enabling the receipt of SNS messages. Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); Aws::String policy = createPolicyForQueue(queueARN, topicARN); request.AddAttributes(Aws::SQS::Model::QueueAttributeName::Policy, policy); Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(request); if (outcome.IsSuccess()) { std::cout << "The attributes for the queue '" << queueName << "' were successfully updated." << std::endl; } else { std::cerr << "Error with SQS::SetQueueAttributes. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, Publish messages to queues 881 Amazon Simple Notification Service Developer Guide sqsClient); return false; } } printAsterisksLine(); { // 5. Subscribe the SQS queue to the SNS topic. Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); if (isFifoTopic) { if (first) { std::cout << "Subscriptions to a FIFO topic can have filters." << std::endl; std::cout << "If you add a filter to this subscription, then only the filtered messages " << "will be received in the queue." << std::endl; std::cout << "For information about message filtering, " << "see https://docs.aws.amazon.com/sns/latest/dg/ sns-message-filtering.html" << std::endl; std::cout << "For this example, you can filter messages by a \"" << TONE_ATTRIBUTE << "\" attribute." << std::endl; } std::ostringstream ostringstream; ostringstream << "Filter messages for \"" << queueName << "\"'s subscription to the topic \"" << topicName << "\"? (y/n)"; // Add filter if user answers yes. if (askYesNoQuestion(ostringstream.str())) { Aws::String jsonPolicy = getFilterPolicyFromUser(); if (!jsonPolicy.empty()) { filteringMessages = true; Publish messages to queues 882 Amazon Simple Notification Service Developer Guide std::cout << "This is the filter policy for this subscription." << std::endl; std::cout << jsonPolicy << std::endl; request.AddAttributes("FilterPolicy", jsonPolicy); } else { std::cout << "Because you did not select any attributes, no filter " << "will be added to this subscription." << std::endl; } } } // if (isFifoTopic) Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } Publish messages to queues 883 Amazon Simple Notification Service Developer Guide first = false; } first = true; do { printAsterisksLine(); // 6. Publish a message to the SNS topic. Aws::SNS::Model::PublishRequest request; request.SetTopicArn(topicARN); Aws::String message = askQuestion("Enter a message text to publish. "); request.SetMessage(message); if (isFifoTopic) { if (first) { std::cout << "Because you are using a
sns-dg-227
sns-dg.pdf
227
"'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } Publish messages to queues 883 Amazon Simple Notification Service Developer Guide first = false; } first = true; do { printAsterisksLine(); // 6. Publish a message to the SNS topic. Aws::SNS::Model::PublishRequest request; request.SetTopicArn(topicARN); Aws::String message = askQuestion("Enter a message text to publish. "); request.SetMessage(message); if (isFifoTopic) { if (first) { std::cout << "Because you are using a FIFO topic, you must set a message group ID." << std::endl; std::cout << "All messages within the same group will be received in the " << "order they were published." << std::endl; } Aws::String messageGroupID = askQuestion( "Enter a message group ID for this message. "); request.SetMessageGroupId(messageGroupID); if (!contentBasedDeduplication) { if (first) { std::cout << "Because you are not using content-based deduplication, " << "you must enter a deduplication ID." << std::endl; } Aws::String deduplicationID = askQuestion( "Enter a deduplication ID for this message. "); request.SetMessageDeduplicationId(deduplicationID); } } if (filteringMessages && askYesNoQuestion( "Add an attribute to this message? (y/n) ")) { for (size_t i = 0; i < TONES.size(); ++i) { std::cout << " " << (i + 1) << ". " << TONES[i] << std::endl; Publish messages to queues 884 Amazon Simple Notification Service } Developer Guide int selection = askQuestionForIntRange( "Enter a number for an attribute. ", 1, static_cast<int>(TONES.size())); Aws::SNS::Model::MessageAttributeValue messageAttributeValue; messageAttributeValue.SetDataType("String"); messageAttributeValue.SetStringValue(TONES[selection - 1]); request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue); } Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Your message was successfully published." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Publish. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } first = false; } while (askYesNoQuestion("Post another message? (y/n) ")); printAsterisksLine(); std::cout << "Now the SQS queue will be polled to retrieve the messages." << std::endl; askQuestion("Press any key to continue...", alwaysTrueTest); for (size_t i = 0; i < queueURLS.size(); ++i) { // 7. Poll an SQS queue for its messages. std::vector<Aws::String> messages; std::vector<Aws::String> receiptHandles; while (true) { Aws::SQS::Model::ReceiveMessageRequest request; Publish messages to queues 885 Amazon Simple Notification Service Developer Guide request.SetMaxNumberOfMessages(10); request.SetQueueUrl(queueURLS[i]); // Setting WaitTimeSeconds to non-zero enables long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html request.SetWaitTimeSeconds(1); Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SQS::Model::Message> &newMessages = outcome.GetResult().GetMessages(); if (newMessages.empty()) { break; } else { for (const Aws::SQS::Model::Message &message: newMessages) { messages.push_back(message.GetBody()); receiptHandles.push_back(message.GetReceiptHandle()); } } } else { std::cerr << "Error with SQS::ReceiveMessage. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); if (messages.empty()) { std::cout << "No messages were "; } Publish messages to queues 886 Amazon Simple Notification Service Developer Guide else if (messages.size() == 1) { std::cout << "One message was "; } else { std::cout << messages.size() << " messages were "; } std::cout << "received by the queue '" << queueNames[i] << "'." << std::endl; for (const Aws::String &message: messages) { std::cout << " Message : '" << message << "'." << std::endl; } // 8. Delete a batch of messages from an SQS queue. if (!receiptHandles.empty()) { Aws::SQS::Model::DeleteMessageBatchRequest request; request.SetQueueUrl(queueURLS[i]); int id = 1; // Ids must be unique within a batch delete request. for (const Aws::String &receiptHandle: receiptHandles) { Aws::SQS::Model::DeleteMessageBatchRequestEntry entry; entry.SetId(std::to_string(id)); ++id; entry.SetReceiptHandle(receiptHandle); request.AddEntries(entry); } Aws::SQS::Model::DeleteMessageBatchOutcome outcome = sqsClient.DeleteMessageBatch(request); if (outcome.IsSuccess()) { std::cout << "The batch deletion of messages was successful." << std::endl; } else { std::cerr << "Error with SQS::DeleteMessageBatch. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; Publish messages to queues 887 Amazon Simple Notification Service Developer Guide } } } return cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient, true); // askUser } bool AwsDoc::TopicsAndQueues::cleanUp(const Aws::String &topicARN, const Aws::Vector<Aws::String> &queueURLS, const Aws::Vector<Aws::String> &subscriptionARNS, const Aws::SNS::SNSClient &snsClient, const Aws::SQS::SQSClient &sqsClient, bool askUser) { bool result = true; printAsterisksLine(); if (!queueURLS.empty() && askUser && askYesNoQuestion("Delete the SQS queues? (y/n) ")) { for (const auto &queueURL: queueURLS) { // 9. Delete an SQS queue. Aws::SQS::Model::DeleteQueueRequest request; request.SetQueueUrl(queueURL); Aws::SQS::Model::DeleteQueueOutcome outcome = sqsClient.DeleteQueue(request); if (outcome.IsSuccess()) { std::cout << "The queue with URL '" << queueURL << "' was successfully deleted." << std::endl; } else { std::cerr << "Error with SQS::DeleteQueue. " << outcome.GetError().GetMessage() << std::endl; result = false; } } Publish messages to queues 888 Amazon Simple Notification Service Developer Guide for (const auto &subscriptionARN: subscriptionARNS) { // 10. Unsubscribe an SNS subscription. Aws::SNS::Model::UnsubscribeRequest request; request.SetSubscriptionArn(subscriptionARN); Aws::SNS::Model::UnsubscribeOutcome outcome = snsClient.Unsubscribe(request); if (outcome.IsSuccess()) { std::cout << "Unsubscribe of subscription ARN '" << subscriptionARN << "' was successful." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Unsubscribe. " << outcome.GetError().GetMessage() << std::endl; result = false; } } } printAsterisksLine(); if (!topicARN.empty() && askUser && askYesNoQuestion("Delete the SNS topic? (y/n) ")) { // 11. Delete an
sns-dg-228
sns-dg.pdf
228
{ std::cerr << "Error with SQS::DeleteQueue. " << outcome.GetError().GetMessage() << std::endl; result = false; } } Publish messages to queues 888 Amazon Simple Notification Service Developer Guide for (const auto &subscriptionARN: subscriptionARNS) { // 10. Unsubscribe an SNS subscription. Aws::SNS::Model::UnsubscribeRequest request; request.SetSubscriptionArn(subscriptionARN); Aws::SNS::Model::UnsubscribeOutcome outcome = snsClient.Unsubscribe(request); if (outcome.IsSuccess()) { std::cout << "Unsubscribe of subscription ARN '" << subscriptionARN << "' was successful." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Unsubscribe. " << outcome.GetError().GetMessage() << std::endl; result = false; } } } printAsterisksLine(); if (!topicARN.empty() && askUser && askYesNoQuestion("Delete the SNS topic? (y/n) ")) { // 11. Delete an SNS topic. Aws::SNS::Model::DeleteTopicRequest request; request.SetTopicArn(topicARN); Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request); if (outcome.IsSuccess()) { std::cout << "The topic with ARN '" << topicARN << "' was successfully deleted." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::DeleteTopicRequest. " << outcome.GetError().GetMessage() << std::endl; result = false; } Publish messages to queues 889 Amazon Simple Notification Service } return result; } Developer Guide //! Create an IAM policy that gives an SQS queue permission to receive messages from an SNS topic. /*! \sa createPolicyForQueue() \param queueARN: The SQS queue Amazon Resource Name (ARN). \param topicARN: The SNS topic ARN. \return Aws::String: The policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::createPolicyForQueue(const Aws::String &queueARN, const Aws::String &topicARN) { std::ostringstream policyStream; policyStream << R"({ "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": ")" << queueARN << R"(", "Condition": { "ArnEquals": { "aws:SourceArn": ")" << topicARN << R"(" } } } ] })"; return policyStream.str(); } • For API details, see the following topics in AWS SDK for C++ API Reference. • CreateQueue • CreateTopic Publish messages to queues 890 Amazon Simple Notification Service Developer Guide • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe 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. Run an interactive scenario at a command prompt. import ( "context" "encoding/json" "fmt" "log" "strings" "topics_and_queues/actions" "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/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" "github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools" ) Publish messages to queues 891 Amazon Simple Notification Service Developer Guide const FIFO_SUFFIX = ".fifo" const TONE_KEY = "tone" var ToneChoices = []string{"cheerful", "funny", "serious", "sincere"} // MessageBody is used to deserialize the body of a message from a JSON string. type MessageBody struct { Message string } // ScenarioRunner separates the steps of this scenario into individual functions so that // they are simpler to read and understand. type ScenarioRunner struct { questioner demotools.IQuestioner snsActor *actions.SnsActions sqsActor *actions.SqsActions } func (runner ScenarioRunner) CreateTopic(ctx context.Context) (string, string, bool, bool) { log.Println("SNS topics can be configured as FIFO (First-In-First-Out) or standard.\n" + "FIFO topics deliver messages in order and support deduplication and message filtering.") isFifoTopic := runner.questioner.AskBool("\nWould you like to work with FIFO topics? (y/n) ", "y") contentBasedDeduplication := false if isFifoTopic { log.Println(strings.Repeat("-", 88)) log.Println("Because you have chosen a FIFO topic, deduplication is supported. \n" + "Deduplication IDs are either set in the message or are automatically generated\n" + "from content using a hash function. If a message is successfully published to \n" + "an SNS FIFO topic, any message published and determined to have the same\n" + "deduplication ID, within the five-minute deduplication interval, is accepted \n" + "but not delivered. For more information about deduplication, see:\n" + "\thttps://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.") contentBasedDeduplication = runner.questioner.AskBool( Publish messages to queues 892 Amazon Simple Notification Service Developer Guide "\nDo you want to use content-based deduplication instead of entering a deduplication ID? (y/n) ", "y") } log.Println(strings.Repeat("-", 88)) topicName := runner.questioner.Ask("Enter a name for your SNS topic. ") if isFifoTopic { topicName = fmt.Sprintf("%v%v", topicName, FIFO_SUFFIX) log.Printf("Because you have selected a FIFO topic, '%v' must be appended to \n"+ "the topic name.", FIFO_SUFFIX) } topicArn, err := runner.snsActor.CreateTopic(ctx, topicName, isFifoTopic, contentBasedDeduplication) if err != nil { panic(err) } log.Printf("Your new topic with the name '%v' and Amazon Resource Name (ARN) \n"+ "'%v' has been created.", topicName, topicArn) return topicName, topicArn, isFifoTopic, contentBasedDeduplication } func (runner ScenarioRunner) CreateQueue(ctx context.Context, ordinal string, isFifoTopic bool) (string, string) { queueName := runner.questioner.Ask(fmt.Sprintf("Enter a name for the %v SQS queue. ", ordinal)) if isFifoTopic { queueName = fmt.Sprintf("%v%v", queueName, FIFO_SUFFIX) if ordinal == "first" { log.Printf("Because you are creating a FIFO SQS queue, '%v' must "+ "be appended to the queue name.\n", FIFO_SUFFIX) } } queueUrl, err := runner.sqsActor.CreateQueue(ctx, queueName, isFifoTopic) if err != nil { panic(err) } log.Printf("Your new SQS queue with the name '%v' and the queue URL "+ "'%v' has been created.", queueName, queueUrl) return queueName, queueUrl Publish messages to queues 893 Amazon Simple Notification Service Developer Guide } func (runner ScenarioRunner) SubscribeQueueToTopic( ctx context.Context, queueName string, queueUrl string, topicName string, topicArn string, ordinal string, isFifoTopic bool) (string, bool) { queueArn, err := runner.sqsActor.GetQueueArn(ctx, queueUrl) if err
sns-dg-229
sns-dg.pdf
229
if ordinal == "first" { log.Printf("Because you are creating a FIFO SQS queue, '%v' must "+ "be appended to the queue name.\n", FIFO_SUFFIX) } } queueUrl, err := runner.sqsActor.CreateQueue(ctx, queueName, isFifoTopic) if err != nil { panic(err) } log.Printf("Your new SQS queue with the name '%v' and the queue URL "+ "'%v' has been created.", queueName, queueUrl) return queueName, queueUrl Publish messages to queues 893 Amazon Simple Notification Service Developer Guide } func (runner ScenarioRunner) SubscribeQueueToTopic( ctx context.Context, queueName string, queueUrl string, topicName string, topicArn string, ordinal string, isFifoTopic bool) (string, bool) { queueArn, err := runner.sqsActor.GetQueueArn(ctx, queueUrl) if err != nil { panic(err) } log.Printf("The ARN of your queue is: %v.\n", queueArn) err = runner.sqsActor.AttachSendMessagePolicy(ctx, queueUrl, queueArn, topicArn) if err != nil { panic(err) } log.Println("Attached an IAM policy to the queue so the SNS topic can send " + "messages to it.") log.Println(strings.Repeat("-", 88)) var filterPolicy map[string][]string if isFifoTopic { if ordinal == "first" { log.Println("Subscriptions to a FIFO topic can have filters.\n" + "If you add a filter to this subscription, then only the filtered messages\n" + "will be received in the queue.\n" + "For information about message filtering, see\n" + "\thttps://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n" + "For this example, you can filter messages by a \"tone\" attribute.") } wantFiltering := runner.questioner.AskBool( fmt.Sprintf("Do you want to filter messages that are sent to \"%v\"\n"+ "from the %v topic? (y/n) ", queueName, topicName), "y") if wantFiltering { log.Println("You can filter messages by one or more of the following \"tone\" attributes.") var toneSelections []string askAboutTones := true for askAboutTones { toneIndex := runner.questioner.AskChoice( Publish messages to queues 894 Amazon Simple Notification Service Developer Guide "Enter the number of the tone you want to filter by:\n", ToneChoices) toneSelections = append(toneSelections, ToneChoices[toneIndex]) askAboutTones = runner.questioner.AskBool("Do you want to add another tone to the filter? (y/n) ", "y") } log.Printf("Your subscription will be filtered to only pass the following tones: %v\n", toneSelections) filterPolicy = map[string][]string{TONE_KEY: toneSelections} } } subscriptionArn, err := runner.snsActor.SubscribeQueue(ctx, topicArn, queueArn, filterPolicy) if err != nil { panic(err) } log.Printf("The queue %v is now subscribed to the topic %v with the subscription ARN %v.\n", queueName, topicName, subscriptionArn) return subscriptionArn, filterPolicy != nil } func (runner ScenarioRunner) PublishMessages(ctx context.Context, topicArn string, isFifoTopic bool, contentBasedDeduplication bool, usingFilters bool) { var message string var groupId string var dedupId string var toneSelection string publishMore := true for publishMore { groupId = "" dedupId = "" toneSelection = "" message = runner.questioner.Ask("Enter a message to publish: ") if isFifoTopic { log.Println("Because you are using a FIFO topic, you must set a message group ID.\n" + "All messages within the same group will be received in the order they were published.") groupId = runner.questioner.Ask("Enter a message group ID: ") if !contentBasedDeduplication { log.Println("Because you are not using content-based deduplication,\n" + "you must enter a deduplication ID.") Publish messages to queues 895 Amazon Simple Notification Service Developer Guide dedupId = runner.questioner.Ask("Enter a deduplication ID: ") } } if usingFilters { if runner.questioner.AskBool("Add a tone attribute so this message can be filtered? (y/n) ", "y") { toneIndex := runner.questioner.AskChoice( "Enter the number of the tone you want to filter by:\n", ToneChoices) toneSelection = ToneChoices[toneIndex] } } err := runner.snsActor.Publish(ctx, topicArn, message, groupId, dedupId, TONE_KEY, toneSelection) if err != nil { panic(err) } log.Println(("Your message was published.")) publishMore = runner.questioner.AskBool("Do you want to publish another messsage? (y/n) ", "y") } } func (runner ScenarioRunner) PollForMessages(ctx context.Context, queueUrls []string) { log.Println("Polling queues for messages...") for _, queueUrl := range queueUrls { var messages []types.Message for { currentMsgs, err := runner.sqsActor.GetMessages(ctx, queueUrl, 10, 1) if err != nil { panic(err) } if len(currentMsgs) == 0 { break } messages = append(messages, currentMsgs...) } if len(messages) == 0 { log.Printf("No messages were received by queue %v.\n", queueUrl) } else if len(messages) == 1 { log.Printf("One message was received by queue %v:\n", queueUrl) Publish messages to queues 896 Amazon Simple Notification Service } else { Developer Guide log.Printf("%v messages were received by queue %v:\n", len(messages), queueUrl) } for msgIndex, message := range messages { messageBody := MessageBody{} err := json.Unmarshal([]byte(*message.Body), &messageBody) if err != nil { panic(err) } log.Printf("Message %v: %v\n", msgIndex+1, messageBody.Message) } if len(messages) > 0 { log.Printf("Deleting %v messages from queue %v.\n", len(messages), queueUrl) err := runner.sqsActor.DeleteMessages(ctx, queueUrl, messages) if err != nil { panic(err) } } } } // RunTopicsAndQueuesScenario is an interactive example that shows you how to use the // AWS SDK for Go to create and use Amazon SNS topics and Amazon SQS queues. // // 1. Create a topic (FIFO or non-FIFO). // 2. Subscribe several queues to the topic with an option to apply a filter. // 3. Publish messages to the topic. // 4. Poll the queues for messages received. // 5. Delete the topic and the queues. // // This example creates service clients from the
sns-dg-230
sns-dg.pdf
230
err := runner.sqsActor.DeleteMessages(ctx, queueUrl, messages) if err != nil { panic(err) } } } } // RunTopicsAndQueuesScenario is an interactive example that shows you how to use the // AWS SDK for Go to create and use Amazon SNS topics and Amazon SQS queues. // // 1. Create a topic (FIFO or non-FIFO). // 2. Subscribe several queues to the topic with an option to apply a filter. // 3. Publish messages to the topic. // 4. Poll the queues for messages received. // 5. Delete the topic and the queues. // // This example creates service clients from the specified sdkConfig so that // you can replace it with a mocked or stubbed config for unit testing. // // It uses a questioner from the `demotools` package to get input during the example. // This package can be found in the ..\..\demotools folder of this repo. func RunTopicsAndQueuesScenario( ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) { resources := Resources{} defer func() { if r := recover(); r != nil { Publish messages to queues 897 Amazon Simple Notification Service Developer Guide log.Println("Something went wrong with the demo.\n" + "Cleaning up any resources that were created...") resources.Cleanup(ctx) } }() queueCount := 2 log.Println(strings.Repeat("-", 88)) log.Printf("Welcome to messaging with topics and queues.\n\n"+ "In this scenario, you will create an SNS topic and subscribe %v SQS queues to the\n"+ "topic. You can select from several options for configuring the topic and the \n"+ "subscriptions for the queues. You can then post to the topic and see the results\n"+ "in the queues.\n", queueCount) log.Println(strings.Repeat("-", 88)) runner := ScenarioRunner{ questioner: questioner, snsActor: &actions.SnsActions{SnsClient: sns.NewFromConfig(sdkConfig)}, sqsActor: &actions.SqsActions{SqsClient: sqs.NewFromConfig(sdkConfig)}, } resources.snsActor = runner.snsActor resources.sqsActor = runner.sqsActor topicName, topicArn, isFifoTopic, contentBasedDeduplication := runner.CreateTopic(ctx) resources.topicArn = topicArn log.Println(strings.Repeat("-", 88)) log.Printf("Now you will create %v SQS queues and subscribe them to the topic. \n", queueCount) ordinals := []string{"first", "next"} usingFilters := false for _, ordinal := range ordinals { queueName, queueUrl := runner.CreateQueue(ctx, ordinal, isFifoTopic) resources.queueUrls = append(resources.queueUrls, queueUrl) _, filtering := runner.SubscribeQueueToTopic(ctx, queueName, queueUrl, topicName, topicArn, ordinal, isFifoTopic) usingFilters = usingFilters || filtering } Publish messages to queues 898 Amazon Simple Notification Service Developer Guide log.Println(strings.Repeat("-", 88)) runner.PublishMessages(ctx, topicArn, isFifoTopic, contentBasedDeduplication, usingFilters) log.Println(strings.Repeat("-", 88)) runner.PollForMessages(ctx, resources.queueUrls) log.Println(strings.Repeat("-", 88)) wantCleanup := questioner.AskBool("Do you want to remove all AWS resources created for this scenario? (y/n) ", "y") if wantCleanup { log.Println("Cleaning up resources...") resources.Cleanup(ctx) } log.Println(strings.Repeat("-", 88)) log.Println("Thanks for watching!") log.Println(strings.Repeat("-", 88)) } Define a struct that wraps Amazon SNS actions used in this example. 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 } Publish messages to queues 899 Amazon Simple Notification Service Developer Guide // CreateTopic creates an Amazon SNS topic with the specified name. You can optionally // specify that the topic is created as a FIFO topic and whether it uses content- based // deduplication instead of ID-based deduplication. func (actor SnsActions) CreateTopic(ctx context.Context, topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) { var topicArn string topicAttributes := map[string]string{} if isFifoTopic { topicAttributes["FifoTopic"] = "true" } if contentBasedDeduplication { topicAttributes["ContentBasedDeduplication"] = "true" } topic, err := actor.SnsClient.CreateTopic(ctx, &sns.CreateTopicInput{ Name: aws.String(topicName), Attributes: topicAttributes, }) if err != nil { log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err) } else { topicArn = *topic.TopicArn } return topicArn, err } // 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 } Publish messages to queues 900 Amazon Simple Notification Service Developer Guide // SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an // Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy // so that messages are only sent to the queue when the message has the specified attributes. func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) { var subscriptionArn string var attributes map[string]string if filterMap != nil { filterBytes, err := json.Marshal(filterMap) if err != nil { log.Printf("Couldn't create filter policy, here's why: %v\n", err) return "", err } attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err } // Publish publishes a message to an Amazon SNS topic. The message is then sent to all // subscribers. When the topic is a FIFO topic, the message must also contain a group ID // and, when ID-based deduplication is used, a
sns-dg-231
sns-dg.pdf
231
here's why: %v\n", err) return "", err } attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err } // Publish publishes a message to an Amazon SNS topic. The message is then sent to all // subscribers. When the topic is a FIFO topic, the message must also contain a group ID // and, when ID-based deduplication is used, a deduplication ID. An optional key- value Publish messages to queues 901 Amazon Simple Notification Service Developer Guide // filter attribute can be specified so that the message can be filtered according to // a filter policy. func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error { publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)} if groupId != "" { publishInput.MessageGroupId = aws.String(groupId) } if dedupId != "" { publishInput.MessageDeduplicationId = aws.String(dedupId) } if filterKey != "" && filterValue != "" { publishInput.MessageAttributes = map[string]types.MessageAttributeValue{ filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)}, } } _, err := actor.SnsClient.Publish(ctx, &publishInput) if err != nil { log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err) } return err } Define a struct that wraps Amazon SQS actions used in this example. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) Publish messages to queues 902 Amazon Simple Notification Service Developer Guide // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // CreateQueue creates an Amazon SQS queue with the specified name. You can specify // whether the queue is created as a FIFO queue. func (actor SqsActions) CreateQueue(ctx context.Context, queueName string, isFifoQueue bool) (string, error) { var queueUrl string queueAttributes := map[string]string{} if isFifoQueue { queueAttributes["FifoQueue"] = "true" } queue, err := actor.SqsClient.CreateQueue(ctx, &sqs.CreateQueueInput{ QueueName: aws.String(queueName), Attributes: queueAttributes, }) if err != nil { log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err) } else { queueUrl = *queue.QueueUrl } return queueUrl, err } // GetQueueArn uses the GetQueueAttributes action to get the Amazon Resource Name (ARN) // of an Amazon SQS queue. func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) { var queueArn string arnAttributeName := types.QueueAttributeNameQueueArn attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(queueUrl), Publish messages to queues 903 Amazon Simple Notification Service Developer Guide AttributeNames: []types.QueueAttributeName{arnAttributeName}, }) if err != nil { log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err) } else { queueArn = attribute.Attributes[string(arnAttributeName)] } return queueArn, err } // AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an // Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the // queue. func (actor SqsActions) AttachSendMessagePolicy(ctx context.Context, queueUrl string, queueArn string, topicArn string) error { policyDoc := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Action: "sqs:SendMessage", Principal: map[string]string{"Service": "sns.amazonaws.com"}, Resource: aws.String(queueArn), Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}}, }}, } policyBytes, err := json.Marshal(policyDoc) if err != nil { log.Printf("Couldn't create policy document. Here's why: %v\n", err) return err } _, err = actor.SqsClient.SetQueueAttributes(ctx, &sqs.SetQueueAttributesInput{ Attributes: map[string]string{ string(types.QueueAttributeNamePolicy): string(policyBytes), }, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err) Publish messages to queues 904 Amazon Simple Notification Service Developer Guide } return err } // PolicyDocument defines a policy document as a Go struct that can be serialized // to JSON. type PolicyDocument struct { Version string Statement []PolicyStatement } // PolicyStatement defines a statement in a policy document. type PolicyStatement struct { Effect string Action string Principal map[string]string `json:",omitempty"` Resource *string `json:",omitempty"` Condition PolicyCondition `json:",omitempty"` } // PolicyCondition defines a condition in a policy. type PolicyCondition map[string]map[string]string // GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue. func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) { var messages []types.Message result, err := actor.SqsClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{ QueueUrl: aws.String(queueUrl), MaxNumberOfMessages: maxMessages, WaitTimeSeconds: waitTime, }) if err != nil { log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err) } else { messages = result.Messages } return messages, err } Publish messages to queues 905 Amazon Simple Notification Service Developer Guide // DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from // an Amazon SQS queue. func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error { entries := make([]types.DeleteMessageBatchRequestEntry, len(messages)) for msgIndex := range messages { entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex)) entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle } _, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{ Entries: entries, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err) } return err } //
sns-dg-232
sns-dg.pdf
232
} else { messages = result.Messages } return messages, err } Publish messages to queues 905 Amazon Simple Notification Service Developer Guide // DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from // an Amazon SQS queue. func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error { entries := make([]types.DeleteMessageBatchRequestEntry, len(messages)) for msgIndex := range messages { entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex)) entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle } _, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{ Entries: entries, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err) } return err } // DeleteQueue deletes an Amazon SQS queue. func (actor SqsActions) DeleteQueue(ctx context.Context, queueUrl string) error { _, err := actor.SqsClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{ QueueUrl: aws.String(queueUrl)}) if err != nil { log.Printf("Couldn't delete queue %v. Here's why: %v\n", queueUrl, err) } return err } Clean up resources. import ( "context" "fmt" Publish messages to queues 906 Amazon Simple Notification Service Developer Guide "log" "topics_and_queues/actions" ) // Resources keeps track of AWS resources created during an example and handles // cleanup when the example finishes. type Resources struct { topicArn string queueUrls []string snsActor *actions.SnsActions sqsActor *actions.SqsActions } // Cleanup deletes all AWS resources created during an example. func (resources Resources) Cleanup(ctx context.Context) { defer func() { if r := recover(); r != nil { fmt.Println("Something went wrong during cleanup. Use the AWS Management Console\n" + "to remove any remaining resources that were created for this scenario.") } }() var err error if resources.topicArn != "" { log.Printf("Deleting topic %v.\n", resources.topicArn) err = resources.snsActor.DeleteTopic(ctx, resources.topicArn) if err != nil { panic(err) } } for _, queueUrl := range resources.queueUrls { log.Printf("Deleting queue %v.\n", queueUrl) err = resources.sqsActor.DeleteQueue(ctx, queueUrl) if err != nil { panic(err) } } } • For API details, see the following topics in AWS SDK for Go API Reference. Publish messages to queues 907 Amazon Simple Notification Service Developer Guide • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe 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. package com.example.sns; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.MessageAttributeValue; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest; Publish messages to queues 908 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest; import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry; import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.SqsException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * <p> * For more information, see the following documentation topic: * <p> * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html * <p> * This Java example performs these tasks: * <p> * 1. Gives the user three options to choose from. * 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic. Publish messages to queues 909 Amazon Simple Notification Service Developer Guide * 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue. * 4. Gets the SQS queue Amazon Resource Name (ARN) attribute. * 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue. * 6. Subscribes to the SQS queue. * 7. Publishes a message to the topic. * 8. Displays the messages. * 9. Deletes the received message. * 10. Unsubscribes from the topic. * 11. Deletes the SNS topic. */ public class SNSWorkflow { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) { final String usage = "\n" + "Usage:\n" + " <fifoQueueARN>\n\n" + "Where:\n" + " accountId - Your AWS account Id value."; if (args.length != 1) { System.out.println(usage); System.exit(1); } SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); SqsClient sqsClient = SqsClient.builder() .region(Region.US_EAST_1) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Scanner in = new Scanner(System.in); String accountId = args[0]; String useFIFO; String duplication = "n"; String topicName; String deduplicationID = null; String groupId = null; Publish messages to queues 910 Amazon Simple Notification Service Developer Guide String topicArn; String sqsQueueName; String sqsQueueUrl; String sqsQueueArn; String subscriptionArn; boolean selectFIFO = false; String message; List<Message> messageList; List<String> filterList = new ArrayList<>(); String msgAttValue = ""; System.out.println(DASHES); System.out.println("Welcome to messaging with topics and queues."); System.out.println("In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.\n" + "You can select from several options for configuring the topic and the subscriptions for the queue.\n" + "You can then post to the topic and see the results in the queue."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("SNS topics can be
sns-dg-233
sns-dg.pdf
233
messages to queues 910 Amazon Simple Notification Service Developer Guide String topicArn; String sqsQueueName; String sqsQueueUrl; String sqsQueueArn; String subscriptionArn; boolean selectFIFO = false; String message; List<Message> messageList; List<String> filterList = new ArrayList<>(); String msgAttValue = ""; System.out.println(DASHES); System.out.println("Welcome to messaging with topics and queues."); System.out.println("In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.\n" + "You can select from several options for configuring the topic and the subscriptions for the queue.\n" + "You can then post to the topic and see the results in the queue."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("SNS topics can be configured as FIFO (First-In-First- Out).\n" + "FIFO topics deliver messages in order and support deduplication and message filtering.\n" + "Would you like to work with FIFO topics? (y/n)"); useFIFO = in.nextLine(); if (useFIFO.compareTo("y") == 0) { selectFIFO = true; System.out.println("You have selected FIFO"); System.out.println(" Because you have chosen a FIFO topic, deduplication is supported.\n" + " Deduplication IDs are either set in the message or automatically generated from content using a hash function.\n" + " If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID, \n" + " within the five-minute deduplication interval, is accepted but not delivered.\n" + " For more information about deduplication, see https:// docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html."); Publish messages to queues 911 Amazon Simple Notification Service Developer Guide System.out.println( "Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)"); duplication = in.nextLine(); if (duplication.compareTo("y") == 0) { System.out.println("Please enter a group id value"); groupId = in.nextLine(); } else { System.out.println("Please enter deduplication Id value"); deduplicationID = in.nextLine(); System.out.println("Please enter a group id value"); groupId = in.nextLine(); } } System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Create a topic."); System.out.println("Enter a name for your SNS topic."); topicName = in.nextLine(); if (selectFIFO) { System.out.println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name."); topicName = topicName + ".fifo"; System.out.println("The name of the topic is " + topicName); topicArn = createFIFO(snsClient, topicName, duplication); System.out.println("The ARN of the FIFO topic is " + topicArn); } else { System.out.println("The name of the topic is " + topicName); topicArn = createSNSTopic(snsClient, topicName); System.out.println("The ARN of the non-FIFO topic is " + topicArn); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Create an SQS queue."); System.out.println("Enter a name for your SQS queue."); sqsQueueName = in.nextLine(); if (selectFIFO) { sqsQueueName = sqsQueueName + ".fifo"; } Publish messages to queues 912 Amazon Simple Notification Service Developer Guide sqsQueueUrl = createQueue(sqsClient, sqsQueueName, selectFIFO); System.out.println("The queue URL is " + sqsQueueUrl); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Get the SQS queue ARN attribute."); sqsQueueArn = getSQSQueueAttrs(sqsClient, sqsQueueUrl); System.out.println("The ARN of the new queue is " + sqsQueueArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Attach an IAM policy to the queue."); // Define the policy to use. Make sure that you change the REGION if you are // running this code // in a different region. String policy = """ { "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-east-1:%s:%s", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-1:%s:%s" } } } ] } """.formatted(accountId, sqsQueueName, accountId, topicName); setQueueAttr(sqsClient, sqsQueueUrl, policy); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Subscribe to the SQS queue."); if (selectFIFO) { System.out.println( Publish messages to queues 913 Amazon Simple Notification Service Developer Guide "If you add a filter to this subscription, then only the filtered messages will be received in the queue.\n" + "For information about message filtering, see https:// docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n" + "For this example, you can filter messages by a \"tone\" attribute."); System.out.println("Would you like to filter messages for " + sqsQueueName + "'s subscription to the topic " + topicName + "? (y/n)"); String filterAns = in.nextLine(); if (filterAns.compareTo("y") == 0) { boolean moreAns = false; System.out.println("You can filter messages by one or more of the following \"tone\" attributes."); System.out.println("1. cheerful"); System.out.println("2. funny"); System.out.println("3. serious"); System.out.println("4. sincere"); while (!moreAns) { System.out.println("Select a number or choose 0 to end."); String ans = in.nextLine(); switch (ans) { case "1": filterList.add("cheerful"); break; case "2": filterList.add("funny"); break; case "3": filterList.add("serious"); break; case "4": filterList.add("sincere"); break; default: moreAns = true; break; } } } } subscriptionArn = subQueue(snsClient, topicArn, sqsQueueArn, filterList); Publish messages to queues 914 Amazon Simple Notification Service Developer Guide System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Publish a message to the topic."); if (selectFIFO) { System.out.println("Would you like to add an attribute to this message? (y/n)"); String msgAns = in.nextLine(); if (msgAns.compareTo("y") == 0) { System.out.println("You can filter messages by one or more of the following \"tone\" attributes."); System.out.println("1. cheerful"); System.out.println("2. funny"); System.out.println("3. serious"); System.out.println("4. sincere"); System.out.println("Select a number or choose 0 to end."); String ans = in.nextLine(); switch (ans) { case "1": msgAttValue = "cheerful"; break; case "2": msgAttValue = "funny"; break; case "3": msgAttValue = "serious"; break; default: msgAttValue = "sincere"; break; } System.out.println("Selected value is " + msgAttValue); } System.out.println("Enter a message.");
sns-dg-234
sns-dg.pdf
234
System.out.println("7. Publish a message to the topic."); if (selectFIFO) { System.out.println("Would you like to add an attribute to this message? (y/n)"); String msgAns = in.nextLine(); if (msgAns.compareTo("y") == 0) { System.out.println("You can filter messages by one or more of the following \"tone\" attributes."); System.out.println("1. cheerful"); System.out.println("2. funny"); System.out.println("3. serious"); System.out.println("4. sincere"); System.out.println("Select a number or choose 0 to end."); String ans = in.nextLine(); switch (ans) { case "1": msgAttValue = "cheerful"; break; case "2": msgAttValue = "funny"; break; case "3": msgAttValue = "serious"; break; default: msgAttValue = "sincere"; break; } System.out.println("Selected value is " + msgAttValue); } System.out.println("Enter a message."); message = in.nextLine(); pubMessageFIFO(snsClient, message, topicArn, msgAttValue, duplication, groupId, deduplicationID); } else { System.out.println("Enter a message."); message = in.nextLine(); pubMessage(snsClient, message, topicArn); } Publish messages to queues 915 Amazon Simple Notification Service Developer Guide System.out.println(DASHES); System.out.println(DASHES); System.out.println("8. Display the message. Press any key to continue."); in.nextLine(); messageList = receiveMessages(sqsClient, sqsQueueUrl, msgAttValue); for (Message mes : messageList) { System.out.println("Message Id: " + mes.messageId()); System.out.println("Full Message: " + mes.body()); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("9. Delete the received message. Press any key to continue."); in.nextLine(); deleteMessages(sqsClient, sqsQueueUrl, messageList); System.out.println(DASHES); System.out.println(DASHES); System.out.println("10. Unsubscribe from the topic and delete the queue. Press any key to continue."); in.nextLine(); unSub(snsClient, subscriptionArn); deleteSQSQueue(sqsClient, sqsQueueName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("11. Delete the topic. Press any key to continue."); in.nextLine(); deleteSNSTopic(snsClient, topicArn); System.out.println(DASHES); System.out.println("The SNS/SQS workflow has completed successfully."); System.out.println(DASHES); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); Publish messages to queues 916 Amazon Simple Notification Service Developer Guide System.out.println("Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteSQSQueue(SqsClient sqsClient, String queueName) { try { GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl(); DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder() .queueUrl(queueUrl) .build(); sqsClient.deleteQueue(deleteQueueRequest); System.out.println(queueName + " was successfully deleted."); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void unSub(SnsClient snsClient, String subscriptionArn) { try { UnsubscribeRequest request = UnsubscribeRequest.builder() .subscriptionArn(subscriptionArn) .build(); UnsubscribeResponse result = snsClient.unsubscribe(request); System.out.println("Status was " + result.sdkHttpResponse().statusCode() + "\nSubscription was removed for " + request.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } Publish messages to queues 917 Amazon Simple Notification Service } Developer Guide public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) { try { List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>(); for (Message msg : messages) { DeleteMessageBatchRequestEntry entry = DeleteMessageBatchRequestEntry.builder() .id(msg.messageId()) .build(); entries.add(entry); } DeleteMessageBatchRequest deleteMessageBatchRequest = DeleteMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(entries) .build(); sqsClient.deleteMessageBatch(deleteMessageBatchRequest); System.out.println("The batch delete of messages was successful"); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl, String msgAttValue) { try { if (msgAttValue.isEmpty()) { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveMessageRequest).messages(); } else { // We know there are filters on the message. Publish messages to queues 918 Amazon Simple Notification Service Developer Guide ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .messageAttributeNames(msgAttValue) // Include other message attributes if needed. .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveRequest).messages(); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } public static void pubMessage(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void pubMessageFIFO(SnsClient snsClient, String message, String topicArn, String msgAttValue, String duplication, String groupId, String deduplicationID) { Publish messages to queues 919 Amazon Simple Notification Service Developer Guide try { PublishRequest request; // Means the user did not choose to use a message attribute. if (msgAttValue.isEmpty()) { if (duplication.compareTo("y") == 0) { request = PublishRequest.builder() .message(message) .messageGroupId(groupId) .topicArn(topicArn) .build(); } else { request = PublishRequest.builder() .message(message) .messageDeduplicationId(deduplicationID) .messageGroupId(groupId) .topicArn(topicArn) .build(); } } else { Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put(msgAttValue, MessageAttributeValue.builder() .dataType("String") .stringValue("true") .build()); if (duplication.compareTo("y") == 0) { request = PublishRequest.builder() .message(message) .messageGroupId(groupId) .topicArn(topicArn) .build(); } else { // Create a publish request with the message and attributes. request = PublishRequest.builder() .topicArn(topicArn) .message(message) .messageDeduplicationId(deduplicationID) .messageGroupId(groupId) .messageAttributes(messageAttributes) .build(); Publish messages to queues 920 Amazon Simple Notification Service Developer Guide } } // Publish the message to the topic. PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Subscribe to the SQS queue. public static String subQueue(SnsClient snsClient, String topicArn, String queueArn, List<String> filterList) { try { SubscribeRequest request; if (filterList.isEmpty()) { // No filter subscription is added. request = SubscribeRequest.builder() .protocol("sqs") .endpoint(queueArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" + "with the subscription ARN " + result.subscriptionArn()); return result.subscriptionArn(); } else { request = SubscribeRequest.builder() .protocol("sqs") .endpoint(queueArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); Publish messages to queues 921 Amazon Simple Notification
sns-dg-235
sns-dg.pdf
235
e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Subscribe to the SQS queue. public static String subQueue(SnsClient snsClient, String topicArn, String queueArn, List<String> filterList) { try { SubscribeRequest request; if (filterList.isEmpty()) { // No filter subscription is added. request = SubscribeRequest.builder() .protocol("sqs") .endpoint(queueArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" + "with the subscription ARN " + result.subscriptionArn()); return result.subscriptionArn(); } else { request = SubscribeRequest.builder() .protocol("sqs") .endpoint(queueArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); Publish messages to queues 921 Amazon Simple Notification Service Developer Guide System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" + "with the subscription ARN " + result.subscriptionArn()); String attributeName = "FilterPolicy"; Gson gson = new Gson(); String jsonString = "{\"tone\": []}"; JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); JsonArray toneArray = jsonObject.getAsJsonArray("tone"); for (String value : filterList) { toneArray.add(new JsonPrimitive(value)); } String updatedJsonString = gson.toJson(jsonObject); System.out.println(updatedJsonString); SetSubscriptionAttributesRequest attRequest = SetSubscriptionAttributesRequest.builder() .subscriptionArn(result.subscriptionArn()) .attributeName(attributeName) .attributeValue(updatedJsonString) .build(); snsClient.setSubscriptionAttributes(attRequest); return result.subscriptionArn(); } } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } // Attach a policy to the queue. public static void setQueueAttr(SqsClient sqsClient, String queueUrl, String policy) { try { Map<software.amazon.awssdk.services.sqs.model.QueueAttributeName, String> attrMap = new HashMap<>(); attrMap.put(QueueAttributeName.POLICY, policy); SetQueueAttributesRequest attributesRequest = SetQueueAttributesRequest.builder() Publish messages to queues 922 Amazon Simple Notification Service Developer Guide .queueUrl(queueUrl) .attributes(attrMap) .build(); sqsClient.setQueueAttributes(attributesRequest); System.out.println("The policy has been successfully attached."); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static String getSQSQueueAttrs(SqsClient sqsClient, String queueUrl) { // Specify the attributes to retrieve. List<QueueAttributeName> atts = new ArrayList<>(); atts.add(QueueAttributeName.QUEUE_ARN); GetQueueAttributesRequest attributesRequest = GetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributeNames(atts) .build(); GetQueueAttributesResponse response = sqsClient.getQueueAttributes(attributesRequest); Map<String, String> queueAtts = response.attributesAsStrings(); for (Map.Entry<String, String> queueAtt : queueAtts.entrySet()) return queueAtt.getValue(); return ""; } public static String createQueue(SqsClient sqsClient, String queueName, Boolean selectFIFO) { try { System.out.println("\nCreate Queue"); if (selectFIFO) { Map<QueueAttributeName, String> attrs = new HashMap<>(); attrs.put(QueueAttributeName.FIFO_QUEUE, "true"); CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(attrs) Publish messages to queues 923 Amazon Simple Notification Service Developer Guide .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); } else { CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; Publish messages to queues 924 Amazon Simple Notification Service } Developer Guide public static String createFIFO(SnsClient snsClient, String topicName, String duplication) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = new HashMap<>(); if (duplication.compareTo("n") == 0) { topicAttributes.put("FifoTopic", "true"); topicAttributes.put("ContentBasedDeduplication", "false"); } else { topicAttributes.put("FifoTopic", "true"); topicAttributes.put("ContentBasedDeduplication", "true"); } CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); return response.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish Publish messages to queues 925 Amazon Simple Notification Service Developer Guide • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe 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. This is the entry point for this scenario. import { SNSClient } from "@aws-sdk/client-sns"; import { SQSClient } from "@aws-sdk/client-sqs"; import { TopicsQueuesWkflw } from "./TopicsQueuesWkflw.js"; import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js"; export const startSnsWorkflow = () => { const snsClient = new SNSClient({}); const sqsClient = new SQSClient({}); const prompter = new Prompter(); const logger = console; const wkflw = new TopicsQueuesWkflw(snsClient, sqsClient, prompter, logger); wkflw.start(); }; The preceding code provides the necessary dependencies and starts the scenario. The next section contains the bulk of the example. Publish messages to queues 926 Amazon Simple Notification Service Developer Guide const toneChoices = [ { name: "cheerful", value: "cheerful" }, { name: "funny", value: "funny" }, { name: "serious", value: "serious" }, { name: "sincere", value: "sincere" }, ]; export class TopicsQueuesWkflw { // SNS topic is configured as First-In-First-Out isFifo = true; // Automatic content-based deduplication is enabled. autoDedup = false; snsClient; sqsClient; topicName; topicArn; subscriptionArns = []; /** * @type {{ queueName: string, queueArn: string, queueUrl: string, policy?: string }[]} */ queues = []; prompter; /** * @param {import('@aws-sdk/client-sns').SNSClient} snsClient * @param {import('@aws-sdk/client-sqs').SQSClient} sqsClient * @param {import('../../libs/prompter.js').Prompter} prompter * @param {import('../../libs/logger.js').Logger} logger */ constructor(snsClient, sqsClient, prompter, logger) { this.snsClient = snsClient; this.sqsClient = sqsClient; this.prompter = prompter; this.logger = logger; } async welcome() { await this.logger.log(MESSAGES.description); } async confirmFifo() { Publish messages to
sns-dg-236
sns-dg.pdf
236
value: "sincere" }, ]; export class TopicsQueuesWkflw { // SNS topic is configured as First-In-First-Out isFifo = true; // Automatic content-based deduplication is enabled. autoDedup = false; snsClient; sqsClient; topicName; topicArn; subscriptionArns = []; /** * @type {{ queueName: string, queueArn: string, queueUrl: string, policy?: string }[]} */ queues = []; prompter; /** * @param {import('@aws-sdk/client-sns').SNSClient} snsClient * @param {import('@aws-sdk/client-sqs').SQSClient} sqsClient * @param {import('../../libs/prompter.js').Prompter} prompter * @param {import('../../libs/logger.js').Logger} logger */ constructor(snsClient, sqsClient, prompter, logger) { this.snsClient = snsClient; this.sqsClient = sqsClient; this.prompter = prompter; this.logger = logger; } async welcome() { await this.logger.log(MESSAGES.description); } async confirmFifo() { Publish messages to queues 927 Amazon Simple Notification Service Developer Guide await this.logger.log(MESSAGES.snsFifoDescription); this.isFifo = await this.prompter.confirm({ message: MESSAGES.snsFifoPrompt, }); if (this.isFifo) { this.logger.logSeparator(MESSAGES.headerDedup); await this.logger.log(MESSAGES.deduplicationNotice); await this.logger.log(MESSAGES.deduplicationDescription); this.autoDedup = await this.prompter.confirm({ message: MESSAGES.deduplicationPrompt, }); } } async createTopic() { await this.logger.log(MESSAGES.creatingTopics); this.topicName = await this.prompter.input({ message: MESSAGES.topicNamePrompt, }); if (this.isFifo) { this.topicName += ".fifo"; this.logger.logSeparator(MESSAGES.headerFifoNaming); await this.logger.log(MESSAGES.appendFifoNotice); } const response = await this.snsClient.send( new CreateTopicCommand({ Name: this.topicName, Attributes: { FifoTopic: this.isFifo ? "true" : "false", ...(this.autoDedup ? { ContentBasedDeduplication: "true" } : {}), }, }), ); this.topicArn = response.TopicArn; await this.logger.log( MESSAGES.topicCreatedNotice .replace("${TOPIC_NAME}", this.topicName) .replace("${TOPIC_ARN}", this.topicArn), ); } Publish messages to queues 928 Amazon Simple Notification Service Developer Guide async createQueues() { await this.logger.log(MESSAGES.createQueuesNotice); // Increase this number to add more queues. const maxQueues = 2; for (let i = 0; i < maxQueues; i++) { await this.logger.log(MESSAGES.queueCount.replace("${COUNT}", i + 1)); let queueName = await this.prompter.input({ message: MESSAGES.queueNamePrompt.replace( "${EXAMPLE_NAME}", i === 0 ? "good-news" : "bad-news", ), }); if (this.isFifo) { queueName += ".fifo"; await this.logger.log(MESSAGES.appendFifoNotice); } const response = await this.sqsClient.send( new CreateQueueCommand({ QueueName: queueName, Attributes: { ...(this.isFifo ? { FifoQueue: "true" } : {}) }, }), ); const { Attributes } = await this.sqsClient.send( new GetQueueAttributesCommand({ QueueUrl: response.QueueUrl, AttributeNames: ["QueueArn"], }), ); this.queues.push({ queueName, queueArn: Attributes.QueueArn, queueUrl: response.QueueUrl, }); await this.logger.log( MESSAGES.queueCreatedNotice .replace("${QUEUE_NAME}", queueName) .replace("${QUEUE_URL}", response.QueueUrl) Publish messages to queues 929 Amazon Simple Notification Service Developer Guide .replace("${QUEUE_ARN}", Attributes.QueueArn), ); } } async attachQueueIamPolicies() { for (const [index, queue] of this.queues.entries()) { const policy = JSON.stringify( { Statement: [ { Effect: "Allow", Principal: { Service: "sns.amazonaws.com", }, Action: "sqs:SendMessage", Resource: queue.queueArn, Condition: { ArnEquals: { "aws:SourceArn": this.topicArn, }, }, }, ], }, null, 2, ); if (index !== 0) { this.logger.logSeparator(); } await this.logger.log(MESSAGES.attachPolicyNotice); console.log(policy); const addPolicy = await this.prompter.confirm({ message: MESSAGES.addPolicyConfirmation.replace( "${QUEUE_NAME}", queue.queueName, ), }); if (addPolicy) { await this.sqsClient.send( Publish messages to queues 930 Amazon Simple Notification Service Developer Guide new SetQueueAttributesCommand({ QueueUrl: queue.queueUrl, Attributes: { Policy: policy, }, }), ); queue.policy = policy; } else { await this.logger.log( MESSAGES.policyNotAttachedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } } async subscribeQueuesToTopic() { for (const [index, queue] of this.queues.entries()) { /** * @type {import('@aws-sdk/client-sns').SubscribeCommandInput} */ const subscribeParams = { TopicArn: this.topicArn, Protocol: "sqs", Endpoint: queue.queueArn, }; let tones = []; if (this.isFifo) { if (index === 0) { await this.logger.log(MESSAGES.fifoFilterNotice); } tones = await this.prompter.checkbox({ message: MESSAGES.fifoFilterSelect.replace( "${QUEUE_NAME}", queue.queueName, ), choices: toneChoices, }); if (tones.length) { Publish messages to queues 931 Amazon Simple Notification Service Developer Guide subscribeParams.Attributes = { FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ tone: tones, }), }; } } const { SubscriptionArn } = await this.snsClient.send( new SubscribeCommand(subscribeParams), ); this.subscriptionArns.push(SubscriptionArn); await this.logger.log( MESSAGES.queueSubscribedNotice .replace("${QUEUE_NAME}", queue.queueName) .replace("${TOPIC_NAME}", this.topicName) .replace("${TONES}", tones.length ? tones.join(", ") : "none"), ); } } async publishMessages() { const message = await this.prompter.input({ message: MESSAGES.publishMessagePrompt, }); let groupId; let deduplicationId; let choices; if (this.isFifo) { await this.logger.log(MESSAGES.groupIdNotice); groupId = await this.prompter.input({ message: MESSAGES.groupIdPrompt, }); if (this.autoDedup === false) { await this.logger.log(MESSAGES.deduplicationIdNotice); deduplicationId = await this.prompter.input({ message: MESSAGES.deduplicationIdPrompt, }); Publish messages to queues 932 Amazon Simple Notification Service } Developer Guide choices = await this.prompter.checkbox({ message: MESSAGES.messageAttributesPrompt, choices: toneChoices, }); } await this.snsClient.send( new PublishCommand({ TopicArn: this.topicArn, Message: message, ...(groupId ? { MessageGroupId: groupId, } : {}), ...(deduplicationId ? { MessageDeduplicationId: deduplicationId, } : {}), ...(choices ? { MessageAttributes: { tone: { DataType: "String.Array", StringValue: JSON.stringify(choices), }, }, } : {}), }), ); const publishAnother = await this.prompter.confirm({ message: MESSAGES.publishAnother, }); if (publishAnother) { await this.publishMessages(); } } Publish messages to queues 933 Amazon Simple Notification Service Developer Guide async receiveAndDeleteMessages() { for (const queue of this.queues) { const { Messages } = await this.sqsClient.send( new ReceiveMessageCommand({ QueueUrl: queue.queueUrl, }), ); if (Messages) { await this.logger.log( MESSAGES.messagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); console.log(Messages); await this.sqsClient.send( new DeleteMessageBatchCommand({ QueueUrl: queue.queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } else { await this.logger.log( MESSAGES.noMessagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } const deleteAndPoll = await this.prompter.confirm({ message: MESSAGES.deleteAndPollConfirmation, }); if (deleteAndPoll) { await this.receiveAndDeleteMessages(); } } Publish messages to queues 934 Amazon Simple Notification Service Developer Guide async destroyResources() { for (const subscriptionArn of this.subscriptionArns) { await this.snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn }), ); } for (const queue of this.queues) { await this.sqsClient.send( new DeleteQueueCommand({ QueueUrl: queue.queueUrl }), );
sns-dg-237
sns-dg.pdf
237
}), ); if (Messages) { await this.logger.log( MESSAGES.messagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); console.log(Messages); await this.sqsClient.send( new DeleteMessageBatchCommand({ QueueUrl: queue.queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } else { await this.logger.log( MESSAGES.noMessagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } const deleteAndPoll = await this.prompter.confirm({ message: MESSAGES.deleteAndPollConfirmation, }); if (deleteAndPoll) { await this.receiveAndDeleteMessages(); } } Publish messages to queues 934 Amazon Simple Notification Service Developer Guide async destroyResources() { for (const subscriptionArn of this.subscriptionArns) { await this.snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn }), ); } for (const queue of this.queues) { await this.sqsClient.send( new DeleteQueueCommand({ QueueUrl: queue.queueUrl }), ); } if (this.topicArn) { await this.snsClient.send( new DeleteTopicCommand({ TopicArn: this.topicArn }), ); } } async start() { console.clear(); try { this.logger.logSeparator(MESSAGES.headerWelcome); await this.welcome(); this.logger.logSeparator(MESSAGES.headerFifo); await this.confirmFifo(); this.logger.logSeparator(MESSAGES.headerCreateTopic); await this.createTopic(); this.logger.logSeparator(MESSAGES.headerCreateQueues); await this.createQueues(); this.logger.logSeparator(MESSAGES.headerAttachPolicy); await this.attachQueueIamPolicies(); this.logger.logSeparator(MESSAGES.headerSubscribeQueues); await this.subscribeQueuesToTopic(); this.logger.logSeparator(MESSAGES.headerPublishMessage); await this.publishMessages(); this.logger.logSeparator(MESSAGES.headerReceiveMessages); await this.receiveAndDeleteMessages(); } catch (err) { console.error(err); } finally { Publish messages to queues 935 Amazon Simple Notification Service Developer Guide await this.destroyResources(); } } } • For API details, see the following topics in AWS SDK for JavaScript API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe 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. package com.example.sns import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.CreateTopicRequest import aws.sdk.kotlin.services.sns.model.DeleteTopicRequest import aws.sdk.kotlin.services.sns.model.PublishRequest import aws.sdk.kotlin.services.sns.model.SetSubscriptionAttributesRequest import aws.sdk.kotlin.services.sns.model.SubscribeRequest Publish messages to queues 936 Amazon Simple Notification Service Developer Guide import aws.sdk.kotlin.services.sns.model.UnsubscribeRequest import aws.sdk.kotlin.services.sqs.SqsClient import aws.sdk.kotlin.services.sqs.model.CreateQueueRequest import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequest import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequestEntry import aws.sdk.kotlin.services.sqs.model.DeleteQueueRequest import aws.sdk.kotlin.services.sqs.model.GetQueueAttributesRequest import aws.sdk.kotlin.services.sqs.model.GetQueueUrlRequest import aws.sdk.kotlin.services.sqs.model.Message import aws.sdk.kotlin.services.sqs.model.QueueAttributeName import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest import aws.sdk.kotlin.services.sqs.model.SetQueueAttributesRequest import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonPrimitive import java.util.Scanner /** Before running this Kotlin code example, set up your development environment, including your AWS credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html This Kotlin example performs the following tasks: 1. Gives the user three options to choose from. 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic. 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue. 4. Gets the SQS queue Amazon Resource Name (ARN) attribute. 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue. 6. Subscribes to the SQS queue. 7. Publishes a message to the topic. 8. Displays the messages. 9. Deletes the received message. 10. Unsubscribes from the topic. 11. Deletes the SNS topic. */ val DASHES: String = String(CharArray(80)).replace("\u0000", "-") suspend fun main() { val input = Scanner(System.`in`) val useFIFO: String var duplication = "n" Publish messages to queues 937 Amazon Simple Notification Service Developer Guide var topicName: String var deduplicationID: String? = null var groupId: String? = null val topicArn: String? var sqsQueueName: String val sqsQueueUrl: String? val sqsQueueArn: String val subscriptionArn: String? var selectFIFO = false val message: String val messageList: List<Message?>? val filterList = ArrayList<String>() var msgAttValue = "" println(DASHES) println("Welcome to the AWS SDK for Kotlin messaging with topics and queues.") println( """ In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic. You can select from several options for configuring the topic and the subscriptions for the queue. You can then post to the topic and see the results in the queue. """.trimIndent(), ) println(DASHES) println(DASHES) println( """ SNS topics can be configured as FIFO (First-In-First-Out). FIFO topics deliver messages in order and support deduplication and message filtering. Would you like to work with FIFO topics? (y/n) """.trimIndent(), ) useFIFO = input.nextLine() if (useFIFO.compareTo("y") == 0) { selectFIFO = true println("You have selected FIFO") println( """ Because you have chosen a FIFO topic, deduplication is supported. Publish messages to queues 938 Amazon Simple Notification Service Developer Guide Deduplication IDs are either set in the message or automatically generated from content using a hash function. If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID, within the five-minute deduplication interval, is accepted but not delivered. For more information about deduplication, see https:// docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.""", ) println("Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)") duplication = input.nextLine() if (duplication.compareTo("y") == 0) { println("Enter a group id value") groupId = input.nextLine() } else { println("Enter deduplication Id value") deduplicationID = input.nextLine() println("Enter a group id value") groupId = input.nextLine() } } println(DASHES) println(DASHES) println("2. Create a topic.") println("Enter a name for your SNS topic.") topicName = input.nextLine() if (selectFIFO) { println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.") topicName = "$topicName.fifo" println("The name of the topic is $topicName") topicArn = createFIFO(topicName, duplication) println("The ARN of the FIFO topic is $topicArn") } else { println("The name of the topic is $topicName") topicArn = createSNSTopic(topicName) println("The ARN
sns-dg-238
sns-dg.pdf
238
{ println("Enter a group id value") groupId = input.nextLine() } else { println("Enter deduplication Id value") deduplicationID = input.nextLine() println("Enter a group id value") groupId = input.nextLine() } } println(DASHES) println(DASHES) println("2. Create a topic.") println("Enter a name for your SNS topic.") topicName = input.nextLine() if (selectFIFO) { println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.") topicName = "$topicName.fifo" println("The name of the topic is $topicName") topicArn = createFIFO(topicName, duplication) println("The ARN of the FIFO topic is $topicArn") } else { println("The name of the topic is $topicName") topicArn = createSNSTopic(topicName) println("The ARN of the non-FIFO topic is $topicArn") } println(DASHES) println(DASHES) Publish messages to queues 939 Amazon Simple Notification Service Developer Guide println("3. Create an SQS queue.") println("Enter a name for your SQS queue.") sqsQueueName = input.nextLine() if (selectFIFO) { sqsQueueName = "$sqsQueueName.fifo" } sqsQueueUrl = createQueue(sqsQueueName, selectFIFO) println("The queue URL is $sqsQueueUrl") println(DASHES) println(DASHES) println("4. Get the SQS queue ARN attribute.") sqsQueueArn = getSQSQueueAttrs(sqsQueueUrl) println("The ARN of the new queue is $sqsQueueArn") println(DASHES) println(DASHES) println("5. Attach an IAM policy to the queue.") // Define the policy to use. val policy = """{ "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "$sqsQueueArn", "Condition": { "ArnEquals": { "aws:SourceArn": "$topicArn" } } } ] }""" setQueueAttr(sqsQueueUrl, policy) println(DASHES) println(DASHES) println("6. Subscribe to the SQS queue.") if (selectFIFO) { println( Publish messages to queues 940 Amazon Simple Notification Service Developer Guide """If you add a filter to this subscription, then only the filtered messages will be received in the queue. For information about message filtering, see https://docs.aws.amazon.com/sns/ latest/dg/sns-message-filtering.html For this example, you can filter messages by a "tone" attribute.""", ) println("Would you like to filter messages for $sqsQueueName's subscription to the topic $topicName? (y/n)") val filterAns: String = input.nextLine() if (filterAns.compareTo("y") == 0) { var moreAns = false println("You can filter messages by using one or more of the following \"tone\" attributes.") println("1. cheerful") println("2. funny") println("3. serious") println("4. sincere") while (!moreAns) { println("Select a number or choose 0 to end.") val ans: String = input.nextLine() when (ans) { "1" -> filterList.add("cheerful") "2" -> filterList.add("funny") "3" -> filterList.add("serious") "4" -> filterList.add("sincere") else -> moreAns = true } } } } subscriptionArn = subQueue(topicArn, sqsQueueArn, filterList) println(DASHES) println(DASHES) println("7. Publish a message to the topic.") if (selectFIFO) { println("Would you like to add an attribute to this message? (y/n)") val msgAns: String = input.nextLine() if (msgAns.compareTo("y") == 0) { println("You can filter messages by one or more of the following \"tone\" attributes.") println("1. cheerful") println("2. funny") println("3. serious") Publish messages to queues 941 Amazon Simple Notification Service Developer Guide println("4. sincere") println("Select a number or choose 0 to end.") val ans: String = input.nextLine() msgAttValue = when (ans) { "1" -> "cheerful" "2" -> "funny" "3" -> "serious" else -> "sincere" } println("Selected value is $msgAttValue") } println("Enter a message.") message = input.nextLine() pubMessageFIFO(message, topicArn, msgAttValue, duplication, groupId, deduplicationID) } else { println("Enter a message.") message = input.nextLine() pubMessage(message, topicArn) } println(DASHES) println(DASHES) println("8. Display the message. Press any key to continue.") input.nextLine() messageList = receiveMessages(sqsQueueUrl, msgAttValue) if (messageList != null) { for (mes in messageList) { println("Message Id: ${mes.messageId}") println("Full Message: ${mes.body}") } } println(DASHES) println(DASHES) println("9. Delete the received message. Press any key to continue.") input.nextLine() if (messageList != null) { deleteMessages(sqsQueueUrl, messageList) } println(DASHES) println(DASHES) Publish messages to queues 942 Amazon Simple Notification Service Developer Guide println("10. Unsubscribe from the topic and delete the queue. Press any key to continue.") input.nextLine() unSub(subscriptionArn) deleteSQSQueue(sqsQueueName) println(DASHES) println(DASHES) println("11. Delete the topic. Press any key to continue.") input.nextLine() deleteSNSTopic(topicArn) println(DASHES) println(DASHES) println("The SNS/SQS workflow has completed successfully.") println(DASHES) } suspend fun deleteSNSTopic(topicArnVal: String?) { val request = DeleteTopicRequest { topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.deleteTopic(request) println("$topicArnVal was deleted") } } suspend fun deleteSQSQueue(queueNameVal: String) { val getQueueRequest = GetQueueUrlRequest { queueName = queueNameVal } SqsClient { region = "us-east-1" }.use { sqsClient -> val queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl val deleteQueueRequest = DeleteQueueRequest { queueUrl = queueUrlVal } sqsClient.deleteQueue(deleteQueueRequest) println("$queueNameVal was successfully deleted.") } } Publish messages to queues 943 Amazon Simple Notification Service Developer Guide suspend fun unSub(subscripArn: String?) { val request = UnsubscribeRequest { subscriptionArn = subscripArn } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.unsubscribe(request) println("Subscription was removed for $subscripArn") } } suspend fun deleteMessages(queueUrlVal: String?, messages: List<Message>) { val entriesVal: MutableList<DeleteMessageBatchRequestEntry> = mutableListOf() for (msg in messages) { val entry = DeleteMessageBatchRequestEntry { id = msg.messageId } entriesVal.add(entry) } val deleteMessageBatchRequest = DeleteMessageBatchRequest { queueUrl = queueUrlVal entries = entriesVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.deleteMessageBatch(deleteMessageBatchRequest) println("The batch delete of messages was successful") } } suspend fun receiveMessages(queueUrlVal: String?, msgAttValue: String): List<Message>? { if (msgAttValue.isEmpty()) { val request = ReceiveMessageRequest { queueUrl = queueUrlVal
sns-dg-239
sns-dg.pdf
239
{ subscriptionArn = subscripArn } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.unsubscribe(request) println("Subscription was removed for $subscripArn") } } suspend fun deleteMessages(queueUrlVal: String?, messages: List<Message>) { val entriesVal: MutableList<DeleteMessageBatchRequestEntry> = mutableListOf() for (msg in messages) { val entry = DeleteMessageBatchRequestEntry { id = msg.messageId } entriesVal.add(entry) } val deleteMessageBatchRequest = DeleteMessageBatchRequest { queueUrl = queueUrlVal entries = entriesVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.deleteMessageBatch(deleteMessageBatchRequest) println("The batch delete of messages was successful") } } suspend fun receiveMessages(queueUrlVal: String?, msgAttValue: String): List<Message>? { if (msgAttValue.isEmpty()) { val request = ReceiveMessageRequest { queueUrl = queueUrlVal maxNumberOfMessages = 5 } SqsClient { region = "us-east-1" }.use { sqsClient -> return sqsClient.receiveMessage(request).messages } } else { val receiveRequest = ReceiveMessageRequest { queueUrl = queueUrlVal Publish messages to queues 944 Amazon Simple Notification Service Developer Guide waitTimeSeconds = 1 maxNumberOfMessages = 5 } SqsClient { region = "us-east-1" }.use { sqsClient -> return sqsClient.receiveMessage(receiveRequest).messages } } } suspend fun pubMessage(messageVal: String?, topicArnVal: String?) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } } suspend fun pubMessageFIFO( messageVal: String?, topicArnVal: String?, msgAttValue: String, duplication: String, groupIdVal: String?, deduplicationID: String?, ) { // Means the user did not choose to use a message attribute. if (msgAttValue.isEmpty()) { if (duplication.compareTo("y") == 0) { val request = PublishRequest { message = messageVal messageGroupId = groupIdVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println(result.messageId.toString() + " Message sent.") } } else { val request = PublishRequest { Publish messages to queues 945 Amazon Simple Notification Service Developer Guide message = messageVal messageDeduplicationId = deduplicationID messageGroupId = groupIdVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println(result.messageId.toString() + " Message sent.") } } } else { val messAttr = aws.sdk.kotlin.services.sns.model.MessageAttributeValue { dataType = "String" stringValue = "true" } val mapAtt: Map<String, aws.sdk.kotlin.services.sns.model.MessageAttributeValue> = mapOf(msgAttValue to messAttr) if (duplication.compareTo("y") == 0) { val request = PublishRequest { message = messageVal messageGroupId = groupIdVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println(result.messageId.toString() + " Message sent.") } } else { // Create a publish request with the message and attributes. val request = PublishRequest { topicArn = topicArnVal message = messageVal messageDeduplicationId = deduplicationID messageGroupId = groupIdVal messageAttributes = mapAtt } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println(result.messageId.toString() + " Message sent.") Publish messages to queues 946 Amazon Simple Notification Service Developer Guide } } } } // Subscribe to the SQS queue. suspend fun subQueue(topicArnVal: String?, queueArnVal: String, filterList: List<String?>): String? { val request: SubscribeRequest if (filterList.isEmpty()) { // No filter subscription is added. request = SubscribeRequest { protocol = "sqs" endpoint = queueArnVal returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println( "The queue " + queueArnVal + " has been subscribed to the topic " + topicArnVal + "\n" + "with the subscription ARN " + result.subscriptionArn, ) return result.subscriptionArn } } else { request = SubscribeRequest { protocol = "sqs" endpoint = queueArnVal returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println("The queue $queueArnVal has been subscribed to the topic $topicArnVal with the subscription ARN ${result.subscriptionArn}") val attributeNameVal = "FilterPolicy" val gson = Gson() val jsonString = "{\"tone\": []}" val jsonObject = gson.fromJson(jsonString, JsonObject::class.java) Publish messages to queues 947 Amazon Simple Notification Service Developer Guide val toneArray = jsonObject.getAsJsonArray("tone") for (value: String? in filterList) { toneArray.add(JsonPrimitive(value)) } val updatedJsonString: String = gson.toJson(jsonObject) println(updatedJsonString) val attRequest = SetSubscriptionAttributesRequest { subscriptionArn = result.subscriptionArn attributeName = attributeNameVal attributeValue = updatedJsonString } snsClient.setSubscriptionAttributes(attRequest) return result.subscriptionArn } } } suspend fun setQueueAttr(queueUrlVal: String?, policy: String) { val attrMap: MutableMap<String, String> = HashMap() attrMap[QueueAttributeName.Policy.toString()] = policy val attributesRequest = SetQueueAttributesRequest { queueUrl = queueUrlVal attributes = attrMap } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.setQueueAttributes(attributesRequest) println("The policy has been successfully attached.") } } suspend fun getSQSQueueAttrs(queueUrlVal: String?): String { val atts: MutableList<QueueAttributeName> = ArrayList() atts.add(QueueAttributeName.QueueArn) val attributesRequest = GetQueueAttributesRequest { queueUrl = queueUrlVal attributeNames = atts } SqsClient { region = "us-east-1" }.use { sqsClient -> val response = sqsClient.getQueueAttributes(attributesRequest) Publish messages to queues 948 Amazon Simple Notification Service Developer Guide val mapAtts = response.attributes if (mapAtts != null) { mapAtts.forEach { entry -> println("${entry.key} : ${entry.value}") return entry.value } } } return "" } suspend fun createQueue(queueNameVal: String?, selectFIFO: Boolean): String? { println("\nCreate Queue") if (selectFIFO) { val attrs = mutableMapOf<String, String>() attrs[QueueAttributeName.FifoQueue.toString()] = "true" val createQueueRequest = CreateQueueRequest { queueName = queueNameVal
sns-dg-240
sns-dg.pdf
240
fun getSQSQueueAttrs(queueUrlVal: String?): String { val atts: MutableList<QueueAttributeName> = ArrayList() atts.add(QueueAttributeName.QueueArn) val attributesRequest = GetQueueAttributesRequest { queueUrl = queueUrlVal attributeNames = atts } SqsClient { region = "us-east-1" }.use { sqsClient -> val response = sqsClient.getQueueAttributes(attributesRequest) Publish messages to queues 948 Amazon Simple Notification Service Developer Guide val mapAtts = response.attributes if (mapAtts != null) { mapAtts.forEach { entry -> println("${entry.key} : ${entry.value}") return entry.value } } } return "" } suspend fun createQueue(queueNameVal: String?, selectFIFO: Boolean): String? { println("\nCreate Queue") if (selectFIFO) { val attrs = mutableMapOf<String, String>() attrs[QueueAttributeName.FifoQueue.toString()] = "true" val createQueueRequest = CreateQueueRequest { queueName = queueNameVal attributes = attrs } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.createQueue(createQueueRequest) println("\nGet queue url") val urlRequest = GetQueueUrlRequest { queueName = queueNameVal } val getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest) return getQueueUrlResponse.queueUrl } } else { val createQueueRequest = CreateQueueRequest { queueName = queueNameVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.createQueue(createQueueRequest) println("Get queue url") val urlRequest = GetQueueUrlRequest { queueName = queueNameVal Publish messages to queues 949 Amazon Simple Notification Service } Developer Guide val getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest) return getQueueUrlResponse.queueUrl } } } suspend fun createSNSTopic(topicName: String?): String? { val request = CreateTopicRequest { name = topicName } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.createTopic(request) return result.topicArn } } suspend fun createFIFO(topicName: String?, duplication: String): String? { val topicAttributes: MutableMap<String, String> = HashMap() if (duplication.compareTo("n") == 0) { topicAttributes["FifoTopic"] = "true" topicAttributes["ContentBasedDeduplication"] = "false" } else { topicAttributes["FifoTopic"] = "true" topicAttributes["ContentBasedDeduplication"] = "true" } val topicRequest = CreateTopicRequest { name = topicName attributes = topicAttributes } SnsClient { region = "us-east-1" }.use { snsClient -> val response = snsClient.createTopic(topicRequest) return response.topicArn } } • For API details, see the following topics in AWS SDK for Kotlin API reference. • CreateQueue • CreateTopic Publish messages to queues 950 Amazon Simple Notification Service Developer Guide • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe 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 ArgumentParser import AWSClientRuntime import AWSSNS import AWSSQS import Foundation struct ExampleCommand: ParsableCommand { @Option(help: "Name of the Amazon Region to use") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "queue-scenario", abstract: """ This example interactively demonstrates how to use Amazon Simple Notification Service (Amazon SNS) and Amazon Simple Queue Service (Amazon SQS) together to publish and receive messages using queues. """, discussion: """ Publish messages to queues 951 Amazon Simple Notification Service Developer Guide Supports filtering using a "tone" attribute. """ ) /// Prompt for an input string. Only non-empty strings are allowed. /// /// - Parameter prompt: The prompt to display. /// /// - Returns: The string input by the user. func stringRequest(prompt: String) -> String { var str: String? while str == nil { print(prompt, terminator: "") str = readLine() if str != nil && str?.count == 0 { str = nil } } return str! } /// Ask a yes/no question. /// /// - Parameter prompt: A prompt string to print. /// /// - Returns: `true` if the user answered "Y", otherwise `false`. func yesNoRequest(prompt: String) -> Bool { while true { let answer = stringRequest(prompt: prompt).lowercased() if answer == "y" || answer == "n" { return answer == "y" } } } /// Display a menu of options then request a selection. /// /// - Parameters: /// - prompt: A prompt string to display before the menu. /// - options: An array of strings giving the menu options. /// Publish messages to queues 952 Amazon Simple Notification Service Developer Guide /// - Returns: The index number of the selected option or 0 if no item was /// selected. func menuRequest(prompt: String, options: [String]) -> Int { let numOptions = options.count if numOptions == 0 { return 0 } print(prompt) for (index, value) in options.enumerated() { print("(\(index)) \(value)") } repeat { print("Enter your selection (0 - \(numOptions-1)): ", terminator: "") if let answer = readLine() { guard let answer = Int(answer) else { print("Please enter the number matching your selection.") continue } if answer >= 0 && answer < numOptions { return answer } else { print("Please enter the number matching your selection.") } } } while true } /// Ask the user too press RETURN. Accepts any input but ignores it. /// /// - Parameter prompt: The text prompt to display. func returnRequest(prompt: String) { print(prompt, terminator: "") _ = readLine() } var attrValues = [ "<none>", "cheerful", "funny", Publish messages to queues 953 Amazon Simple Notification Service Developer Guide "serious", "sincere" ] /// Ask the user to choose one of the attribute values to use as a filter. /// /// - Parameters: /// -
sns-dg-241
sns-dg.pdf
241
&& answer < numOptions { return answer } else { print("Please enter the number matching your selection.") } } } while true } /// Ask the user too press RETURN. Accepts any input but ignores it. /// /// - Parameter prompt: The text prompt to display. func returnRequest(prompt: String) { print(prompt, terminator: "") _ = readLine() } var attrValues = [ "<none>", "cheerful", "funny", Publish messages to queues 953 Amazon Simple Notification Service Developer Guide "serious", "sincere" ] /// Ask the user to choose one of the attribute values to use as a filter. /// /// - Parameters: /// - message: A message to display before the menu of values. /// - attrValues: An array of strings giving the values to choose from. /// /// - Returns: The string corresponding to the selected option. func askForFilter(message: String, attrValues: [String]) -> String? { print(message) for (index, value) in attrValues.enumerated() { print(" [\(index)] \(value)") } var answer: Int? repeat { answer = Int(stringRequest(prompt: "Select an value for the 'tone' attribute or 0 to end: ")) } while answer == nil || answer! < 0 || answer! > attrValues.count + 1 if answer == 0 { return nil } return attrValues[answer!] } /// Prompts the user for filter terms and constructs the attribute /// record that specifies them. /// /// - Returns: A mapping of "FilterPolicy" to a JSON string representing /// the user-defined filter. func buildFilterAttributes() -> [String:String] { var attr: [String:String] = [:] var filterString = "" var first = true while let ans = askForFilter(message: "Choose a value to apply to the 'tone' attribute.", attrValues: attrValues) { if !first { Publish messages to queues 954 Amazon Simple Notification Service Developer Guide filterString += "," } first = false filterString += "\"\(ans)\"" } let filterJSON = "{ \"tone\": [\(filterString)]}" attr["FilterPolicy"] = filterJSON return attr } /// Create a queue, returning its URL string. /// /// - Parameters: /// - prompt: A prompt to ask for the queue name. /// - isFIFO: Whether or not to create a FIFO queue. /// /// - Returns: The URL of the queue. func createQueue(prompt: String, sqsClient: SQSClient, isFIFO: Bool) async throws -> String? { repeat { var queueName = stringRequest(prompt: prompt) var attributes: [String: String] = [:] if isFIFO { queueName += ".fifo" attributes["FifoQueue"] = "true" } do { let output = try await sqsClient.createQueue( input: CreateQueueInput( attributes: attributes, queueName: queueName ) ) guard let url = output.queueUrl else { return nil } return url } catch _ as QueueDeletedRecently { Publish messages to queues 955 Amazon Simple Notification Service Developer Guide print("You need to use a different queue name. A queue by that name was recently deleted.") continue } } while true } /// Return the ARN of a queue given its URL. /// /// - Parameter queueUrl: The URL of the queue for which to return the /// ARN. /// /// - Returns: The ARN of the specified queue. func getQueueARN(sqsClient: SQSClient, queueUrl: String) async throws -> String? { let output = try await sqsClient.getQueueAttributes( input: GetQueueAttributesInput( attributeNames: [.queuearn], queueUrl: queueUrl ) ) guard let attributes = output.attributes else { return nil } return attributes["QueueArn"] } /// Applies the needed policy to the specified queue. /// /// - Parameters: /// - sqsClient: The Amazon SQS client to use. /// - queueUrl: The queue to apply the policy to. /// - queueArn: The ARN of the queue to apply the policy to. /// - topicArn: The topic that should have access via the policy. /// /// - Throws: Errors from the SQS `SetQueueAttributes` action. func setQueuePolicy(sqsClient: SQSClient, queueUrl: String, queueArn: String, topicArn: String) async throws { _ = try await sqsClient.setQueueAttributes( input: SetQueueAttributesInput( attributes: [ "Policy": Publish messages to queues 956 Amazon Simple Notification Service Developer Guide """ { "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "\(queueArn)", "Condition": { "ArnEquals": { "aws:SourceArn": "\(topicArn)" } } } ] } """ ], queueUrl: queueUrl ) ) } /// Receive the available messages on a queue, outputting them to the /// screen. Returns a dictionary you pass to DeleteMessageBatch to delete /// all the received messages. /// /// - Parameters: /// - sqsClient: The Amazon SQS client to use. /// - queueUrl: The SQS queue on which to receive messages. /// /// - Throws: Errors from `SQSClient.receiveMessage()` /// /// - Returns: An array of SQSClientTypes.DeleteMessageBatchRequestEntry /// items, each describing one received message in the format needed to /// delete it. func receiveAndListMessages(sqsClient: SQSClient, queueUrl: String) async throws -> [SQSClientTypes.DeleteMessageBatchRequestEntry] { let output = try await sqsClient.receiveMessage( Publish messages to queues 957 Amazon Simple Notification Service Developer Guide input: ReceiveMessageInput( maxNumberOfMessages: 10, queueUrl: queueUrl ) ) guard let messages = output.messages else { print("No messages received.") return [] } var deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry] = [] // Print out all the messages that were
sns-dg-242
sns-dg.pdf
242
queueUrl: The SQS queue on which to receive messages. /// /// - Throws: Errors from `SQSClient.receiveMessage()` /// /// - Returns: An array of SQSClientTypes.DeleteMessageBatchRequestEntry /// items, each describing one received message in the format needed to /// delete it. func receiveAndListMessages(sqsClient: SQSClient, queueUrl: String) async throws -> [SQSClientTypes.DeleteMessageBatchRequestEntry] { let output = try await sqsClient.receiveMessage( Publish messages to queues 957 Amazon Simple Notification Service Developer Guide input: ReceiveMessageInput( maxNumberOfMessages: 10, queueUrl: queueUrl ) ) guard let messages = output.messages else { print("No messages received.") return [] } var deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry] = [] // Print out all the messages that were received, including their // attributes, if any. for message in messages { print("Message ID: \(message.messageId ?? "<unknown>")") print("Receipt handle: \(message.receiptHandle ?? "<unknown>")") print("Message JSON: \(message.body ?? "<body missing>")") if message.receiptHandle != nil { deleteList.append( SQSClientTypes.DeleteMessageBatchRequestEntry( id: message.messageId, receiptHandle: message.receiptHandle ) ) } } return deleteList } /// Delete all the messages in the specified list. /// /// - Parameters: /// - sqsClient: The Amazon SQS client to use. /// - queueUrl: The SQS queue to delete messages from. /// - deleteList: A list of `DeleteMessageBatchRequestEntry` objects /// describing the messages to delete. /// /// - Throws: Errors from `SQSClient.deleteMessageBatch()`. func deleteMessageList(sqsClient: SQSClient, queueUrl: String, Publish messages to queues 958 Amazon Simple Notification Service Developer Guide deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry]) async throws { let output = try await sqsClient.deleteMessageBatch( input: DeleteMessageBatchInput(entries: deleteList, queueUrl: queueUrl) ) if let failed = output.failed { print("\(failed.count) errors occurred deleting messages from the queue.") for message in failed { print("---> Failed to delete message \(message.id ?? "<unknown ID>") with error: \(message.code ?? "<unknown>") (\(message.message ?? "..."))") } } } /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let rowOfStars = String(repeating: "*", count: 75) print(""" \(rowOfStars) Welcome to the cross-service messaging with topics and queues example. In this workflow, you'll create an SNS topic, then create two SQS queues which will be subscribed to that topic. You can specify several options for configuring the topic, as well as the queue subscriptions. You can then post messages to the topic and receive the results on the queues. \(rowOfStars)\n """ ) // 0. Create SNS and SQS clients. let snsConfig = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: snsConfig) Publish messages to queues 959 Amazon Simple Notification Service Developer Guide let sqsConfig = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: sqsConfig) // 1. Ask the user whether to create a FIFO topic. If so, ask whether // to use content-based deduplication instead of requiring a // deduplication ID. let isFIFO = yesNoRequest(prompt: "Do you want to create a FIFO topic (Y/ N)? ") var isContentBasedDeduplication = false if isFIFO { print(""" \(rowOfStars) Because you've chosen to create a FIFO topic, deduplication is supported. Deduplication IDs are either set in the message or are automatically generated from the content using a hash function. If a message is successfully published to an SNS FIFO topic, any message published and found to have the same deduplication ID (within a five-minute deduplication interval), is accepted but not delivered. For more information about deduplication, see: https://docs.aws.amazon.com/sns/latest/dg/fifo-message- dedup.html. """ ) isContentBasedDeduplication = yesNoRequest( prompt: "Use content-based deduplication instead of entering a deduplication ID (Y/N)? ") print(rowOfStars) } var topicName = stringRequest(prompt: "Enter the name of the topic to create: ") // 2. Create the topic. Append ".fifo" to the name if FIFO was Publish messages to queues 960 Amazon Simple Notification Service Developer Guide // requested, and set the "FifoTopic" attribute to "true" if so as // well. Set the "ContentBasedDeduplication" attribute to "true" if // content-based deduplication was requested. if isFIFO { topicName += ".fifo" } print("Topic name: \(topicName)") var attributes = [ "FifoTopic": (isFIFO ? "true" : "false") ] // If it's a FIFO topic with content-based deduplication, set the // "ContentBasedDeduplication" attribute. if isContentBasedDeduplication { attributes["ContentBasedDeduplication"] = "true" } // Create the topic and retrieve the ARN. let output = try await snsClient.createTopic( input: CreateTopicInput( attributes: attributes, name: topicName ) ) guard let topicArn = output.topicArn else { print("No topic ARN returned!") return } print(""" Topic '\(topicName) has been created with the topic ARN \(topicArn)." """ ) print(rowOfStars) // 3. Create an SQS queue. Append ".fifo" to the name if one of the Publish messages to queues 961 Amazon Simple Notification Service Developer Guide // FIFO topic configurations was chosen, and set "FifoQueue" to // "true" if the topic is FIFO. print(""" Next, you will create two SQS queues that will be subscribed to the topic you just created.\n """ ) let q1Url = try await createQueue(prompt: "Enter the name of the first queue: ", sqsClient: sqsClient, isFIFO: isFIFO) guard let q1Url else { print("Unable to create queue 1!") return } // 4. Get the SQS queue's ARN attribute using `GetQueueAttributes`. let q1Arn
sns-dg-243
sns-dg.pdf
243
queue. Append ".fifo" to the name if one of the Publish messages to queues 961 Amazon Simple Notification Service Developer Guide // FIFO topic configurations was chosen, and set "FifoQueue" to // "true" if the topic is FIFO. print(""" Next, you will create two SQS queues that will be subscribed to the topic you just created.\n """ ) let q1Url = try await createQueue(prompt: "Enter the name of the first queue: ", sqsClient: sqsClient, isFIFO: isFIFO) guard let q1Url else { print("Unable to create queue 1!") return } // 4. Get the SQS queue's ARN attribute using `GetQueueAttributes`. let q1Arn = try await getQueueARN(sqsClient: sqsClient, queueUrl: q1Url) guard let q1Arn else { print("Unable to get ARN of queue 1!") return } print("Got queue 1 ARN: \(q1Arn)") // 5. Attach an AWS IAM policy to the queue using // `SetQueueAttributes`. try await setQueuePolicy(sqsClient: sqsClient, queueUrl: q1Url, queueArn: q1Arn, topicArn: topicArn) // 6. Subscribe the SQS queue to the SNS topic. Set the topic ARN in // the request. Set the protocol to "sqs". Set the queue ARN to the // ARN just received in step 5. For FIFO topics, give the option to // apply a filter. A filter allows only matching messages to enter // the queue. var q1Attributes: [String:String]? = nil if isFIFO { print( """ Publish messages to queues 962 Amazon Simple Notification Service Developer Guide If you add a filter to this subscription, then only the filtered messages will be received in the queue. For information about message filtering, see https://docs.aws.amazon.com/sns/latest/dg/sns-message- filtering.html For this example, you can filter messages by a 'tone' attribute. """ ) let subPrompt = """ Would you like to filter messages for the first queue's subscription to the topic \(topicName) (Y/N)? """ if (yesNoRequest(prompt: subPrompt)) { q1Attributes = buildFilterAttributes() } } let sub1Output = try await snsClient.subscribe( input: SubscribeInput( attributes: q1Attributes, endpoint: q1Arn, protocol: "sqs", topicArn: topicArn ) ) guard let q1SubscriptionArn = sub1Output.subscriptionArn else { print("Invalid subscription ARN returned for queue 1!") return } // 7. Repeat steps 3-6 for the second queue. let q2Url = try await createQueue(prompt: "Enter the name of the second queue: ", sqsClient: sqsClient, isFIFO: isFIFO) guard let q2Url else { print("Unable to create queue 2!") Publish messages to queues 963 Amazon Simple Notification Service Developer Guide return } let q2Arn = try await getQueueARN(sqsClient: sqsClient, queueUrl: q2Url) guard let q2Arn else { print("Unable to get ARN of queue 2!") return } print("Got queue 2 ARN: \(q2Arn)") try await setQueuePolicy(sqsClient: sqsClient, queueUrl: q2Url, queueArn: q2Arn, topicArn: topicArn) var q2Attributes: [String:String]? = nil if isFIFO { let subPrompt = """ Would you like to filter messages for the second queue's subscription to the topic \(topicName) (Y/N)? """ if (yesNoRequest(prompt: subPrompt)) { q2Attributes = buildFilterAttributes() } } let sub2Output = try await snsClient.subscribe( input: SubscribeInput( attributes: q2Attributes, endpoint: q2Arn, protocol: "sqs", topicArn: topicArn ) ) guard let q2SubscriptionArn = sub2Output.subscriptionArn else { print("Invalid subscription ARN returned for queue 1!") return } // 8. Let the user publish messages to the topic, asking for a message // body for each message. Handle the types of topic correctly (SEE // MVP INFORMATION AND FIX THESE COMMENTS!!! Publish messages to queues 964 Amazon Simple Notification Service Developer Guide print("\n\(rowOfStars)\n") var first = true repeat { var publishInput = PublishInput( topicArn: topicArn ) publishInput.message = stringRequest(prompt: "Enter message text to publish: ") // If using a FIFO topic, a message group ID must be set on the // message. if isFIFO { if first { print(""" Because you're using a FIFO topic, you must set a message group ID. All messages within the same group will be received in the same order in which they were published. \n """ ) } publishInput.messageGroupId = stringRequest(prompt: "Enter a message group ID for this message: ") if !isContentBasedDeduplication { if first { print(""" Because you're not using content-based deduplication, you must enter a deduplication ID. If other messages with the same deduplication ID are published within the same deduplication interval, they will not be delivered. """ ) } publishInput.messageDeduplicationId = stringRequest(prompt: "Enter a deduplication ID for this message: ") } Publish messages to queues 965 Amazon Simple Notification Service } Developer Guide // Allow the user to add a value for the "tone" attribute if they // wish to do so. var messageAttributes: [String:SNSClientTypes.MessageAttributeValue] = [:] let attrValSelection = menuRequest(prompt: "Choose a tone to apply to this message.", options: attrValues) if attrValSelection != 0 { let val = SNSClientTypes.MessageAttributeValue(dataType: "String", stringValue: attrValues[attrValSelection]) messageAttributes["tone"] = val } publishInput.messageAttributes = messageAttributes // Publish the message and display its ID. let publishOutput = try await snsClient.publish(input: publishInput) guard let messageID = publishOutput.messageId else { print("Unable to get the published message's ID!") return } print("Message published with ID \(messageID).") first = false // 9. Repeat step 8 until the user
sns-dg-244
sns-dg.pdf
244
to add a value for the "tone" attribute if they // wish to do so. var messageAttributes: [String:SNSClientTypes.MessageAttributeValue] = [:] let attrValSelection = menuRequest(prompt: "Choose a tone to apply to this message.", options: attrValues) if attrValSelection != 0 { let val = SNSClientTypes.MessageAttributeValue(dataType: "String", stringValue: attrValues[attrValSelection]) messageAttributes["tone"] = val } publishInput.messageAttributes = messageAttributes // Publish the message and display its ID. let publishOutput = try await snsClient.publish(input: publishInput) guard let messageID = publishOutput.messageId else { print("Unable to get the published message's ID!") return } print("Message published with ID \(messageID).") first = false // 9. Repeat step 8 until the user says they don't want to post // another. } while (yesNoRequest(prompt: "Post another message (Y/N)? ")) // 10. Display a list of the messages in each queue by using // `ReceiveMessage`. Show at least the body and the attributes. print(rowOfStars) print("Contents of queue 1:") let q1DeleteList = try await receiveAndListMessages(sqsClient: sqsClient, queueUrl: q1Url) print("\n\nContents of queue 2:") Publish messages to queues 966 Amazon Simple Notification Service Developer Guide let q2DeleteList = try await receiveAndListMessages(sqsClient: sqsClient, queueUrl: q2Url) print(rowOfStars) returnRequest(prompt: "\nPress return to clean up: ") // 11. Delete the received messages using `DeleteMessageBatch`. print("Deleting the messages from queue 1...") try await deleteMessageList(sqsClient: sqsClient, queueUrl: q1Url, deleteList: q1DeleteList) print("\nDeleting the messages from queue 2...") try await deleteMessageList(sqsClient: sqsClient, queueUrl: q2Url, deleteList: q2DeleteList) // 12. Unsubscribe and delete both queues. print("\nUnsubscribing from queue 1...") _ = try await snsClient.unsubscribe( input: UnsubscribeInput(subscriptionArn: q1SubscriptionArn) ) print("Unsubscribing from queue 2...") _ = try await snsClient.unsubscribe( input: UnsubscribeInput(subscriptionArn: q2SubscriptionArn) ) print("Deleting queue 1...") _ = try await sqsClient.deleteQueue( input: DeleteQueueInput(queueUrl: q1Url) ) print("Deleting queue 2...") _ = try await sqsClient.deleteQueue( input: DeleteQueueInput(queueUrl: q2Url) ) // 13. Delete the topic. print("Deleting the SNS topic...") _ = try await snsClient.deleteTopic( input: DeleteTopicInput(topicArn: topicArn) ) } Publish messages to queues 967 Amazon Simple Notification Service Developer Guide } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } } • For API details, see the following topics in AWS SDK for Swift API reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish messages to queues 968 Amazon Simple Notification Service Developer Guide Use API Gateway to invoke a Lambda function The following code examples show how to create an AWS Lambda function invoked by Amazon API Gateway. Java SDK for Java 2.x Shows how to create an AWS Lambda function by using the Lambda Java runtime API. This example invokes different AWS services to perform a specific use case. This example demonstrates how to create a Lambda function invoked by Amazon API Gateway that scans an Amazon DynamoDB table for work anniversaries and uses Amazon Simple Notification Service (Amazon SNS) to send a text message to your employees that congratulates them at their one year anniversary date. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon SNS JavaScript SDK for JavaScript (v3) Shows how to create an AWS Lambda function by using the Lambda JavaScript runtime API. This example invokes different AWS services to perform a specific use case. This example demonstrates how to create a Lambda function invoked by Amazon API Gateway that scans an Amazon DynamoDB table for work anniversaries and uses Amazon Simple Notification Service (Amazon SNS) to send a text message to your employees that congratulates them at their one year anniversary date. For complete source code and instructions on how to set up and run, see the full example on GitHub. Use API Gateway to invoke a Lambda function 969 Amazon Simple Notification Service Developer Guide This example is also available in the AWS SDK for JavaScript v3 developer guide. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon SNS Python SDK for Python (Boto3) This example shows how to create and use an Amazon API Gateway REST API that targets an AWS Lambda function. The Lambda handler demonstrates how to route based on HTTP methods; how to get data from the query string, header, and body; and how to return a JSON response. • Deploy a Lambda function. • Create an API Gateway REST API. • Create a REST resource that targets the Lambda function. • Grant permission to let API Gateway invoke the Lambda function. • Use the
sns-dg-245
sns-dg.pdf
245
• API Gateway • DynamoDB • Lambda • Amazon SNS Python SDK for Python (Boto3) This example shows how to create and use an Amazon API Gateway REST API that targets an AWS Lambda function. The Lambda handler demonstrates how to route based on HTTP methods; how to get data from the query string, header, and body; and how to return a JSON response. • Deploy a Lambda function. • Create an API Gateway REST API. • Create a REST resource that targets the Lambda function. • Grant permission to let API Gateway invoke the Lambda function. • Use the Requests package to send requests to the REST API. • Clean up all resources created during the demo. This example is best viewed on GitHub. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon SNS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use API Gateway to invoke a Lambda function 970 Amazon Simple Notification Service Developer Guide Use scheduled events to invoke a Lambda function The following code examples show how to create an AWS Lambda function invoked by an Amazon EventBridge scheduled event. Java SDK for Java 2.x Shows how to create an Amazon EventBridge scheduled event that invokes an AWS Lambda function. Configure EventBridge to use a cron expression to schedule when the Lambda function is invoked. In this example, you create a Lambda function by using the Lambda Java runtime API. This example invokes different AWS services to perform a specific use case. This example demonstrates how to create an app that sends a mobile text message to your employees that congratulates them at the one year anniversary date. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • CloudWatch Logs • DynamoDB • EventBridge • Lambda • Amazon SNS JavaScript SDK for JavaScript (v3) Shows how to create an Amazon EventBridge scheduled event that invokes an AWS Lambda function. Configure EventBridge to use a cron expression to schedule when the Lambda function is invoked. In this example, you create a Lambda function by using the Lambda JavaScript runtime API. This example invokes different AWS services to perform a specific use case. This example demonstrates how to create an app that sends a mobile text message to your employees that congratulates them at the one year anniversary date. For complete source code and instructions on how to set up and run, see the full example on GitHub. Use scheduled events to invoke a Lambda function 971 Amazon Simple Notification Service Developer Guide This example is also available in the AWS SDK for JavaScript v3 developer guide. Services used in this example • CloudWatch Logs • DynamoDB • EventBridge • Lambda • Amazon SNS Python SDK for Python (Boto3) This example shows how to register an AWS Lambda function as the target of a scheduled Amazon EventBridge event. The Lambda handler writes a friendly message and the full event data to Amazon CloudWatch Logs for later retrieval. • Deploys a Lambda function. • Creates an EventBridge scheduled event and makes the Lambda function the target. • Grants permission to let EventBridge invoke the Lambda function. • Prints the latest data from CloudWatch Logs to show the result of the scheduled invocations. • Cleans up all resources created during the demo. This example is best viewed on GitHub. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • CloudWatch Logs • DynamoDB • EventBridge • Lambda • Amazon SNS Use scheduled events to invoke a Lambda function 972 Amazon Simple Notification Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Serverless examples for Amazon SNS The following code examples show how to use Amazon SNS with AWS SDKs. Examples • Invoke a Lambda function from an Amazon SNS trigger Invoke a Lambda function from an Amazon SNS trigger The following code examples show how to implement a Lambda function that receives an event triggered by receiving messages from an SNS topic. The function retrieves the messages from the event parameter and logs the content of each message. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the
sns-dg-246
sns-dg.pdf
246
Serverless examples for Amazon SNS The following code examples show how to use Amazon SNS with AWS SDKs. Examples • Invoke a Lambda function from an Amazon SNS trigger Invoke a Lambda function from an Amazon SNS trigger The following code examples show how to implement a Lambda function that receives an event triggered by receiving messages from an SNS topic. The function retrieves the messages from the event parameter and logs the content of each message. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an SNS event with Lambda using .NET. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] Serverless examples 973 Amazon Simple Notification Service Developer Guide namespace SnsIntegration; public class Function { public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach (var record in evnt.Records) { await ProcessRecordAsync(record, context); } context.Logger.LogInformation("done"); } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { try { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } } Invoke a Lambda function from an Amazon SNS trigger 974 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 Serverless examples repository. Consuming an SNS event with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handler(ctx context.Context, snsEvent events.SNSEvent) { for _, record := range snsEvent.Records { processMessage(record) } fmt.Println("done") } func processMessage(record events.SNSEventRecord) { message := record.SNS.Message fmt.Printf("Processed message: %s\n", message) // TODO: Process your record here } func main() { lambda.Start(handler) } Invoke a Lambda function from an Amazon SNS trigger 975 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 Serverless examples repository. Consuming an SNS event with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SNSEvent; import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord; import java.util.Iterator; import java.util.List; public class SNSEventHandler implements RequestHandler<SNSEvent, Boolean> { LambdaLogger logger; @Override public Boolean handleRequest(SNSEvent event, Context context) { logger = context.getLogger(); List<SNSRecord> records = event.getRecords(); if (!records.isEmpty()) { Iterator<SNSRecord> recordsIter = records.iterator(); while (recordsIter.hasNext()) { processRecord(recordsIter.next()); } } return Boolean.TRUE; } public void processRecord(SNSRecord record) { Invoke a Lambda function from an Amazon SNS trigger 976 Amazon Simple Notification Service try { Developer Guide String message = record.getSNS().getMessage(); logger.log("message: " + message); } catch (Exception e) { throw new RuntimeException(e); } } } 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 Serverless examples repository. Consuming an SNS event with Lambda using JavaScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { for (const record of event.Records) { await processMessageAsync(record); } console.info("done"); }; async function processMessageAsync(record) { try { const message = JSON.stringify(record.Sns.Message); console.log(`Processed message ${message}`); await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); Invoke a Lambda function from an Amazon SNS trigger 977 Amazon Simple Notification Service throw err; } } Developer Guide Consuming an SNS event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SNSEvent, Context, SNSHandler, SNSEventRecord } from "aws-lambda"; export const functionHandler: SNSHandler = async ( event: SNSEvent, context: Context ): Promise<void> => { for (const record of event.Records) { await processMessageAsync(record); } console.info("done"); }; async function processMessageAsync(record: SNSEventRecord): Promise<any> { try { const message: string = JSON.stringify(record.Sns.Message); console.log(`Processed message ${message}`); await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } } PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Invoke a Lambda function from an Amazon SNS trigger 978 Amazon Simple Notification Service Developer Guide Consuming an SNS event with Lambda using PHP. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php /* Since native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda. For more information on
sns-dg-247
sns-dg.pdf
247
} catch (err) { console.error("An error occurred"); throw err; } } PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Invoke a Lambda function from an Amazon SNS trigger 978 Amazon Simple Notification Service Developer Guide Consuming an SNS event with Lambda using PHP. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php /* Since native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda. For more information on Bref's PHP runtime for Lambda, refer to: https://bref.sh/ docs/runtimes/function Another approach would be to create a custom runtime. A practical example can be found here: https://aws.amazon.com/blogs/apn/aws- lambda-custom-runtime-for-php-a-practical-example/ */ // Additional composer packages may be required when using Bref or any other PHP functions runtime. // require __DIR__ . '/vendor/autoload.php'; use Bref\Context\Context; use Bref\Event\Sns\SnsEvent; use Bref\Event\Sns\SnsHandler; class Handler extends SnsHandler { public function handleSns(SnsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $message = $record->getMessage(); // TODO: Implement your custom processing logic here // Any exception thrown will be logged and the invocation will be marked as failed echo "Processed Message: $message" . PHP_EOL; } } } return new Handler(); Invoke a Lambda function from an Amazon SNS trigger 979 Amazon Simple Notification Service Developer Guide 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 Serverless examples repository. Consuming an SNS event with Lambda using Python. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def lambda_handler(event, context): for record in event['Records']: process_message(record) print("done") def process_message(record): try: message = record['Sns']['Message'] print(f"Processed message {message}") # TODO; Process your record here except Exception as e: print("An error occurred") raise e Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Invoke a Lambda function from an Amazon SNS trigger 980 Amazon Simple Notification Service Developer Guide Consuming an SNS event with Lambda using Ruby. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def lambda_handler(event:, context:) event['Records'].map { |record| process_message(record) } end def process_message(record) message = record['Sns']['Message'] puts("Processing message: #{message}") rescue StandardError => e puts("Error processing message: #{e}") raise end Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an SNS event with Lambda using Rust. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use aws_lambda_events::event::sns::SnsEvent; use aws_lambda_events::sns::SnsRecord; use lambda_runtime::{run, service_fn, Error, LambdaEvent}; use tracing::info; // Built with the following dependencies: // aws_lambda_events = { version = "0.10.0", default-features = false, features = ["sns"] } // lambda_runtime = "0.8.1" // tokio = { version = "1", features = ["macros"] } Invoke a Lambda function from an Amazon SNS trigger 981 Amazon Simple Notification Service Developer Guide // tracing = { version = "0.1", features = ["log"] } // tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] } async fn function_handler(event: LambdaEvent<SnsEvent>) -> Result<(), Error> { for event in event.payload.records { process_record(&event)?; } Ok(()) } fn process_record(record: &SnsRecord) -> Result<(), Error> { info!("Processing SNS Message: {}", record.sns.message); // Implement your record handling code here. Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .with_target(false) .without_time() .init(); run(service_fn(function_handler)).await } For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Invoke a Lambda function from an Amazon SNS trigger 982 Amazon Simple Notification Service Developer Guide Amazon SNS security The AWS shared responsibility model applies to data protection in Amazon Simple Notification Service. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. This content includes the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the Data Privacy FAQ. For information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. For data protection purposes, we recommend that you protect AWS account credentials and set up individual user accounts with AWS Identity and Access Management (IAM). That way each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: • Use multi-factor authentication (MFA) with each account. • Use SSL/TLS to
sns-dg-248
sns-dg.pdf
248
that you use. For more information about data privacy, see the Data Privacy FAQ. For information about data protection in Europe, see the AWS Shared Responsibility Model and GDPR blog post on the AWS Security Blog. For data protection purposes, we recommend that you protect AWS account credentials and set up individual user accounts with AWS Identity and Access Management (IAM). That way each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways: • Use multi-factor authentication (MFA) with each account. • Use SSL/TLS to communicate with AWS resources. We recommend TLS 1.2 or later. • Set up API and user activity logging with AWS CloudTrail. • Use AWS encryption solutions, along with all default security controls within AWS services. • Use advanced managed security services such as Amazon Macie, which assists in discovering and securing personal data that is stored in Amazon S3. • If you require FIPS 140-2 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see Federal Information Processing Standard (FIPS) 140-2. • Message data protection • Message data protection is a new major feature of Amazon SNS • Use MDP to scan message for confidential or sensitive information • Provide message auditing to all content flowing through the topic • Provide content access controls to messages published to the topic and messages delivered by the topic 983 Amazon Simple Notification Service Developer Guide Important We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form fields such as a Name field. This includes when you work with Amazon SNS or other Amazon Web Services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server. Amazon SNS data encryption Data protection refers to protecting data while in-transit (as it travels to and from Amazon SNS) and at rest (while it is stored on disks in Amazon SNS data centers). You can protect data in transit using Secure Sockets Layer (SSL) or client-side encryption. By default, Amazon SNS stores messages and files using disk encryption. You can protect data at rest by requesting Amazon SNS to encrypt your messages before saving them to the encrypted file system in its data centers. Amazon SNS recommends using SSE for optimized data encryption. Securing Amazon SNS data with server-side encryption Server-side encryption (SSE) lets you store sensitive data in encrypted topics by protecting the contents of messages in Amazon SNS topics using keys managed in AWS Key Management Service (AWS KMS). SSE encrypts messages as soon as Amazon SNS receives them. The messages are stored in encrypted form, and only decrypted when they are sent. • For information about managing SSE using the AWS Management Console or the AWS SDK for Java (by setting the KmsMasterKeyId attribute using the CreateTopic and SetTopicAttributes API actions), see Setting up Amazon SNS topic encryption with server- side encryption. • For information about creating encrypted topics using AWS CloudFormation (by setting the KmsMasterKeyId property using the AWS::SNS::Topic resource), see the AWS CloudFormation User Guide. Data encryption 984 Amazon Simple Notification Service Developer Guide Important All requests to topics with SSE enabled must use HTTPS and Signature Version 4. For information about compatibility of other services with encrypted topics, see your service documentation. Amazon SNS only supports symmetric encryption KMS keys. You cannot use any other type of KMS key to encrypt your service resources. For help determining whether a KMS key is a symmetric encryption key, see Identifying asymmetric KMS keys. AWS KMS combines secure, highly available hardware and software to provide a key management system scaled for the cloud. When you use Amazon SNS with AWS KMS, the data keys that encrypt your message data are also encrypted and stored with the data they protect. The following are benefits of using AWS KMS: • You can create and manage the AWS KMS key yourself. • You can also use AWS-managed KMS keys for Amazon SNS, which are unique for each account and region. • The AWS KMS security standards can help you meet encryption-related compliance requirements. For more information, see What is AWS Key Management Service? in the AWS Key Management Service Developer Guide. Encryption scope SSE encrypts the body of a message in an Amazon SNS topic. SSE doesn't encrypt the following: • Topic metadata (topic name and attributes) • Message
sns-dg-249
sns-dg.pdf
249
data they protect. The following are benefits of using AWS KMS: • You can create and manage the AWS KMS key yourself. • You can also use AWS-managed KMS keys for Amazon SNS, which are unique for each account and region. • The AWS KMS security standards can help you meet encryption-related compliance requirements. For more information, see What is AWS Key Management Service? in the AWS Key Management Service Developer Guide. Encryption scope SSE encrypts the body of a message in an Amazon SNS topic. SSE doesn't encrypt the following: • Topic metadata (topic name and attributes) • Message metadata (subject, message ID, timestamp, and attributes) • Data protection policy • Per-topic metrics Securing data with server-side encryption 985 Amazon Simple Notification Service Developer Guide Note • A message is encrypted only if it is sent after the encryption of a topic is enabled. Amazon SNS doesn't encrypt backlogged messages. • Any encrypted message remains encrypted even if the encryption of its topic is disabled. Key terms The following key terms can help you better understand the functionality of SSE. For detailed descriptions, see the Amazon Simple Notification Service API Reference. Data key The data encryption key (DEK) responsible for encrypting the contents of Amazon SNS messages. For more information, see Data Keys in the AWS Key Management Service Developer Guide and Envelope Encryption in the AWS Encryption SDK Developer Guide. AWS KMS key ID The alias, alias ARN, key ID, or key ARN of an AWS KMS key, or a custom AWS KMS—in your account or in another account. While the alias of the AWS managed AWS KMS for Amazon SNS is always alias/aws/sns, the alias of a custom AWS KMS can, for example, be alias/MyAlias. You can use these AWS KMS keys to protect the messages in Amazon SNS topics. Note Keep the following in mind: • The first time you use the AWS Management Console to specify the AWS managed KMS for Amazon SNS for a topic, AWS KMS creates the AWS managed KMS for Amazon SNS. • Alternatively, the first time you use the Publish action on a topic with SSE enabled, AWS KMS creates the AWS managed KMS for Amazon SNS. Securing data with server-side encryption 986 Amazon Simple Notification Service Developer Guide You can create AWS KMS keys, define the policies that control how AWS KMS keys can be used, and audit AWS KMS usage using the AWS KMS keys section of the AWS KMS console or the CreateKey AWS KMS action. For more information, see AWS KMS keys and Creating Keys in the AWS Key Management Service Developer Guide. For more examples of AWS KMS identifiers, see KeyId in the AWS Key Management Service API Reference. For information about finding AWS KMS identifiers, see Find the Key ID and ARN in the AWS Key Management Service Developer Guide. Important There are additional charges for using AWS KMS. For more information, see Estimating AWS KMS costs and AWS Key Management Service Pricing. Managing Amazon SNS encryption keys and costs The following sections provide information about working with keys managed in AWS Key Management Service (AWS KMS). Note Amazon SNS only supports symmetric encryption KMS keys. You cannot use any other type of KMS key to encrypt your service resources. For help determining whether a KMS key is a symmetric encryption key, see Identifying asymmetric KMS keys. Estimating AWS KMS costs To predict costs and better understand your AWS bill, you might want to know how often Amazon SNS uses your AWS KMS key. Note Although the following formula can give you a very good idea of expected costs, actual costs might be higher because of the distributed nature of Amazon SNS. To calculate the number of API requests (R) per topic, use the following formula: Key management 987 Amazon Simple Notification Service Developer Guide R = B / D * (2 * P) B is the billing period (in seconds). D is the data key reuse period (in seconds—Amazon SNS reuses a data key for up to 5 minutes). P is the number of publishing principals that send to the Amazon SNS topic. The following are example calculations. For exact pricing information, see AWS Key Management Service Pricing. Example 1: Calculating the number of AWS KMS API calls for 1 publisher and 1 topic This example assumes the following: • The billing period is January 1-31 (2,678,400 seconds). • The data key reuse period is 5 minutes (300 seconds). • There is 1 topic. • There is 1 publishing principal. 2,678,400 / 300 * (2 * 1) = 17,856 Example 2: Calculating the number of AWS KMS API calls for multiple publishers and 2 topics This example assumes the following: • The billing period is February 1-28 (2,419,200 seconds). • The data key
sns-dg-250
sns-dg.pdf
250
AWS Key Management Service Pricing. Example 1: Calculating the number of AWS KMS API calls for 1 publisher and 1 topic This example assumes the following: • The billing period is January 1-31 (2,678,400 seconds). • The data key reuse period is 5 minutes (300 seconds). • There is 1 topic. • There is 1 publishing principal. 2,678,400 / 300 * (2 * 1) = 17,856 Example 2: Calculating the number of AWS KMS API calls for multiple publishers and 2 topics This example assumes the following: • The billing period is February 1-28 (2,419,200 seconds). • The data key reuse period is 5 minutes (300 seconds). • There are 2 topics. • The first topic has 3 publishing principals. • The second topic has 5 publishing principals. (2,419,200 / 300 * (2 * 3)) + (2,419,200 / 300 * (2 * 5)) = 129,024 Key management 988 Amazon Simple Notification Service Developer Guide Configuring AWS KMS permissions Before you can use SSE, you must configure AWS KMS key policies to allow encryption of topics and encryption and decryption of messages. For examples and more information about AWS KMS permissions, see AWS KMS API Permissions: Actions and Resources Reference in the AWS Key Management Service Developer Guide. For details on how to set up an Amazon SNS topic with server-side encryption, see Additional information. Note You can also manage permissions for symmetric encryption KMS keys using IAM policies. For more information, see Using IAM Policies with AWS KMS. While you can configure global permissions to send to and receive from Amazon SNS, AWS KMS requires explicitly naming the full ARN of KMSs in specific regions in the Resource section of an IAM policy. You must also ensure that the key policies of the AWS KMS key allow the necessary permissions. To do this, name the principals that produce and consume encrypted messages in Amazon SNS as users in the KMS key policy. Alternatively, you can specify the required AWS KMS actions and KMS ARN in an IAM policy assigned to the principals that publish and subscribe to receive encrypted messages in Amazon SNS. For more information, see Managing Access to AWS KMS in the AWS Key Management Service Developer Guide. If selecting a customer-managed key for your Amazon SNS topic and you are using aliases to control access to KMS keys using IAM policies or KMS key policies with the condition key kms:ResourceAliases, ensure that the customer-managed key that is selected also has an alias associated. For more information on using alias to control access to KMS keys, see Using aliases to control access to KMS keys in the AWS Key Management Service Developer Guide. Allow a user to send messages to a topic with SSE The publisher must have the kms:GenerateDataKey* and kms:Decrypt permissions for the AWS KMS key. { Key management 989 Developer Guide Amazon Simple Notification Service "Statement": [{ "Effect": "Allow", "Action": [ "kms:GenerateDataKey*", "kms:Decrypt" ], "Resource": "arn:aws:kms:us- east-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" }, { "Effect": "Allow", "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:*:123456789012:MyTopic" }] } Enable compatibility between event sources from AWS services and encrypted topics Several AWS services publish events to Amazon SNS topics. To allow these event sources to work with encrypted topics, you must perform the following steps. 1. Use a customer managed key. For more information, see Creating Keys in the AWS Key Management Service Developer Guide. 2. To allow the AWS service to have the kms:GenerateDataKey* and kms:Decrypt permissions, add the following statement to the KMS policy. { "Statement": [{ "Effect": "Allow", "Principal": { "Service": "service.amazonaws.com" }, "Action": [ "kms:GenerateDataKey*", "kms:Decrypt" ], "Resource": "*" }] } Key management 990 Amazon Simple Notification Service Developer Guide Event source Service principal Amazon CloudWatch cloudwatch.amazonaws.com Amazon CloudWatch Events events.amazonaws.com AWS CodeCommit codecommit.amazonaws.com AWS Database Migration Service dms.amazonaws.com AWS Directory Service ds.amazonaws.com Amazon DynamoDB dynamodb.amazonaws.com Amazon Inspector Amazon Redshift Amazon RDS inspector.amazonaws.com redshift.amazonaws.com events.rds.amazonaws.com Amazon S3 Glacier glacier.amazonaws.com Amazon Simple Email Service ses.amazonaws.com Amazon Simple Storage Service s3.amazonaws.com AWS Snowball Edge importexport.amazonaws.com AWS Systems Manager Incident Manager AWS Systems Manager Incident Manager consists of two service principles: ssm-incidents.amazonaws.com ; ssm-contacts.amazonaws.com Note Some Amazon SNS event sources require you to provide an IAM role (rather than the service principal) in the AWS KMS key policy: • Amazon EC2 Auto Scaling Key management 991 Amazon Simple Notification Service Developer Guide • Amazon Elastic Transcoder • AWS CodePipeline • AWS Config • AWS Elastic Beanstalk • AWS IoT • EC2 Image Builder 3. Add the aws:SourceAccount and aws:SourceArn condition keys to the KMS resource policy to further protect the KMS key from confused deputy attacks. Refer to service specific documentation list (above) for exact details in each case. Important Adding the aws:SourceAccount, aws:SourceArn, and aws:SourceOrgID to a AWS KMS policy is not supported for EventBridge-to-encrypted topics. { "Effect": "Allow", "Principal": { "Service": "service.amazonaws.com"
sns-dg-251
sns-dg.pdf
251
AWS KMS key policy: • Amazon EC2 Auto Scaling Key management 991 Amazon Simple Notification Service Developer Guide • Amazon Elastic Transcoder • AWS CodePipeline • AWS Config • AWS Elastic Beanstalk • AWS IoT • EC2 Image Builder 3. Add the aws:SourceAccount and aws:SourceArn condition keys to the KMS resource policy to further protect the KMS key from confused deputy attacks. Refer to service specific documentation list (above) for exact details in each case. Important Adding the aws:SourceAccount, aws:SourceArn, and aws:SourceOrgID to a AWS KMS policy is not supported for EventBridge-to-encrypted topics. { "Effect": "Allow", "Principal": { "Service": "service.amazonaws.com" }, "Action": [ "kms:GenerateDataKey*", "kms:Decrypt" ], "Resource": "*", "Condition": { "StringEquals": { "aws:SourceAccount": "customer-account-id" }, "ArnLike": { "aws:SourceArn": "arn:aws:service:region:customer-account-id:resource- type:customer-resource-id" } } } 4. Enable SSE for your topic using your KMS. Key management 992 Amazon Simple Notification Service Developer Guide 5. Provide the ARN of the encrypted topic to the event source. AWS KMS errors When you work with Amazon SNS and AWS KMS, you might encounter errors. The following list describes the errors and possible troubleshooting solutions. KMSAccessDeniedException The ciphertext references a key that doesn't exist or that you don't have access to. HTTP Status Code: 400 KMSDisabledException The request was rejected because the specified KMS isn't enabled. HTTP Status Code: 400 KMSInvalidStateException The request was rejected because the state of the specified resource isn't valid for this request. For more information, see Key states of AWS KMS keys in the AWS Key Management Service Developer Guide. HTTP Status Code: 400 KMSNotFoundException The request was rejected because the specified entity or resource can't be found. HTTP Status Code: 400 KMSOptInRequired The AWS access key ID needs a subscription for the service. HTTP Status Code: 403 KMSThrottlingException The request was denied due to request throttling. For more information about throttling, see Quotas in the AWS Key Management Service Developer Guide. HTTP Status Code: 400 Key management 993 Amazon Simple Notification Service Developer Guide Setting up Amazon SNS topic encryption with server-side encryption Amazon SNS supports server-side encryption (SSE) to protect the contents of messages using AWS Key Management Service (AWS KMS). Follow the instructions below to enable SSE using the Amazon SNS console or CDK. Option 1: Enable encryption using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. Navigate to the Topics page, select your topic, and choose Edit. 3. Expand the Encryption section and do the following: • Toggle encryption to Enable. • Select the AWS managed SNS Key (alias/aws/sns) as the encryption key. This is selected by default. 4. Choose Save changes. Note • The AWS managed key is automatically created if it doesn’t already exist. • If you don’t see the key or have insufficient permissions, ask your administrator for kms:ListAliases and kms:DescribeKey. Option 2: Enable encryption using AWS CDK To use the AWS managed SNS key in your CDK application, add the following snippet: import software.amazon.awscdk.services.sns.*; import software.amazon.awscdk.services.kms.*; import software.amazon.awscdk.core.*; public class SnsEncryptionExample extends Stack { public SnsEncryptionExample(final Construct scope, final String id) { super(scope, id); // Define the managed SNS key IKey snsKey = Alias.fromAliasName(this, "helloKey", "alias/aws/sns"); Setting up topic encryption with server-side encryption 994 Amazon Simple Notification Service Developer Guide // Create the SNS Topic with encryption enabled Topic.Builder.create(this, "MyEncryptedTopic") .masterKey(snsKey) .build(); } } Additional information • Custom KMS key – You can specify a custom key if required. In the Amazon SNS console, select your custom KMS key from the list or enter the ARN. • Permissions for custom KMS keys – If using a custom KMS key, include the following in the key policy to allow Amazon SNS to encrypt and decrypt messages: { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "*", "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:service:region:customer-account-id:resource- type/customer-resource-id" }, "StringEquals": { "kms:EncryptionContext:aws:sns:topicArn": "arn:aws:sns:your_region:customer-account-id:your_sns_topic_name" } } } Impact on consumers Enabling SSE does not change how subscribers consume messages. AWS manages encryption and decryption transparently. Messages remain encrypted at rest and are automatically decrypted Setting up topic encryption with server-side encryption 995 Amazon Simple Notification Service Developer Guide before delivery to subscribers. For optimal security, AWS recommends enabling HTTPS for all endpoints to ensure secure transmission of messages. Setting up Amazon SNS topic encryption with encrypted Amazon SQS queue subscription You can enable server-side encryption (SSE) for a topic to protect its data. To allow Amazon SNS to send messages to encrypted Amazon SQS queues, the customer managed key associated with the Amazon SQS queue must have a policy statement that grants Amazon SNS service-principal access to the AWS KMS API actions GenerateDataKey and Decrypt. For more information about using SSE, see Securing Amazon SNS data with server-side encryption. This topic explains how to enable SSE for an Amazon SNS topic with an encrypted Amazon SQS queue subscription using the
sns-dg-252
sns-dg.pdf
252
Amazon SNS topic encryption with encrypted Amazon SQS queue subscription You can enable server-side encryption (SSE) for a topic to protect its data. To allow Amazon SNS to send messages to encrypted Amazon SQS queues, the customer managed key associated with the Amazon SQS queue must have a policy statement that grants Amazon SNS service-principal access to the AWS KMS API actions GenerateDataKey and Decrypt. For more information about using SSE, see Securing Amazon SNS data with server-side encryption. This topic explains how to enable SSE for an Amazon SNS topic with an encrypted Amazon SQS queue subscription using the AWS Management Console. Step 1: Create a custom KMS key 1. Sign in to the AWS KMS console with a user that has at least the AWSKeyManagementServicePowerUser policy. 2. Choose Create a key. 3. To create a symmetric encryption KMS key, for Key type choose Symmetric. For information about how to create an asymmetric KMS key in the AWS KMS console, see Creating asymmetric KMS keys (console). 4. In Key usage, the Encrypt and decrypt option is selected for you. For information about how to create KMS keys that generate and verify MAC codes, see Creating HMAC KMS keys. For information about the Advanced options, see Special-purpose keys. 5. Choose Next. 6. Type an alias for the KMS key. The alias name cannot begin with aws/. The aws/ prefix is reserved by Amazon Web Services to represent AWS managed keys in your account. Setting up topic encryption with encrypted Amazon SQS queue subscription 996 Amazon Simple Notification Service Developer Guide Note Adding, deleting, or updating an alias can allow or deny permission to the KMS key. For details, see ABAC for AWS KMS and Using aliases to control access to KMS keys. An alias is a display name that you can use to identify the KMS key. We recommend that you choose an alias that indicates the type of data you plan to protect or the application you plan to use with the KMS key. Aliases are required when you create a KMS key in the AWS Management Console. They are optional when you use the CreateKey operation. 7. (Optional) Type a description for the KMS key. You can add a description now or update it any time unless the key state is Pending Deletion or Pending Replica Deletion. To add, change, or delete the description of an existing customer managed key, edit the description in the AWS Management Console or use the UpdateKeyDescription operation. 8. (Optional) Type a tag key and an optional tag value. To add more than one tag to the KMS key, choose Add tag. Note Tagging or untagging a KMS key can allow or deny permission to the KMS key. For details, see ABAC for AWS KMS and Using tags to control access to KMS keys. When you add tags to your AWS resources, AWS generates a cost allocation report with usage and costs aggregated by tags. Tags can also be used to control access to a KMS key. For information about tagging KMS keys, see Tagging keys and ABAC for AWS KMS. 9. Choose Next. 10. Select the IAM users and roles that can administer the KMS key. Setting up topic encryption with encrypted Amazon SQS queue subscription 997 Amazon Simple Notification Service Developer Guide Note This key policy gives the AWS account full control of this KMS key. It allows account administrators to use IAM policies to give other principals permission to manage the KMS key. For details, see Default key policy. IAM best practices discourage the use of IAM users with long-term credentials. Whenever possible, use IAM roles, which provide temporary credentials. For details, see Security best practices in IAM in the IAM User Guide. 11. (Optional) To prevent the selected IAM users and roles from deleting this KMS key, in the Key deletion section at the bottom of the page, clear the Allow key administrators to delete this key check box. 12. Choose Next. 13. Select the IAM users and roles that can use the key in cryptographic operations. Choose Next. 14. On the Review and edit key policy page, add the following statement to the key policy, and then choose Finish. { "Sid": "Allow Amazon SNS to use this key", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey*" ], "Resource": "*" } Your new customer managed key appears in the list of keys. Step 2: Create an encrypted Amazon SNS topic 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. Setting up topic encryption with encrypted Amazon SQS queue subscription 998 Amazon Simple Notification Service 3. Choose Create topic. Developer Guide 4. On the Create new topic page, for Name, enter a topic name (for example, MyEncryptedTopic) and then choose Create
sns-dg-253
sns-dg.pdf
253
Finish. { "Sid": "Allow Amazon SNS to use this key", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey*" ], "Resource": "*" } Your new customer managed key appears in the list of keys. Step 2: Create an encrypted Amazon SNS topic 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. Setting up topic encryption with encrypted Amazon SQS queue subscription 998 Amazon Simple Notification Service 3. Choose Create topic. Developer Guide 4. On the Create new topic page, for Name, enter a topic name (for example, MyEncryptedTopic) and then choose Create topic. 5. Expand the Encryption section and do the following: a. b. Choose Enable server-side encryption. Specify the customer managed key. For more information, see Key terms. For each customer managed key type, the Description, Account, and customer managed key ARN are displayed. Important If you aren't the owner of the customer managed key, or if you log in with an account that doesn't have the kms:ListAliases and kms:DescribeKey permissions, you won't be able to view information about the customer managed key on the Amazon SNS console. Ask the owner of the customer managed key to grant you these permissions. For more information, see the AWS KMS API Permissions: Actions and Resources Reference in the AWS Key Management Service Developer Guide. c. For customer managed key, choose MyCustomKey which you created earlier and then choose Enable server-side encryption. 6. Choose Save changes. SSE is enabled for your topic and the MyTopic page is displayed. The topic's Encryption status, AWS Account, customer managed key, customer managed key ARN, and Description are displayed on the Encryption tab. Your new encrypted topic appears in the list of topics. Step 3: Create and subscribe encrypted Amazon SQS queues 1. Sign in to the Amazon SQS console. 2. Choose Create New Queue. 3. On the Create New Queue page, do the following: Setting up topic encryption with encrypted Amazon SQS queue subscription 999 Amazon Simple Notification Service Developer Guide a. Enter a Queue Name (for example, MyEncryptedQueue1). b. Choose Standard Queue, and then choose Configure Queue. c. d. Choose Use SSE. For AWS KMS key, choose MyCustomKey which you created earlier, and then choose Create Queue. 4. Repeat the process to create a second queue (for example, named MyEncryptedQueue2). Your new encrypted queues appear in the list of queues. 5. On the Amazon SQS console, choose MyEncryptedQueue1 and MyEncryptedQueue2 and then choose Queue Actions, Subscribe Queues to SNS Topic. 6. In the Subscribe to a Topic dialog box, for Choose a Topic select MyEncryptedTopic, and then choose Subscribe. Your encrypted queues' subscriptions to your encrypted topic are displayed in the Topic Subscription Result dialog box. 7. Choose OK. Step 4: Publish a message to your encrypted topic 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Topics. 3. From the list of topics, choose MyEncryptedTopic and then choose Publish message. 4. On the Publish a message page, do the following: a. b. (Optional) In the Message details section, enter the Subject (for example, Testing message publishing). In the Message body section, enter the message body (for example, My message body is encrypted at rest.). c. Choose Publish message. Your message is published to your subscribed encrypted queues. Setting up topic encryption with encrypted Amazon SQS queue subscription 1000 Amazon Simple Notification Service Developer Guide Step 5: Verify message delivery 1. 2. Sign in to the Amazon SQS console. From the list of queues, choose MyEncryptedQueue1 and then choose Send and receive messages. 3. On the Send and receive messages in MyEncryptedQueue1 page, choose Poll for messages. The message that you sent earlier is displayed. 4. Choose More Details to view your message. 5. When you're finished, choose Close. 6. Repeat the process for MyEncryptedQueue2. Securing Amazon SNS traffic with VPC endpoints An Amazon Virtual Private Cloud (Amazon VPC) endpoint for Amazon SNS is a logical entity within a VPC that allows connectivity only to Amazon SNS. The VPC routes requests to Amazon SNS and routes responses back to the VPC. The following sections provide information about working with VPC endpoints and creating VPC endpoint policies. If you use Amazon Virtual Private Cloud (Amazon VPC) to host your AWS resources, you can establish a private connection between your VPC and Amazon SNS. With this connection, you can publish messages to your Amazon SNS topics without sending them through the public internet. Amazon VPC is an AWS service that you can use to launch AWS resources in a virtual network that you define. With a VPC, you have control over your network settings, such the IP address range, subnets, route tables, and network gateways. To connect your VPC to Amazon SNS, you define an interface VPC endpoint. This type of endpoint enables
sns-dg-254
sns-dg.pdf
254
Private Cloud (Amazon VPC) to host your AWS resources, you can establish a private connection between your VPC and Amazon SNS. With this connection, you can publish messages to your Amazon SNS topics without sending them through the public internet. Amazon VPC is an AWS service that you can use to launch AWS resources in a virtual network that you define. With a VPC, you have control over your network settings, such the IP address range, subnets, route tables, and network gateways. To connect your VPC to Amazon SNS, you define an interface VPC endpoint. This type of endpoint enables you to connect your VPC to AWS services. The endpoint provides reliable, scalable connectivity to Amazon SNS without requiring an internet gateway, network address translation (NAT) instance, or VPN connection. For more information, see Access an AWS service using an interface VPC endpoint in the Amazon VPC User Guide. The information in this section is for users of Amazon VPC. For more information, and to get started with creating a VPC, see Plan your VPC in the Amazon VPC User Guide. Note VPC endpoints don't allow you to subscribe an Amazon SNS topic to a private IP address. Securing traffic with VPC endpoints 1001 Amazon Simple Notification Service Developer Guide Creating an Amazon VPC endpoint for Amazon SNS To publish messages to your Amazon SNS topics from an Amazon VPC, create an interface VPC endpoint. Then, you can publish messages to your topics while keeping the traffic within the network that you manage with the VPC. Use the following information to create the endpoint and test the connection between your VPC and Amazon SNS. Or, for a walkthrough that helps you start from scratch, see Publishing an Amazon SNS message from Amazon VPC. Creating the endpoint You can create an Amazon SNS endpoint in your VPC using the AWS Management Console, the AWS CLI, an AWS SDK, the Amazon SNS API, or AWS CloudFormation. For information about creating and configuring an endpoint using the Amazon VPC console or the AWS CLI, see Creating an Interface Endpoint in the Amazon VPC User Guide. Important You can use Amazon Virtual Private Cloud only with HTTPS Amazon SNS endpoints. When you create an endpoint, specify Amazon SNS as the service that you want your VPC to connect to. In the Amazon VPC console, service names vary based on the region. For example, if you choose US East (N. Virginia), the service name is com.amazonaws.us- east-1.sns. When you configure Amazon SNS to send messages from Amazon VPC, you must enable private DNS and specify endpoints in the format sns.us-east-2.amazonaws.com. Private DNS doesn't support legacy endpoints such as queue.amazonaws.com or us- east-2.queue.amazonaws.com. For information about creating and configuring an endpoint using AWS CloudFormation, see the AWS::EC2::VPCEndpoint resource in the AWS CloudFormation User Guide. Testing the connection between your VPC and Amazon SNS After you create an endpoint for Amazon SNS, you can publish messages from your VPC to your Amazon SNS topics. To test this connection, do the following: Creating a VPC endpoint 1002 Amazon Simple Notification Service Developer Guide 1. Connect to an Amazon EC2 instance that resides in your VPC. For information about connecting, see Connect to Your Linux Instance or Connecting to Your Windows Instance in the Amazon EC2 documentation. For example, to connect to a Linux instance using an SSH client, run the following command from a terminal: $ ssh -i ec2-key-pair.pem ec2-user@instance-hostname Where: • ec2-key-pair.pem is the file that contains the key pair that Amazon EC2 provided when you created the instance. • instance-hostname is the public hostname of the instance. To get the hostname in the Amazon EC2 console: Choose Instances, choose your instance, and find the value for Public DNS. 2. From your instance, use the Amazon SNS publish command with the AWS CLI. You can send a simple message to a topic with the following command: $ aws sns publish --region aws-region --topic-arn sns-topic-arn --message "Hello" Where: • aws-region is the AWS Region that the topic is located in. • sns-topic-arn is the Amazon Resource Name (ARN) of the topic. To get the ARN from the Amazon SNS console: Choose Topics, find your topic, and find the value in the ARN column. If the message is successfully received by Amazon SNS, the terminal prints a message ID, like the following: { "MessageId": "6c96dfff-0fdf-5b37-88d7-8cba910a8b64" } Creating a VPC endpoint 1003 Amazon Simple Notification Service Developer Guide Creating an Amazon VPC endpoint policy for Amazon SNS You can create a policy for Amazon VPC endpoints for Amazon SNS in which you specify the following: • The principal that can perform actions. • The actions that can be performed. • The resources on which actions can be performed. For more information, see Controlling Access to Services with VPC Endpoints in
sns-dg-255
sns-dg.pdf
255
value in the ARN column. If the message is successfully received by Amazon SNS, the terminal prints a message ID, like the following: { "MessageId": "6c96dfff-0fdf-5b37-88d7-8cba910a8b64" } Creating a VPC endpoint 1003 Amazon Simple Notification Service Developer Guide Creating an Amazon VPC endpoint policy for Amazon SNS You can create a policy for Amazon VPC endpoints for Amazon SNS in which you specify the following: • The principal that can perform actions. • The actions that can be performed. • The resources on which actions can be performed. For more information, see Controlling Access to Services with VPC Endpoints in the Amazon VPC User Guide. The following example VPC endpoint policy specifies that the IAM user MyUser is allowed to publish to the Amazon SNS topic MyTopic. { "Statement": [{ "Action": ["sns:Publish"], "Effect": "Allow", "Resource": "arn:aws:sns:us-east-2:123456789012:MyTopic", "Principal": { "AWS": "arn:aws:iam:123456789012:user/MyUser" } }] } The following are denied: • Other Amazon SNS API actions, such as sns:Subscribe and sns:Unsubscribe. • Other IAM users and rules which attempt to use this VPC endpoint. • MyUser publishing to a different Amazon SNS topic. Note The IAM user can still use other Amazon SNS API actions from outside the VPC. Creating a VPC policy 1004 Amazon Simple Notification Service Developer Guide Publishing an Amazon SNS message from Amazon VPC This section describes how to publish to an Amazon SNS topic while keeping the messages secure in a private network. You publish a message from an Amazon EC2 instance that's hosted in Amazon Virtual Private Cloud (Amazon VPC). The message stays within the AWS network without traveling the public internet. By publishing messages privately from a VPC, you can improve the security of the traffic between your applications and Amazon SNS. This security is important when you publish personally identifiable information (PII) about your customers, or when your application is subject to market regulations. For example, publishing privately is helpful if you have a healthcare system that must comply with the Health Insurance Portability and Accountability Act (HIPAA), or a financial system that must comply with the Payment Card Industry Data Security Standard (PCI DSS). The general steps are as follows: • Use an AWS CloudFormation template to automatically create a temporary private network in your AWS account. • Create a VPC endpoint that connects the VPC with Amazon SNS. • Log in to an Amazon EC2 instance and publish a message privately to an Amazon SNS topic. • Verify that the message was delivered successfully. • Delete the resources that you created during this process so that they don't remain in your AWS account. The following diagram depicts the private network that you create in your AWS account as you complete these steps: Publishing a message from a VPC 1005 Amazon Simple Notification Service Developer Guide This network consists of a VPC that contains an Amazon EC2 instance. The instance connects to Amazon SNS through an interface VPC endpoint. This type of endpoint connects to services that are powered by AWS PrivateLink. With this connection established, you can log in to the Amazon EC2 instance and publish messages to the Amazon SNS topic, even though the network is disconnected from the public internet. The topic fans out the messages that it receives to two subscribing AWS Lambda functions. These functions log the messages that they receive in Amazon CloudWatch Logs. It takes about 20 minutes to complete these steps. Topics • Before you begin • Step 1: Create an Amazon EC2 key pair • Step 2: Create the AWS resources • Step 3: Confirm that your Amazon EC2 instance lacks internet access • Step 4: Create an Amazon VPC endpoint for Amazon SNS • Step 5: Publish a message to your Amazon SNS topic • Step 6: Verify your message deliveries • Step 7: Clean up • Related resources Before you begin Before you start, you need an Amazon Web Services (AWS) account. When you sign up, your account is automatically signed up for all services in AWS, including Amazon SNS and Amazon VPC. If you haven't created an account already, go to https://aws.amazon.com/, and then choose Create a Free Account. Step 1: Create an Amazon EC2 key pair A key pair is used to log in to an Amazon EC2 instance. It consists of a public key that's used to encrypt your login information, and a private key that's used to decrypt it. When you create a key pair, you download a copy of the private key. Later, you use the key pair to log in to an Amazon EC2 instance. To log in, you specify the name of the key pair, and you provide the private key. Publishing a message from a VPC 1006 Amazon Simple Notification Service To create the key pair Developer Guide 1. Sign in to the AWS Management
sns-dg-256
sns-dg.pdf
256
to log in to an Amazon EC2 instance. It consists of a public key that's used to encrypt your login information, and a private key that's used to decrypt it. When you create a key pair, you download a copy of the private key. Later, you use the key pair to log in to an Amazon EC2 instance. To log in, you specify the name of the key pair, and you provide the private key. Publishing a message from a VPC 1006 Amazon Simple Notification Service To create the key pair Developer Guide 1. Sign in to the AWS Management Console and open the Amazon EC2 console at https:// console.aws.amazon.com/ec2/. 2. In the navigation menu on the left, find the Network & Security section. Then, choose Key Pairs. 3. Choose Create Key Pair. 4. In the Create Key Pair window, for Key pair name, type VPCE-Tutorial-KeyPair. Then, choose Create. 5. The private key file is automatically downloaded by your browser. Save it in a safe place. Amazon EC2 gives the file an extension of .pem. 6. (Optional) If you're using an SSH client on a Mac or Linux computer to connect to your instance, use the chmod command to set the permissions of your private key file so that only you can read it: a. Open a terminal and navigate to the directory that contains the private key: $ cd /filepath_to_private_key/ b. Set the permissions using the following command: $ chmod 400 VPCE-Tutorial-KeyPair.pem Step 2: Create the AWS resources To set up the infrastructure, you use an AWS CloudFormation template. A template is a file that acts as a blueprint for building AWS resources, such as Amazon EC2 instances and Amazon SNS topics. The template for this process is provided on GitHub for you to download. Publishing a message from a VPC 1007 Amazon Simple Notification Service Developer Guide You provide the template to AWS CloudFormation, and AWS CloudFormation provisions the resources that you need as a stack in your AWS account. A stack is a collection of resources that you manage as a single unit. When you finish these steps, you can use AWS CloudFormation to delete all of the resources in the stack at once. These resources don't remain in your AWS account, unless you want them to. The stack for this process includes the following resources: • A VPC and the associated networking resources, including a subnet, a security group, an internet gateway, and a route table. • An Amazon EC2 instance that's launched into the subnet in the VPC. • An Amazon SNS topic. • Two AWS Lambda functions. These functions receive messages that are published to the Amazon SNS topic, and they log events in CloudWatch Logs. • Amazon CloudWatch metrics and logs. • An IAM role that allows the Amazon EC2 instance to use Amazon SNS, and an IAM role that allows the Lambda functions to write to CloudWatch logs. To create the AWS resources 1. Download the template file from the GitHub website. 2. Sign in to the AWS CloudFormation console. 3. Choose Create Stack. 4. On the Select Template page, choose Upload a template to Amazon S3, choose the file, and choose Next. 5. On the Specify Details page, specify stack and key names: a. b. c. For Stack name, type VPCE-Tutorial-Stack. For KeyName, choose VPCE-Tutorial-KeyPair. For SSHLocation, keep the default value of 0.0.0.0/0. Publishing a message from a VPC 1008 Amazon Simple Notification Service Developer Guide d. Choose Next. 6. On the Options page, keep all of the default values, and choose Next. 7. On the Review page, verify the stack details. 8. Under Capabilities, acknowledge that AWS CloudFormation might create IAM resources with custom names. 9. Choose Create. The AWS CloudFormation console opens the Stacks page. The VPCE-Tutorial-Stack has a status of CREATE_IN_PROGRESS. In a few minutes, after the creation process completes, the status changes to CREATE_COMPLETE. Tip Choose the Refresh button to see the latest stack status. Step 3: Confirm that your Amazon EC2 instance lacks internet access The Amazon EC2 instance that was launched in your VPC in the previous step lacks internet access. It disallows outbound traffic, and it's unable to publish messages to Amazon SNS. Verify this by Publishing a message from a VPC 1009 Amazon Simple Notification Service Developer Guide logging in to the instance. Then, attempt to connect to a public endpoint, and attempt to message Amazon SNS. At this point, the publish attempt fails. In a later step, after you create a VPC endpoint for Amazon SNS, your publish attempt succeeds. To connect to your Amazon EC2 instance 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. 3. In the navigation menu on the left, find the Instances section. Then, choose Instances. In the list of instances, select VPCE-Tutorial-EC2Instance. 4. Copy the hostname
sns-dg-257
sns-dg.pdf
257
this by Publishing a message from a VPC 1009 Amazon Simple Notification Service Developer Guide logging in to the instance. Then, attempt to connect to a public endpoint, and attempt to message Amazon SNS. At this point, the publish attempt fails. In a later step, after you create a VPC endpoint for Amazon SNS, your publish attempt succeeds. To connect to your Amazon EC2 instance 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. 3. In the navigation menu on the left, find the Instances section. Then, choose Instances. In the list of instances, select VPCE-Tutorial-EC2Instance. 4. Copy the hostname that's provided in the Public DNS column. 5. Open a terminal. From the directory that contains the key pair, connect to the instance using the following command, where instance-hostname is the hostname that you copied from the Amazon EC2 console: $ ssh -i VPCE-Tutorial-KeyPair.pem ec2-user@instance-hostname To verify that the instance lacks internet connectivity • In your terminal, attempt to connect to any public endpoint, such as amazon.com: $ ping amazon.com Because the connection attempt fails, you can cancel at any time (Ctrl + C on Windows or Command + C on macOS). To verify that the instance lacks connectivity to Amazon SNS 1. 2. Sign in to the Amazon SNS console. In the navigation menu on the left, choose Topics. Publishing a message from a VPC 1010 Amazon Simple Notification Service Developer Guide 3. On the Topics page, copy the Amazon Resource Name (ARN) for the topic VPCE-Tutorial- Topic. 4. In your terminal, attempt to publish a message to the topic: $ aws sns publish --region aws-region --topic-arn sns-topic-arn --message "Hello" Because the publish attempt fails, you can cancel at any time. Step 4: Create an Amazon VPC endpoint for Amazon SNS To connect the VPC to Amazon SNS, you define an interface VPC endpoint. After you add the endpoint, you can log in to the Amazon EC2 instance in your VPC, and from there you can use the Amazon SNS API. You can publish messages to the topic, and the messages are published privately. They stay within the AWS network, and they don't travel the public internet. Note The instance still lacks access to other AWS services and endpoints on the internet. To create the endpoint 1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/. 2. In the navigation menu on the left, choose Endpoints. 3. Choose Create Endpoint. 4. On the Create Endpoint page, for Service category, keep the default choice of AWS services. 5. For Service Name, choose the service name for Amazon SNS. The service names vary based on the chosen region. For example, if you chose US East (N. Virginia), the service name is com.amazonaws.us-east-1.sns. 6. For VPC, choose the VPC that has the name VPCE-Tutorial-VPC. Publishing a message from a VPC 1011 Amazon Simple Notification Service Developer Guide 7. For Subnets, choose the subnet that has VPCE-Tutorial-Subnet in the subnet ID. 8. 9. For Enable Private DNS Name, select Enable for this endpoint. For Security group, choose Select security group, and choose VPCE-Tutorial-SecurityGroup. Publishing a message from a VPC 1012 Amazon Simple Notification Service Developer Guide 10. Choose Create endpoint. The Amazon VPC console confirms that a VPC endpoint was created. 11. Choose Close. The Amazon VPC console opens the Endpoints page. The new endpoint has a status of pending. In a few minutes, after the creation process completes, the status changes to available. Step 5: Publish a message to your Amazon SNS topic Now that your VPC includes an endpoint for Amazon SNS, you can log in to the Amazon EC2 instance and publish messages to the topic. Publishing a message from a VPC 1013 Amazon Simple Notification Service To publish a message Developer Guide 1. If your terminal is no longer connected to your Amazon EC2 instance, connect again: $ ssh -i VPCE-Tutorial-KeyPair.pem ec2-user@instance-hostname 2. Run the same command that you did previously to publish a message to your Amazon SNS topic. This time, the publish attempt succeeds, and Amazon SNS returns a message ID: $ aws sns publish --region aws-region --topic-arn sns-topic-arn --message "Hello" { "MessageId": "5b111270-d169-5be6-9042-410dfc9e86de" } Step 6: Verify your message deliveries When the Amazon SNS topic receives a message, it fans out the message by sending it to the two subscribing Lambda functions. When these functions receive the message, they log the event to CloudWatch logs. To verify that your message delivery succeeded, check that the functions were invoked, and check that the CloudWatch logs were updated. To verify that the Lambda functions were invoked 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 2. On the Functions page, choose VPCE-Tutorial-Lambda-1. 3. Choose Monitoring. 4. Check the Invocation count graph. This graph shows the number of times that the Lambda function has been run. The invocation count matches the number
sns-dg-258
sns-dg.pdf
258
it fans out the message by sending it to the two subscribing Lambda functions. When these functions receive the message, they log the event to CloudWatch logs. To verify that your message delivery succeeded, check that the functions were invoked, and check that the CloudWatch logs were updated. To verify that the Lambda functions were invoked 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 2. On the Functions page, choose VPCE-Tutorial-Lambda-1. 3. Choose Monitoring. 4. Check the Invocation count graph. This graph shows the number of times that the Lambda function has been run. The invocation count matches the number of times you published a message to the topic. Publishing a message from a VPC 1014 Amazon Simple Notification Service Developer Guide To verify that the CloudWatch logs were updated 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation menu on the left, choose Logs. 3. Check the logs that were written by the Lambda functions: a. Choose the /aws/lambda/VPCE-Tutorial-Lambda-1/ log group. b. Choose the log stream. c. Check that the log includes the entry From SNS: Hello. Publishing a message from a VPC 1015 Amazon Simple Notification Service Developer Guide d. Choose Log Groups at the top of the console to return the Log Groups page. Then, repeat the preceding steps for the /aws/lambda/VPCE-Tutorial-Lambda-2/ log group. Congratulations! By adding an endpoint for Amazon SNS to a VPC, you were able to publish a message to a topic from within the network that's managed by the VPC. The message was published privately without being exposed to the public internet. Step 7: Clean up Unless you want to retain the resources that you created, you can delete them now. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account. First, delete your VPC endpoint using the Amazon VPC console. Then, delete the other resources that you created by deleting the stack in the AWS CloudFormation console. When you delete a stack, AWS CloudFormation removes the stack's resources from your AWS account. To delete your VPC endpoint 1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/. 2. 3. In the navigation menu on the left, choose Endpoints. Select the endpoint that you created. 4. Choose Actions, and then choose Delete Endpoint. Publishing a message from a VPC 1016 Amazon Simple Notification Service Developer Guide 5. In the Delete Endpoint window, choose Yes, Delete. The endpoint status changes to deleting. When the deletion completes, the endpoint is removed from the page. To delete your AWS CloudFormation stack 1. Open the AWS CloudFormation console at https://console.aws.amazon.com/cloudformation. 2. Select the stack VPCE-Tutorial-Stack. 3. Choose Actions, and then choose Delete Stack. 4. In the Delete Stack window, choose Yes, Delete. The stack status changes to DELETE_IN_PROGRESS. When the deletion completes, the stack is removed from the page. Related resources For more information, see the following resources. • AWS Security Blog: Securing messages published to Amazon SNS with AWS PrivateLink • What Is Amazon VPC? • VPC Endpoints • What Is Amazon EC2? • AWS CloudFormation Concepts Enhancing Amazon SNS security with Message Data Protection • Message Data Protection is a feature in Amazon SNS used to define your own rules and policies to audit and control the content for data in motion, as opposed to data at rest. • Message Data Protection provides governance, compliance, and auditing services for enterprise applications that are message-centric, so data ingress and egress can be controlled by the Amazon SNS topic owner, and content flows can be tracked and logged. • You can write payload-based governance rules to stop unauthorized payload content from entering your message streams. Message Data Protection security 1017 Amazon Simple Notification Service Developer Guide • You can grant different content-access permissions to individual subscribers, and audit the entire content-flow process. Identity and access management in Amazon SNS Access to Amazon SNS requires credentials that AWS can use to authenticate your requests. These credentials must have permissions to access AWS resources, such an Amazon SNS topics and messages. The following sections provide details on how you can use AWS Identity and Access Management (IAM) and Amazon SNS to help secure your resources by controlling access to them. AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be authenticated (signed in) and authorized (have permissions) to use Amazon SNS resources. IAM is an AWS service that you can use with no additional charge. Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in Amazon SNS. Service user – If you use the Amazon SNS service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use
sns-dg-259
sns-dg.pdf
259
and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be authenticated (signed in) and authorized (have permissions) to use Amazon SNS resources. IAM is an AWS service that you can use with no additional charge. Audience How you use AWS Identity and Access Management (IAM) differs, depending on the work that you do in Amazon SNS. Service user – If you use the Amazon SNS service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more Amazon SNS features to do your work, you might need additional permissions. Understanding how access is managed can help you request the right permissions from your administrator. If you cannot access a feature in Amazon SNS, see Troubleshooting Amazon Simple Notification Service identity and access. Service administrator – If you're in charge of Amazon SNS resources at your company, you probably have full access to Amazon SNS. It's your job to determine which Amazon SNS features and resources your service users should access. You must then submit requests to your IAM administrator to change the permissions of your service users. Review the information on this page to understand the basic concepts of IAM. To learn more about how your company can use IAM with Amazon SNS, see How Amazon SNS works with IAM. IAM administrator – If you're an IAM administrator, you might want to learn details about how you can write policies to manage access to Amazon SNS. To view example Amazon SNS identity- based policies that you can use in IAM, see Identity-based policy examples for Amazon Simple Notification Service. Identity and access management 1018 Amazon Simple Notification Service Developer Guide Authenticating with identities Authentication is how you sign in to AWS using your identity credentials. You must be authenticated (signed in to AWS) as the AWS account root user, as an IAM user, or by assuming an IAM role. You can sign in to AWS as a federated identity by using credentials provided through an identity source. AWS IAM Identity Center (IAM Identity Center) users, your company's single sign-on authentication, and your Google or Facebook credentials are examples of federated identities. When you sign in as a federated identity, your administrator previously set up identity federation using IAM roles. When you access AWS by using federation, you are indirectly assuming a role. Depending on the type of user you are, you can sign in to the AWS Management Console or the AWS access portal. For more information about signing in to AWS, see How to sign in to your AWS account in the AWS Sign-In User Guide. If you access AWS programmatically, AWS provides a software development kit (SDK) and a command line interface (CLI) to cryptographically sign your requests by using your credentials. If you don't use AWS tools, you must sign requests yourself. For more information about using the recommended method to sign requests yourself, see AWS Signature Version 4 for API requests in the IAM User Guide. Regardless of the authentication method that you use, you might be required to provide additional security information. For example, AWS recommends that you use multi-factor authentication (MFA) to increase the security of your account. To learn more, see Multi-factor authentication in the AWS IAM Identity Center User Guide and AWS Multi-factor authentication in IAM in the IAM User Guide. AWS account root user When you create an AWS account, you begin with one sign-in identity that has complete access to all AWS services and resources in the account. This identity is called the AWS account root user and is accessed by signing in with the email address and password that you used to create the account. We strongly recommend that you don't use the root user for your everyday tasks. Safeguard your root user credentials and use them to perform the tasks that only the root user can perform. For the complete list of tasks that require you to sign in as the root user, see Tasks that require root user credentials in the IAM User Guide. Authenticating with identities 1019 Amazon Simple Notification Service Federated identity Developer Guide As a best practice, require human users, including users that require administrator access, to use federation with an identity provider to access AWS services by using temporary credentials. A federated identity is a user from your enterprise user directory, a web identity provider, the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. When federated identities access AWS accounts, they assume roles, and the roles provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center. You can create
sns-dg-260
sns-dg.pdf
260
identity Developer Guide As a best practice, require human users, including users that require administrator access, to use federation with an identity provider to access AWS services by using temporary credentials. A federated identity is a user from your enterprise user directory, a web identity provider, the AWS Directory Service, the Identity Center directory, or any user that accesses AWS services by using credentials provided through an identity source. When federated identities access AWS accounts, they assume roles, and the roles provide temporary credentials. For centralized access management, we recommend that you use AWS IAM Identity Center. You can create users and groups in IAM Identity Center, or you can connect and synchronize to a set of users and groups in your own identity source for use across all your AWS accounts and applications. For information about IAM Identity Center, see What is IAM Identity Center? in the AWS IAM Identity Center User Guide. IAM users and groups An IAM user is an identity within your AWS account that has specific permissions for a single person or application. Where possible, we recommend relying on temporary credentials instead of creating IAM users who have long-term credentials such as passwords and access keys. However, if you have specific use cases that require long-term credentials with IAM users, we recommend that you rotate access keys. For more information, see Rotate access keys regularly for use cases that require long- term credentials in the IAM User Guide. An IAM group is an identity that specifies a collection of IAM users. You can't sign in as a group. You can use groups to specify permissions for multiple users at a time. Groups make permissions easier to manage for large sets of users. For example, you could have a group named IAMAdmins and give that group permissions to administer IAM resources. Users are different from roles. A user is uniquely associated with one person or application, but a role is intended to be assumable by anyone who needs it. Users have permanent long-term credentials, but roles provide temporary credentials. To learn more, see Use cases for IAM users in the IAM User Guide. IAM roles An IAM role is an identity within your AWS account that has specific permissions. It is similar to an IAM user, but is not associated with a specific person. To temporarily assume an IAM role in the AWS Management Console, you can switch from a user to an IAM role (console). You can assume a Authenticating with identities 1020 Amazon Simple Notification Service Developer Guide role by calling an AWS CLI or AWS API operation or by using a custom URL. For more information about methods for using roles, see Methods to assume a role in the IAM User Guide. IAM roles with temporary credentials are useful in the following situations: • Federated user access – To assign permissions to a federated identity, you create a role and define permissions for the role. When a federated identity authenticates, the identity is associated with the role and is granted the permissions that are defined by the role. For information about roles for federation, see Create a role for a third-party identity provider (federation) in the IAM User Guide. If you use IAM Identity Center, you configure a permission set. To control what your identities can access after they authenticate, IAM Identity Center correlates the permission set to a role in IAM. For information about permissions sets, see Permission sets in the AWS IAM Identity Center User Guide. • Temporary IAM user permissions – An IAM user or role can assume an IAM role to temporarily take on different permissions for a specific task. • Cross-account access – You can use an IAM role to allow someone (a trusted principal) in a different account to access resources in your account. Roles are the primary way to grant cross- account access. However, with some AWS services, you can attach a policy directly to a resource (instead of using a role as a proxy). To learn the difference between roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. • Cross-service access – Some AWS services use features in other AWS services. For example, when you make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or using a service-linked role. • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of
sns-dg-261
sns-dg.pdf
261
use features in other AWS services. For example, when you make a call in a service, it's common for that service to run applications in Amazon EC2 or store objects in Amazon S3. A service might do this using the calling principal's permissions, using a service role, or using a service-linked role. • Forward access sessions (FAS) – When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. • Service role – A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. Authenticating with identities 1021 Amazon Simple Notification Service Developer Guide • Service-linked role – A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. • Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance and make it available to all of its applications, you create an instance profile that is attached to the instance. An instance profile contains the role and enables programs that are running on the EC2 instance to get temporary credentials. For more information, see Use an IAM role to grant permissions to applications running on Amazon EC2 instances in the IAM User Guide. Managing access using policies You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. AWS evaluates these policies when a principal (user, root user, or role session) makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents. For more information about the structure and contents of JSON policy documents, see Overview of JSON policies in the IAM User Guide. Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. By default, users and roles have no permissions. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. IAM policies define permissions for an action regardless of the method that you use to perform the operation. For example, suppose that you have a policy that allows the iam:GetRole action. A user with that policy can get role information from the AWS Management Console, the AWS CLI, or the AWS API. Identity-based policies Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can Managing access using policies 1022 Amazon Simple Notification Service Developer Guide perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. Identity-based policies can be further categorized as inline policies or managed policies. Inline policies are embedded directly into a single user, group, or role. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS managed policies and customer managed policies. To learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. Resource-based policies Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies
sns-dg-262
sns-dg.pdf
262
can be further categorized as inline policies or managed policies. Inline policies are embedded directly into a single user, group, or role. Managed policies are standalone policies that you can attach to multiple users, groups, and roles in your AWS account. Managed policies include AWS managed policies and customer managed policies. To learn how to choose between a managed policy or an inline policy, see Choose between managed policies and inline policies in the IAM User Guide. Resource-based policies Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. Resource-based policies are inline policies that are located in that service. You can't use AWS managed policies from IAM in a resource-based policy. Access control lists (ACLs) Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. Amazon S3, AWS WAF, and Amazon VPC are examples of services that support ACLs. To learn more about ACLs, see Access control list (ACL) overview in the Amazon Simple Storage Service Developer Guide. Other policy types AWS supports additional, less-common policy types. These policy types can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user Managing access using policies 1023 Amazon Simple Notification Service Developer Guide or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. • Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If you enable all features in an organization, then you can apply service control policies (SCPs) to any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see Service control policies in the AWS Organizations User Guide. • Resource control policies (RCPs) – RCPs are JSON policies that you can use to set the maximum available permissions for resources in your accounts without updating the IAM policies attached to each resource that you own. The RCP limits permissions for resources in member accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come from a resource-based policy. An explicit deny in any of these policies overrides the allow. For more information, see Session policies in the IAM User Guide. Multiple policy types When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. Access control Amazon SNS has its own resource-based permissions system that uses policies written in the same language used for AWS Identity and Access Management (IAM) policies. This means that you can achieve similar things with Amazon SNS policies and IAM policies. Access control 1024 Amazon Simple Notification Service Developer Guide Note It is important to understand that all AWS accounts can delegate their permissions to users under their accounts. Cross-account access allows you to share access to your AWS resources without having to manage
sns-dg-263
sns-dg.pdf
263
when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. Access control Amazon SNS has its own resource-based permissions system that uses policies written in the same language used for AWS Identity and Access Management (IAM) policies. This means that you can achieve similar things with Amazon SNS policies and IAM policies. Access control 1024 Amazon Simple Notification Service Developer Guide Note It is important to understand that all AWS accounts can delegate their permissions to users under their accounts. Cross-account access allows you to share access to your AWS resources without having to manage additional users. For information about using cross- account access, see Enabling Cross-Account Access in the IAM User Guide. Amazon SNS access control use cases You have a great deal of flexibility in how you grant or deny access to a resource. However, the typical use cases are fairly simple: • You want to grant another AWS account a particular type of topic action (for example, Publish). For more information, see Grant AWS account access to a topic. • You want to limit subscriptions to your topic to only the HTTPS protocol. For more information, see Limit subscriptions to HTTPS. • You want to allow Amazon SNS to publish messages to your Amazon SQS queue. For more information, see Publish messages to an Amazon SQS queue. Key Amazon SNS access policy concepts The following sections describe the concepts you need to understand to use the access policy language. They're presented in a logical order, with the first terms you need to know at the top of the list. Permission A permission is the concept of allowing or disallowing some kind of access to a particular resource. Permissions essentially follow this form: "A is/isn't allowed to do B to C where D applies." For example, Jane (A) has permission to publish (B) to TopicA (C) as long as she uses the HTTP protocol (D). Whenever Jane publishes to TopicA, the service checks to see if she has permission and if the request satisfies the conditions set forth in the permission. Access control use cases 1025 Amazon Simple Notification Service Statement Developer Guide A statement is the formal description of a single permission, written in the access policy language. You always write a statement as part of a broader container document known as a policy (see the next concept). Policy A policy is a document (written in the access policy language) that acts as a container for one or more statements. For example, a policy could have two statements in it: one that states that Jane can subscribe using the email protocol, and another that states that Bob cannot publish to Topic A. As shown in the following figure, an equivalent scenario would be to have two policies, one that states that Jane can subscribe using the email protocol, and another that states that Bob cannot publish to Topic A. Only ASCII characters are allowed in policy documents. You can utilize aws:SourceAccount and aws:SourceOwner to work around the scenario where you need to plug-in other AWS services' ARNs that contain non-ASCII characters. See the difference between aws:SourceAccount versus aws:SourceOwner. Issuer The issuer is the person who writes a policy to grant permissions for a resource. The issuer (by definition) is always the resource owner. AWS does not permit AWS service users to create policies for resources they don't own. If John is the resource owner, AWS authenticates John's identity when he submits the policy he's written to grant permissions for that resource. Key access policy concepts 1026 Amazon Simple Notification Service Developer Guide Principal The principal is the person or persons who receive the permission in the policy. The principal is A in the statement "A has permission to do B to C where D applies." In a policy, you can set the principal to "anyone" (that is, you can specify a wildcard to represent all people). You might do this, for example, if you don't want to restrict access based on the actual identity of the requester, but instead on some other identifying characteristic such as the requester's IP address. Action The action is the activity the principal has permission to perform. The action is B in the statement "A has permission to do B to C where D applies." Typically, the action is just the operation in the request to AWS. For example, Jane sends a request to Amazon SNS with Action=Subscribe. You can specify one or multiple actions in a policy. Resource The resource is the object the principal is requesting access to. The resource is C in the statement "A has permission to do B to C where D applies." Conditions and keys The conditions are any restrictions or details about the permission. The condition is D in the
sns-dg-264
sns-dg.pdf
264
The action is B in the statement "A has permission to do B to C where D applies." Typically, the action is just the operation in the request to AWS. For example, Jane sends a request to Amazon SNS with Action=Subscribe. You can specify one or multiple actions in a policy. Resource The resource is the object the principal is requesting access to. The resource is C in the statement "A has permission to do B to C where D applies." Conditions and keys The conditions are any restrictions or details about the permission. The condition is D in the statement "A has permission to do B to C where D applies." The part of the policy that specifies the conditions can be the most detailed and complex of all the parts. Typical conditions are related to: • Date and time (for example, the request must arrive before a specific day) • IP address (for example, the requester's IP address must be part of a particular CIDR range) A key is the specific characteristic that is the basis for access restriction. For example, the date and time of request. You use both conditions and keys together to express the restriction. The easiest way to understand how you actually implement a restriction is with an example: If you want to restrict access to before May 30, 2010, you use the condition called DateLessThan. You use the key called aws:CurrentTime and set it to the value 2010-05-30T00:00:00Z. AWS defines the conditions and keys you can use. The AWS service itself (for example, Amazon SQS or Amazon SNS) might also define service-specific keys. For more information, see Amazon SNS API permissions: Actions and resources reference. Key access policy concepts 1027 Amazon Simple Notification Service Requester Developer Guide The requester is the person who sends a request to an AWS service and asks for access to a particular resource. The requester sends a request to AWS that essentially says: "Will you allow me to do B to C where D applies?" Evaluation Evaluation is the process the AWS service uses to determine if an incoming request should be denied or allowed based on the applicable policies. For information about the evaluation logic, see Evaluation logic. Effect The effect is the result that you want a policy statement to return at evaluation time. You specify this value when you write the statements in a policy, and the possible values are deny and allow. For example, you could write a policy that has a statement that denies all requests that come from Antarctica (effect=deny given that the request uses an IP address allocated to Antarctica). Alternately, you could write a policy that has a statement that allows all requests that don't come from Antarctica (effect=allow given that the request doesn't come from Antarctica). Although the two statements sound like they do the same thing, in the access policy language logic, they are different. For more information, see Evaluation logic. Although there are only two possible values you can specify for the effect (allow or deny), there can be three different results at policy evaluation time: default deny, allow, or explicit deny. For more information, see the following concepts and Evaluation logic. Default deny A default deny is the default result from a policy in the absence of an allow or explicit deny. Allow An allow results from a statement that has effect=allow, assuming any stated conditions are met. Example: Allow requests if they are received before 1:00 p.m. on April 30, 2010. An allow overrides all default denies, but never an explicit deny. Key access policy concepts 1028 Amazon Simple Notification Service Explicit deny Developer Guide An explicit deny results from a statement that has effect=deny, assuming any stated conditions are met. Example: Deny all requests if they are from Antarctica. Any request that comes from Antarctica will always be denied no matter what any other policies might allow. Amazon SNS access control architecture overview The following figure and table describe the main components that interact to provide access control for your resources. 1 2 3 You, the resource owner. Your resources (contained within the AWS service; for example, Amazon SQS queues). Your policies. Architectural overview 1029 Amazon Simple Notification Service Developer Guide Typically you have one policy per resource, although you could have multiple. The AWS service itself provides an API you use to upload and manage your policies. 4 5 Requesters and their incoming requests to the AWS service. The access policy language evaluation code. This is the set of code within the AWS service that evaluates incoming requests against the applicable policies and determines whether the requester is allowed access to the resource. For information about how the service makes the decision, see Evaluation logic. Using the Access Policy Language in Amazon SNS
sns-dg-265
sns-dg.pdf
265
1029 Amazon Simple Notification Service Developer Guide Typically you have one policy per resource, although you could have multiple. The AWS service itself provides an API you use to upload and manage your policies. 4 5 Requesters and their incoming requests to the AWS service. The access policy language evaluation code. This is the set of code within the AWS service that evaluates incoming requests against the applicable policies and determines whether the requester is allowed access to the resource. For information about how the service makes the decision, see Evaluation logic. Using the Access Policy Language in Amazon SNS The following figure and table describe the general process of how access control works with the access policy language. Process for using access control with the Access Policy Language 1 2 You write a policy for your resource. For example, you write a policy to specify permissions for your Amazon SNS topics. You upload your policy to AWS. The AWS service itself provides an API you use to upload your policies. For example, you use the Amazon SNS SetTopicAttributes Amazon SNS topic. action to upload a policy for a particular Using the Access Policy Language 1030 Amazon Simple Notification Service Developer Guide 3 4 Someone sends a request to use your resource. For example, a user sends a request to Amazon SNS to use one of your topics. The AWS service determines which policies are applicable to the request. For example, Amazon SNS looks at all the available Amazon SNS policies and determines which ones are applicable (based on what the resource is, who the requester is, etc.). 5 The AWS service evaluates the policies. For example, Amazon SNS evaluates the policies and determines if the requester is allowed to use your topic or not. For information about the decision logic, see Evaluation logic. 6 The AWS service either denies the request or continues to process it. For example, based on the policy evaluation result, the service either returns an "Access denied" error to the requester or continues to process the request. Evaluation logic The goal at evaluation time is to decide whether a grant request should be allowed or denied. The evaluation logic follows several basic rules: • By default, all requests to use your resource coming from anyone but you are denied • An allow overrides any default denies • An explicit deny overrides any allows • The order in which the policies are evaluated is not important The following flow chart and discussion describe in more detail how the decision is made. Evaluation logic 1031 Amazon Simple Notification Service Developer Guide 1 2 3 The decision starts with a default deny. The enforcement code then evaluates all the policies that are applicable to the request (based on the resource, principal, action, and conditions). The order in which the enforcement code evaluates the policies is not important. In all those policies, the enforcement code looks for an explicit deny instruction that would apply to the request. Evaluation logic 1032 Amazon Simple Notification Service Developer Guide If it finds even one, the enforcement code returns a decision of "deny" and the process is finished (this is an explicit deny; for more information, see Explicit deny). 4 5 If no explicit deny is found, the enforcement code looks for any "allow" instructions that would apply to the request. If it finds even one, the enforcement code returns a decision of "allow" and the process is done (the service continues to process the request). If no allow is found, then the final decision is "deny" (because there was no explicit deny or allow, this is considered a default deny (for more information, see Default deny). The interplay of explicit and default denials A policy results in a default deny if it doesn't directly apply to the request. For example, if a user requests to use Amazon SNS, but the policy on the topic doesn't refer to the user's AWS account at all, then that policy results in a default deny. A policy also results in a default deny if a condition in a statement isn't met. If all conditions in the statement are met, then the policy results in either an allow or an explicit deny, based on the value of the Effect element in the policy. Policies don't specify what to do if a condition isn't met, and so the default result in that case is a default deny. For example, let's say you want to prevent requests coming in from Antarctica. You write a policy (called Policy A1) that allows a request only if it doesn't come from Antarctica. The following diagram illustrates the policy. If someone sends a request from the U.S., the condition is met (the request is not from Antarctica). Therefore, the request is allowed. But,
sns-dg-266
sns-dg.pdf
266
allow or an explicit deny, based on the value of the Effect element in the policy. Policies don't specify what to do if a condition isn't met, and so the default result in that case is a default deny. For example, let's say you want to prevent requests coming in from Antarctica. You write a policy (called Policy A1) that allows a request only if it doesn't come from Antarctica. The following diagram illustrates the policy. If someone sends a request from the U.S., the condition is met (the request is not from Antarctica). Therefore, the request is allowed. But, if someone sends a request from Antarctica, the condition isn't met, and the policy's result is therefore a default deny. Evaluation logic 1033 Amazon Simple Notification Service Developer Guide You could turn the result into an explicit deny by rewriting the policy (named Policy A2) as in the following diagram. Here, the policy explicitly denies a request if it comes from Antarctica. If someone sends a request from Antarctica, the condition is met, and the policy's result is therefore an explicit deny. The distinction between a default deny and an explicit deny is important because a default deny can be overridden by an allow, but an explicit deny can't. For example, let's say there's another policy that allows requests if they arrive on June 1, 2010. How does this policy affect the overall outcome when coupled with the policy restricting access from Antarctica? We'll compare the overall outcome when coupling the date-based policy (we'll call Policy B) with the preceding policies A1 and A2. Scenario 1 couples Policy A1 with Policy B, and Scenario 2 couples Policy A2 with Policy B. The following figure and discussion show the results when a request comes in from Antarctica on June 1, 2010. Evaluation logic 1034 Amazon Simple Notification Service Developer Guide In Scenario 1, Policy A1 returns a default deny, as described earlier in this section. Policy B returns an allow because the policy (by definition) allows requests that come in on June 1, 2010. The allow from Policy B overrides the default deny from Policy A1, and the request is therefore allowed. In Scenario 2, Policy A2 returns an explicit deny, as described earlier in this section. Again, Policy B returns an allow. The explicit deny from Policy A2 overrides the allow from Policy B, and the request is therefore denied. Evaluation logic 1035 Amazon Simple Notification Service Developer Guide Example cases for Amazon SNS access control This section describes a few examples of typical use cases for access control. Grant AWS account access to a topic Let's say you have a topic in Amazon SNS, and you want to allow one or more AWS accounts to perform a specific action on that topic, such as publishing messages. You can accomplish this by using the Amazon SNS API action AddPermission. The AddPermission action allows you to specify a topic, a list of AWS account IDs, a list of actions, and a label. Amazon SNS then automatically generates and adds a new policy statement to the topic's access control policy. You don’t need to write the policy statement yourself— Amazon SNS handles this for you. If you need to remove the policy later, you can do so by calling RemovePermission and providing the label you used when adding the permission. For example, if you call AddPermission on the topic arn:aws:sns:us- east-2:444455556666:MyTopic, specify AWS account ID 1111-2222-3333, the Publish action, and the label grant-1234-publish, Amazon SNS will generate and insert the following policy statement into the topic’s access control policy: { "Statement": [{ "Sid": "grant-1234-publish", "Effect": "Allow", "Principal": { "AWS": "111122223333" }, "Action": ["sns:Publish"], "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic" }] } After this statement is added, the AWS account 1111-2222-3333 will have permission to publish messages to the topic. Additional information: • Custom policy management: While AddPermission is convenient for granting permissions, it's often useful to manually manage the topic's access control policy for more complex scenarios, Example cases for Amazon SNS access control 1036 Amazon Simple Notification Service Developer Guide such as adding conditions or granting permissions to specific IAM roles or services. You can do this by using the SetTopicAttributes API to update the policy attribute directly. • Security best practices: Be cautious when granting permissions to ensure that only trusted AWS accounts or entities have access to your Amazon SNS topics. Regularly review and audit the policies attached to your topics to maintain security. • Policy limits: Keep in mind that there are limits to the size and complexity of Amazon SNS policies. If you need to add many permissions or complex conditions, ensure that your policy stays within these limits. Limit subscriptions to HTTPS To restrict the notification delivery protocol for your Amazon SNS topic to HTTPS, you must create a custom
sns-dg-267
sns-dg.pdf
267
policy attribute directly. • Security best practices: Be cautious when granting permissions to ensure that only trusted AWS accounts or entities have access to your Amazon SNS topics. Regularly review and audit the policies attached to your topics to maintain security. • Policy limits: Keep in mind that there are limits to the size and complexity of Amazon SNS policies. If you need to add many permissions or complex conditions, ensure that your policy stays within these limits. Limit subscriptions to HTTPS To restrict the notification delivery protocol for your Amazon SNS topic to HTTPS, you must create a custom policy. The AddPermission action in Amazon SNS does not allow you to specify protocol restrictions when granting access to your topic. Therefore, you need to manually write a policy that enforces this restriction and then use the SetTopicAttributes action to apply the policy to your topic. Here’s how you can create a policy that limits subscriptions to HTTPS: 1. Write the Policy. The policy must specify the AWS account ID that you want to grant access to and enforce the condition that only HTTPS subscriptions are allowed. Below is an example policy that grants the AWS account ID 1111-2222-3333 permission to subscribe to the topic, but only if the protocol used is HTTPS. { "Statement": [{ "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "111122223333" }, "Action": ["sns:Subscribe"], "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic", "Condition": { "StringEquals": { "sns:Protocol": "https" } } }] Example cases for Amazon SNS access control 1037 Amazon Simple Notification Service Developer Guide } 2. Apply the Policy. Use the SetTopicAttributes action in the Amazon SNS API to apply this policy to your topic. Set the Policy attribute of the topic to the JSON policy you created. snsClient.setTopicAttributes(SetTopicAttributesRequest.builder() .topicArn("arn:aws:sns:us-east-2:444455556666:MyTopic") .attributeName("Policy") .attributeValue(jsonPolicyString) // The JSON policy as a string .build()); Additional information: • Customizing access control. This approach allows you to enforce more granular access controls, such as restricting subscription protocols, which is not possible through the AddPermission action alone. Custom policies provide flexibility for scenarios requiring specific conditions, such as protocol enforcement or IP address restrictions. • Security best practices. Limiting subscriptions to HTTPS enhances the security of your notifications by ensuring that data in transit is encrypted. Regularly review your topic policies to ensure they meet your security and compliance requirements. • Policy testing. Before applying the policy in a production environment, test it in a development environment to ensure it behaves as expected. This helps prevent accidental access issues or unintended restrictions. Publish messages to an Amazon SQS queue To publish messages from your Amazon SNS topic to an Amazon SQS queue, you need to configure the correct permissions on the Amazon SQS queue. While both Amazon SNS and Amazon SQS use AWS’s access control policy language, you must explicitly set a policy on the Amazon SQS queue to allow messages to be sent from the Amazon SNS topic. You can achieve this by using the SetQueueAttributes action to apply a custom policy to the Amazon SQS queue. Unlike Amazon SNS, Amazon SQS does not support the AddPermission action for creating policy statements with conditions. Therefore, you must write the policy manually. The following is an example of an Amazon SQS policy that grants Amazon SNS permission to send messages to your queue. Note that this policy is associated with the Amazon SQS queue, Example cases for Amazon SNS access control 1038 Amazon Simple Notification Service Developer Guide not the Amazon SNS topic. The actions specified are Amazon SQS actions, and the resource is the Amazon Resource Name (ARN) of the queue. You can retrieve the queue's ARN by using the GetQueueAttributes action. { "Statement": [{ "Sid": "Allow-SNS-SendMessage", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": ["sqs:SendMessage"], "Resource": "arn:aws:sqs:us-east-2:444455556666:MyQueue", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-2:444455556666:MyTopic" } } }] } This policy uses the aws:SourceArn condition to restrict access to the SQS queue based on the source of the messages being sent. This ensures that only messages originating from the specified SNS topic (in this case, arn:aws:sns:us-east-2:444455556666:MyTopic) are allowed to be delivered to the queue. Additional information: • Queue ARN. Ensure you retrieve the correct ARN of your Amazon SQS queue using the GetQueueAttributes action. This ARN is essential for setting the correct permissions. • Security best practices. When setting up policies, always follow the principle of least privilege. Grant only the necessary permissions to the Amazon SNS topic to interact with the Amazon SQS queue, and regularly review your policies to ensure they are up-to-date and secure • Default policies in Amazon SNS. Amazon SNS doesn't automatically grant a default policy that allows other AWS services or accounts to access newly created topics. By default, Amazon SNS topics are created with no permissions, meaning they are private and only accessible to the account that created them. To enable access
sns-dg-268
sns-dg.pdf
268
setting the correct permissions. • Security best practices. When setting up policies, always follow the principle of least privilege. Grant only the necessary permissions to the Amazon SNS topic to interact with the Amazon SQS queue, and regularly review your policies to ensure they are up-to-date and secure • Default policies in Amazon SNS. Amazon SNS doesn't automatically grant a default policy that allows other AWS services or accounts to access newly created topics. By default, Amazon SNS topics are created with no permissions, meaning they are private and only accessible to the account that created them. To enable access for other AWS services, accounts, or principals, you must explicitly define and attach an access policy to the topic. This aligns with the principle of least privilege, ensuring that no unintended access is granted by default. Example cases for Amazon SNS access control 1039 Amazon Simple Notification Service Developer Guide • Testing and validation. After setting the policy, test the integration by publishing messages to the Amazon SNS topic and verifying that they are successfully delivered to the Amazon SQS queue. This helps confirm that the policy is correctly configured. Allow Amazon S3 event notifications to publish to a topic To allow an Amazon S3 bucket from another AWS account to publish event notifications to your Amazon SNS topic, you need to configure the topic's access policy accordingly. This involves writing a custom policy that grants permission to the Amazon S3 service from the specific AWS account and then applying this policy to your Amazon SNS topic. Here’s how you can set it up: 1. Write the policy. The policy should grant the Amazon S3 service (s3.amazonaws.com) the necessary permissions to publish to your Amazon SNS topic. You will use the SourceAccount condition to ensure that only the specified AWS account, which owns the Amazon S3 bucket, can publish notifications to your topic. The following is an example policy: { "Statement": [{ "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-2:111122223333:MyTopic", "Condition": { "StringEquals": { "AWS:SourceAccount": "444455556666" } } }] } • Topic owner – 111122223333 is the AWS account ID that owns the Amazon SNS topic. • Amazon S3 bucket owner – 444455556666 is the AWS account ID that owns the Amazon S3 bucket sending notifications. Example cases for Amazon SNS access control 1040 Amazon Simple Notification Service Developer Guide 2. Apply the Policy. Use the SetTopicAttributes action to set this policy on your Amazon SNS topic. This will update the topic’s access control to include the permissions specified in your custom policy. snsClient.setTopicAttributes(SetTopicAttributesRequest.builder() .topicArn("arn:aws:sns:us-east-2:111122223333:MyTopic") .attributeName("Policy") .attributeValue(jsonPolicyString) // The JSON policy as a string .build()); Additional information: • Using SourceAccount condition. The SourceAccount condition ensures that only events originating from the specified AWS account (444455556666 in this case) can trigger the Amazon SNS topic. This is a security measure to prevent unauthorized accounts from sending notifications to your topic. • Other services supporting SourceAccount. The SourceAccount condition is supported by the following services. It’s crucial to use this condition when you want to restrict access to your Amazon SNS topic based on the originating account. • Amazon API Gateway • Amazon CloudWatch • Amazon DevOps Guru • Amazon EventBridge • Amazon GameLift Servers • Amazon Pinpoint SMS and Voice API • Amazon RDS • Amazon Redshift • Amazon S3 Glacier • Amazon SES • Amazon Simple Storage Service • AWS CodeCommit • AWS Directory Service • AWS Lambda • AWS Systems Manager Incident Manager Example cases for Amazon SNS access control 1041 Amazon Simple Notification Service Developer Guide • Testing and validation. After applying the policy, test the setup by triggering an event in the Amazon S3 bucket and confirming that it successfully publishes to your Amazon SNS topic. This will help ensure that your policy is correctly configured. • Security best practices. Regularly review and audit your Amazon SNS topic policies to ensure they comply with your security requirements. Limiting access to only trusted accounts and services is essential for maintaining secure operations. Allow Amazon SES to publish to a topic that is owned by another account You can allow another AWS service to publish to a topic that is owned by another AWS account. Suppose that you signed into the 111122223333 account, opened Amazon SES, and created an email. To publish notifications about this email to a Amazon SNS topic that the 444455556666 account owns, you'd create a policy like the following. To do so, you need to provide information about the principal (the other service) and each resource's ownership. The Resource statement provides the topic ARN, which includes the account ID of the topic owner, 444455556666. The "aws:SourceOwner": "111122223333" statement specifies that your account owns the email. { "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "Service": "ses.amazonaws.com" },
sns-dg-269
sns-dg.pdf
269
that you signed into the 111122223333 account, opened Amazon SES, and created an email. To publish notifications about this email to a Amazon SNS topic that the 444455556666 account owns, you'd create a policy like the following. To do so, you need to provide information about the principal (the other service) and each resource's ownership. The Resource statement provides the topic ARN, which includes the account ID of the topic owner, 444455556666. The "aws:SourceOwner": "111122223333" statement specifies that your account owns the email. { "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "Service": "ses.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic", "Condition": { "StringEquals": { "aws:SourceOwner": "111122223333" } } } ] } When publishing events to Amazon SNS, the following services support aws:SourceOwner: Example cases for Amazon SNS access control 1042 Developer Guide Amazon Simple Notification Service • Amazon API Gateway • Amazon CloudWatch • Amazon DevOps Guru • Amazon GameLift Servers • Amazon Pinpoint SMS and Voice API • Amazon RDS • Amazon Redshift • Amazon SES • AWS CodeCommit • AWS Directory Service • AWS Lambda • AWS Systems Manager Incident Manager aws:SourceAccount versus aws:SourceOwner Important aws:SourceOwner is deprecated and new services can integrate with Amazon SNS only through aws:SourceArn and aws:SourceAccount. Amazon SNS still maintains backward compatibility for existing services that are currently supporting aws:SourceOwner. The aws:SourceAccount and aws:SourceOwner condition keys are each set by some AWS services when they publish to an Amazon SNS topic. When supported, the value will be the 12- digit AWS account ID on whose behalf the service is publishing data. Some services support one, and some support the other. • See Allow Amazon S3 event notifications to publish to a topic for how Amazon S3 notifications use aws:SourceAccount and a list of AWS services that support that condition. • See Allow Amazon SES to publish to a topic that is owned by another account for how Amazon SES uses aws:SourceOwner and a list of AWS services that support that condition. Example cases for Amazon SNS access control 1043 Amazon Simple Notification Service Developer Guide Allow accounts in an organization in AWS Organizations to publish to a topic in a different account The AWS Organizations service helps you to centrally manage billing, control access and security, and share resources across your AWS accounts. You can find your organization ID in the Organizations console. For more information, see Viewing details of an organization from the management account. In this example, any AWS account in organization myOrgId can publish to Amazon SNS topic MyTopic in account 444455556666. The policy checks the organization ID value using the aws:PrincipalOrgID global condition key. { "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic", "Condition": { "StringEquals": { "aws:PrincipalOrgID": "myOrgId" } } } ] } Allow any CloudWatch alarm to publish to a topic in a different account Use the following steps to invoke an Amazon SNS topic with a CloudWatch alarm across different AWS accounts. This example uses two accounts: • Account A is used to create the CloudWatch alarm. • Account B is used to create an SNS topic. Create an SNS topic in account B Example cases for Amazon SNS access control 1044 Amazon Simple Notification Service Developer Guide 1. 2. Sign in to the Amazon SNS console. In the navigation pane, choose Topics, and then choose Create topic. 3. Choose Standard for the topic type, and then create a name for the topic. 4. Choose Create topic, and then copy the ARN of the topic. 5. In the navigation pane, choose Subscriptions, and then choose Create subscription. 6. Add the topic's ARN in the Topic ARN section, choose Email as the protocol, and then enter an email address. 7. Choose Create subscription, and then check your email to confirm the subscription. Create a CloudWatch alarm in account A 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. 3. 4. In the navigation pane, choose Alarms, and then choose Create alarms. If you haven't already created an alarm, create one now. Otherwise, select your metric, and then provide details for the threshold and comparison parameters. From Configure Actions, under Notifications, choose Use topic ARN to notify other accounts, and then enter the topic ARN from Account B. 5. Create a name for the alarm, and then choose Create alarm. Update the access policy of the SNS topic in account B 1. 2. Sign in to the Amazon SNS console. In the navigation pane, choose Topics, and then select the topic. 3. Choose Edit, and then add the following to the policy: Note Replace the example values in the policy below with your own. { "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ Example cases for Amazon SNS access control 1045 Developer Guide Amazon Simple Notification Service { "Sid": "__default_statement_ID", "Effect":
sns-dg-270
sns-dg.pdf
270
and then enter the topic ARN from Account B. 5. Create a name for the alarm, and then choose Create alarm. Update the access policy of the SNS topic in account B 1. 2. Sign in to the Amazon SNS console. In the navigation pane, choose Topics, and then select the topic. 3. Choose Edit, and then add the following to the policy: Note Replace the example values in the policy below with your own. { "Version": "2008-10-17", "Id": "__default_policy_ID", "Statement": [ Example cases for Amazon SNS access control 1045 Developer Guide Amazon Simple Notification Service { "Sid": "__default_statement_ID", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": [ "SNS:GetTopicAttributes", "SNS:SetTopicAttributes", "SNS:AddPermission", "SNS:RemovePermission", "SNS:DeleteTopic", "SNS:Subscribe", "SNS:ListSubscriptionsByTopic", "SNS:Publish" ], "Resource": "example-topic-arn-account-b", "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:cloudwatch:example-region:111122223333:alarm:" } } } ] } Test the alarm To test the alarm, either change the alarm threshold based on the metric data points, or manually change the alarm state. When you change the alarm threshold or alarm state, you receive an email notification. Workaround for using a local Amazon SNS topic and forwarding messages Use the following steps to enable cross-account Amazon SNS notifications for CloudWatch Alarms: 1. Create an Amazon SNS topic in the same account as the CloudWatch alarm (111122223333). 2. 3. Subscribe a Lambda function or an Amazon EventBridge rule to that Amazon SNS topic. The Lambda function or EventBridge rule can then publish the message to the Amazon SNS topic in the target account (444455556666). Example cases for Amazon SNS access control 1046 Amazon Simple Notification Service Developer Guide Restrict publication to an Amazon SNS topic only from a specific VPC endpoint In this case, the topic in account 444455556666 is allowed to publish only from the VPC endpoint with the ID vpce-1ab2c34d. { "Statement": [{ "Effect": "Deny", "Principal": "*", "Action": "sns:Publish", "Resource": "arn:aws:sns:us-east-2:444455556666:MyTopic", "Condition": { "StringNotEquals": { "aws:sourceVpce": "vpce-1ab2c34d" } } }] } How Amazon SNS works with IAM Before you use IAM to manage access to Amazon SNS, learn what IAM features are available to use with Amazon SNS. IAM features you can use with Amazon Simple Notification Service IAM feature Amazon SNS support Identity-based policies Resource-based policies Policy actions Policy resources Policy condition keys (service-specific) ACLs Yes Yes Yes Yes Yes No ABAC (tags in policies) Partial How Amazon SNS works with IAM 1047 Amazon Simple Notification Service Developer Guide IAM feature Amazon SNS support Temporary credentials Principal permissions Service roles Service-linked roles Yes Yes Yes No To get a high-level view of how Amazon SNS and other AWS services work with most IAM features, see AWS services that work with IAM in the IAM User Guide. AWS managed policies for Amazon Simple Notification Service An AWS managed policy is a standalone policy that is created and administered by AWS. AWS managed policies are designed to provide permissions for many common use cases so that you can start assigning permissions to users, groups, and roles. Keep in mind that AWS managed policies might not grant least-privilege permissions for your specific use cases because they're available for all AWS customers to use. We recommend that you reduce permissions further by defining customer managed policies that are specific to your use cases. You cannot change the permissions defined in AWS managed policies. If AWS updates the permissions defined in an AWS managed policy, the update affects all principal identities (users, groups, and roles) that the policy is attached to. AWS is most likely to update an AWS managed policy when a new AWS service is launched or new API operations become available for existing services. For more information, see AWS managed policies in the IAM User Guide. AWS managed policy: AmazonSNSFullAccess AmazonSNSFullAccess provides full access to Amazon SNS using the AWS Management Console. This policy also includes the following read and write actions for AWS End User Messaging SMS when called using Amazon SNS. You can attach this policy to your users, groups, or roles. AWS managed policies 1048 Amazon Simple Notification Service Permissions details Developer Guide The following permissions apply only when using the Amazon SNS APIs: • sns:* – Allows full permissions to perform any action related to Amazon SNS. This wildcard (*) means that the user can execute all possible Amazon SNS actions. • sms-voice:DescribeVerifiedDestinationNumbers – Allows you to retrieve a list of phone numbers that have been verified for sending SMS messages within the AWS account. • sms-voice:CreateVerifiedDestinationNumber – Allows you to verify a new phone number for use with SMS messaging services within AWS. • sms-voice:SendDestinationNumberVerificationCode – Allows you to send a verification code to a phone number that is in the process of being verified for SMS messaging within AWS. • sms-voice:SendTextMessage – Allows you to create a new text message and send it to a recipient's phone number. SendTextMessage only sends an SMS
sns-dg-271
sns-dg.pdf
271
execute all possible Amazon SNS actions. • sms-voice:DescribeVerifiedDestinationNumbers – Allows you to retrieve a list of phone numbers that have been verified for sending SMS messages within the AWS account. • sms-voice:CreateVerifiedDestinationNumber – Allows you to verify a new phone number for use with SMS messaging services within AWS. • sms-voice:SendDestinationNumberVerificationCode – Allows you to send a verification code to a phone number that is in the process of being verified for SMS messaging within AWS. • sms-voice:SendTextMessage – Allows you to create a new text message and send it to a recipient's phone number. SendTextMessage only sends an SMS message to one recipient each time it's invoked. • sms-voice:DeleteVerifiedDestinationNumber – Allows you to remove a phone number from the list of verified numbers within the AWS account • sms-voice:VerifyDestinationNumber – Allows you to initiate and complete the verification process for a phone number to be used for SMS messaging services within AWS. • sms-voice:DescribeAccountAttributes – Allows you to retrieve detailed information about the account-level attributes related to SMS messaging services within AWS. • sms-voice:DescribeSpendLimits – Allows you to retrieve information about the spending limits associated with SMS messaging services within the AWS account • sms-voice:DescribePhoneNumbers – Allows you to retrieve detailed information about the phone numbers associated with SMS messaging services within the AWS account • sms-voice:SetTextMessageSpendLimitOverride – Allows you to set or override the spending limit for SMS text messaging within the AWS account • sms-voice:DescribeOptedOutNumbers – Allows you to retrieve a list of phone numbers that have opted out of receiving SMS messages from your AWS account. • sms-voice:DeleteOptedOutNumber – Allows you to remove a phone number from the list of opted-out numbers within the AWS account AmazonSNSFullAccess example policy AWS managed policies 1049 Amazon Simple Notification Service Developer Guide { "Version": "2012-10-17", "Statement": [ { "Sid": "SNSFullAccess", "Effect": "Allow", "Action": "sns:*", "Resource": "*" }, { "Sid": "SMSAccessViaSNS", "Effect": "Allow", "Action": [ "sms-voice:DescribeVerifiedDestinationNumbers", "sms-voice:CreateVerifiedDestinationNumber", "sms-voice:SendDestinationNumberVerificationCode", "sms-voice:SendTextMessage", "sms-voice:DeleteVerifiedDestinationNumber", "sms-voice:VerifyDestinationNumber", "sms-voice:DescribeAccountAttributes", "sms-voice:DescribeSpendLimits", "sms-voice:DescribePhoneNumbers", "sms-voice:SetTextMessageSpendLimitOverride", "sms-voice:DescribeOptedOutNumbers", "sms-voice:DeleteOptedOutNumber" ], "Resource": "*", "Condition": { "StringEquals": { "aws:CalledViaLast": "sns.amazonaws.com" } } } ] } To view the permissions for this policy, see AmazonSNSFullAccess in the AWS Managed Policy Reference. AWS managed policy: AmazonSNSReadOnlyAccess AmazonSNSReadOnlyAccess provides read-only access to Amazon SNS using the AWS Management Console. This policy also includes the following read-only actions for AWS End User AWS managed policies 1050 Amazon Simple Notification Service Developer Guide Messaging SMS when called using Amazon SNS. You can attach this policy to your users, groups, and roles. Permissions details The following permissions apply only when using the Amazon SNS APIs: • sns:GetTopicAttributes – Allows you to retrieve the attributes of an Amazon SNS topic. This includes information such as the topic's ARN (Amazon Resource Name), the list of subscribers, delivery policies, access control policies, and any other metadata associated with the topic. • sns:List* – Allows you to perform any operation that begins with List for Amazon SNS resources. This includes permissions to list various elements related to Amazon SNS, such as: • sns:ListTopics – Allows you to retrieve a list of all Amazon SNS topics in the AWS account. • sns:ListSubscriptions – Allows you to retrieve a list of all subscriptions to Amazon SNS topics. • sns:ListSubscriptionsByTopic – Allows you to list all subscriptions for a specific Amazon SNS topic. • sns:ListPlatformApplications – Allows you to list all platform applications that are created for mobile push notifications. • sns:ListEndpointsByPlatformApplication – Allows you to list all endpoints associated with a platform application. • sns:CheckIfPhoneNumberIsOptedOut – Allows you to check whether a specific phone number has opted out of receiving SMS messages through Amazon SNS. • sns:GetEndpointAttributes – Allows you to retrieve the attributes of an endpoint associated with an Amazon SNS platform application. This could include attributes such as the endpoint's enabled status, custom user data, and any other metadata associated with the endpoint. • sns:GetDataProtectionPolicy – Allows you to retrieve the data protection policy associated with an Amazon SNS topic. • sns:GetPlatformApplicationAttributes – Allows you to retrieve the attributes of an Amazon SNS platform application. Platform applications are used in Amazon SNS to send push notifications to mobile devices through services such as Apple Push Notification Service (APNS) or Firebase Cloud Messaging (FCM). AWS managed policies 1051 Amazon Simple Notification Service Developer Guide • sns:GetSMSAttributes – Allows you to retrieve the default SMS settings for the AWS account. • sns:GetSMSSandboxAccountStatus – Allows you to retrieve the current status of the SMS sandbox for your AWS account. • sns:GetSubscriptionAttributes – Allows you to retrieve the attributes of a specific subscription to an Amazon SNS topic. • sms-voice:DescribeVerifiedDestinationNumbers – Allows you to view or retrieve a list of phone numbers that have been verified for sending SMS messages within the AWS account • sms-voice:DescribeAccountAttributes – Allows you to view or retrieve information about the account-level attributes
sns-dg-272
sns-dg.pdf
272
managed policies 1051 Amazon Simple Notification Service Developer Guide • sns:GetSMSAttributes – Allows you to retrieve the default SMS settings for the AWS account. • sns:GetSMSSandboxAccountStatus – Allows you to retrieve the current status of the SMS sandbox for your AWS account. • sns:GetSubscriptionAttributes – Allows you to retrieve the attributes of a specific subscription to an Amazon SNS topic. • sms-voice:DescribeVerifiedDestinationNumbers – Allows you to view or retrieve a list of phone numbers that have been verified for sending SMS messages within the AWS account • sms-voice:DescribeAccountAttributes – Allows you to view or retrieve information about the account-level attributes related to SMS messaging services within AWS. • sms-voice:DescribeSpendLimits – Allows you to view or retrieve information about the spending limits associated with SMS messaging services within your AWS account • sms-voice:DescribePhoneNumbers – Allows you to view or retrieve information about the phone numbers that are used for SMS messaging services within the AWS account • sms-voice:DescribeOptedOutNumbers – Allows you to view or retrieve a list of phone numbers that have opted out of receiving SMS messages from your AWS account AmazonSNSReadOnlyAccess example policy { "Version": "2012-10-17", "Statement": [ { "Sid": "SNSReadOnlyAccess", "Effect": "Allow", "Action": [ "sns:GetTopicAttributes", "sns:List*", "sns:CheckIfPhoneNumberIsOptedOut", "sns:GetEndpointAttributes", "sns:GetDataProtectionPolicy", "sns:GetPlatformApplicationAttributes", "sns:GetSMSAttributes", "sns:GetSMSSandboxAccountStatus", "sns:GetSubscriptionAttributes" ], "Resource": "*" }, AWS managed policies 1052 Developer Guide Amazon Simple Notification Service { "Sid": "SMSAccessViaSNS", "Effect": "Allow", "Action": [ "sms-voice:DescribeVerifiedDestinationNumbers", "sms-voice:DescribeAccountAttributes", "sms-voice:DescribeSpendLimits", "sms-voice:DescribePhoneNumbers", "sms-voice:DescribeOptedOutNumbers" ], "Resource": "*", "Condition": { "StringEquals": { "aws:CalledViaLast": "sns.amazonaws.com" } } } ] } To view the permissions for this policy, see AmazonSNSFullAccess in the AWS Managed Policy Reference. Amazon SNS updates to AWS managed policies View details about updates to AWS managed policies for Amazon SNS since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Amazon SNS Document history page. Change Description Date AmazonSNSFullAccess – Update to an existing policy 09/24/2024 Amazon SNS added new permissions to allow full access to Amazon SNS using the AWS Management Console. AmazonSNSReadOnlyAccess – Update to an existing policy Amazon SNS added new permissions to allow read- 09/24/2024 AWS managed policies 1053 Amazon Simple Notification Service Developer Guide Change Description Date only access to Amazon SNS using the AWS Management Console. Amazon SNS started tracking changes Amazon SNS started tracking changes for its AWS managed 08/27/2024 policies. Policy actions for Amazon SNS Supports policy actions: Yes Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Action element of a JSON policy describes the actions that you can use to allow or deny access in a policy. Policy actions usually have the same name as the associated AWS API operation. There are some exceptions, such as permission-only actions that don't have a matching API operation. There are also some operations that require multiple actions in a policy. These additional actions are called dependent actions. Include actions in a policy to grant permissions to perform the associated operation. To see a list of Amazon SNS actions, see Resources Defined by Amazon Simple Notification Service in the Service Authorization Reference. Policy actions in Amazon SNS use the following prefix before the action: sns To specify multiple actions in a single statement, separate them with commas. "Action": [ "sns:action1", "sns:action2" ] Policy actions 1054 Amazon Simple Notification Service Developer Guide To view examples of Amazon SNS identity-based policies, see Identity-based policy examples for Amazon Simple Notification Service. Policy resources for Amazon SNS Supports policy resources: Yes Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Resource JSON policy element specifies the object or objects to which the action applies. Statements must include either a Resource or a NotResource element. As a best practice, specify a resource using its Amazon Resource Name (ARN). You can do this for actions that support a specific resource type, known as resource-level permissions. For actions that don't support resource-level permissions, such as listing operations, use a wildcard (*) to indicate that the statement applies to all resources. "Resource": "*" To see a list of Amazon SNS resource types and their ARNs, see Actions Defined by Amazon Simple Notification Service in the Service Authorization Reference. To learn with which actions you can specify the ARN of each resource, see Resources Defined by Amazon Simple Notification Service. To view examples of Amazon SNS identity-based policies, see Identity-based policy examples for Amazon Simple Notification Service. Policy condition keys for Amazon SNS Supports service-specific policy condition keys: Yes Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what
sns-dg-273
sns-dg.pdf
273
see a list of Amazon SNS resource types and their ARNs, see Actions Defined by Amazon Simple Notification Service in the Service Authorization Reference. To learn with which actions you can specify the ARN of each resource, see Resources Defined by Amazon Simple Notification Service. To view examples of Amazon SNS identity-based policies, see Identity-based policy examples for Amazon Simple Notification Service. Policy condition keys for Amazon SNS Supports service-specific policy condition keys: Yes Administrators can use AWS JSON policies to specify who has access to what. That is, which principal can perform actions on what resources, and under what conditions. The Condition element (or Condition block) lets you specify conditions in which a statement is in effect. The Condition element is optional. You can create conditional expressions that use condition operators, such as equals or less than, to match the condition in the policy with values in the request. Policy resources 1055 Amazon Simple Notification Service Developer Guide If you specify multiple Condition elements in a statement, or multiple keys in a single Condition element, AWS evaluates them using a logical AND operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical OR operation. All of the conditions must be met before the statement's permissions are granted. You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see IAM policy elements: variables and tags in the IAM User Guide. AWS supports global condition keys and service-specific condition keys. To see all AWS global condition keys, see AWS global condition context keys in the IAM User Guide. To see a list of Amazon SNS condition keys, see Condition Keys for Amazon Simple Notification Service in the Service Authorization Reference. To learn with which actions and resources you can use a condition key, see Resources Defined by Amazon Simple Notification Service. To view examples of Amazon SNS identity-based policies, see Identity-based policy examples for Amazon Simple Notification Service. ACLs in Amazon SNS Supports ACLs: No Access control lists (ACLs) control which principals (account members, users, or roles) have permissions to access a resource. ACLs are similar to resource-based policies, although they do not use the JSON policy document format. ABAC with Amazon SNS Supports ABAC (tags in policies): Partial Attribute-based access control (ABAC) is an authorization strategy that defines permissions based on attributes. In AWS, these attributes are called tags. You can attach tags to IAM entities (users or roles) and to many AWS resources. Tagging entities and resources is the first step of ABAC. Then you design ABAC policies to allow operations when the principal's tag matches the tag on the resource that they are trying to access. ABAC is helpful in environments that are growing rapidly and helps with situations where policy management becomes cumbersome. ACLs 1056 Amazon Simple Notification Service Developer Guide To control access based on tags, you provide tag information in the condition element of a policy using the aws:ResourceTag/key-name, aws:RequestTag/key-name, or aws:TagKeys condition keys. If a service supports all three condition keys for every resource type, then the value is Yes for the service. If a service supports all three condition keys for only some resource types, then the value is Partial. For more information about ABAC, see Define permissions with ABAC authorization in the IAM User Guide. To view a tutorial with steps for setting up ABAC, see Use attribute-based access control (ABAC) in the IAM User Guide. Using temporary credentials with Amazon SNS Supports temporary credentials: Yes Some AWS services don't work when you sign in using temporary credentials. For additional information, including which AWS services work with temporary credentials, see AWS services that work with IAM in the IAM User Guide. You are using temporary credentials if you sign in to the AWS Management Console using any method except a user name and password. For example, when you access AWS using your company's single sign-on (SSO) link, that process automatically creates temporary credentials. You also automatically create temporary credentials when you sign in to the console as a user and then switch roles. For more information about switching roles, see Switch from a user to an IAM role (console) in the IAM User Guide. You can manually create temporary credentials using the AWS CLI or AWS API. You can then use those temporary credentials to access AWS. AWS recommends that you dynamically generate temporary credentials instead of using long-term access keys. For more information, see Temporary security credentials in IAM. Cross-service principal permissions for Amazon SNS Supports forward access sessions (FAS): Yes When you use an IAM user or role to perform actions in AWS, you are considered
sns-dg-274
sns-dg.pdf
274
user and then switch roles. For more information about switching roles, see Switch from a user to an IAM role (console) in the IAM User Guide. You can manually create temporary credentials using the AWS CLI or AWS API. You can then use those temporary credentials to access AWS. AWS recommends that you dynamically generate temporary credentials instead of using long-term access keys. For more information, see Temporary security credentials in IAM. Cross-service principal permissions for Amazon SNS Supports forward access sessions (FAS): Yes When you use an IAM user or role to perform actions in AWS, you are considered a principal. When you use some services, you might perform an action that then initiates another action in a different service. FAS uses the permissions of the principal calling an AWS service, combined with Temporary credentials 1057 Amazon Simple Notification Service Developer Guide the requesting AWS service to make requests to downstream services. FAS requests are only made when a service receives a request that requires interactions with other AWS services or resources to complete. In this case, you must have permissions to perform both actions. For policy details when making FAS requests, see Forward access sessions. Service roles for Amazon SNS Supports service roles: Yes A service role is an IAM role that a service assumes to perform actions on your behalf. An IAM administrator can create, modify, and delete a service role from within IAM. For more information, see Create a role to delegate permissions to an AWS service in the IAM User Guide. Warning Changing the permissions for a service role might break Amazon SNS functionality. Edit service roles only when Amazon SNS provides guidance to do so. Service-linked roles for Amazon SNS Supports service-linked roles: No A service-linked role is a type of service role that is linked to an AWS service. The service can assume the role to perform an action on your behalf. Service-linked roles appear in your AWS account and are owned by the service. An IAM administrator can view, but not edit the permissions for service-linked roles. For details about creating or managing service-linked roles, see AWS services that work with IAM. Find a service in the table that includes a Yes in the Service-linked role column. Choose the Yes link to view the service-linked role documentation for that service. Identity-based policy examples for Amazon Simple Notification Service By default, users and roles don't have permission to create or modify Amazon SNS resources. They also can't perform tasks by using the AWS Management Console, AWS Command Line Interface (AWS CLI), or AWS API. To grant users permission to perform actions on the resources that they need, an IAM administrator can create IAM policies. The administrator can then add the IAM policies to roles, and users can assume the roles. Service roles 1058 Amazon Simple Notification Service Developer Guide To learn how to create an IAM identity-based policy by using these example JSON policy documents, see Create IAM policies (console) in the IAM User Guide. For details about actions and resource types defined by Amazon SNS, including the format of the ARNs for each of the resource types, see Actions, Resources, and Condition Keys for Amazon Simple Notification Service in the Service Authorization Reference. Policy best practices Identity-based policies determine whether someone can create, access, or delete Amazon SNS resources in your account. These actions can incur costs for your AWS account. When you create or edit identity-based policies, follow these guidelines and recommendations: • Get started with AWS managed policies and move toward least-privilege permissions – To get started granting permissions to your users and workloads, use the AWS managed policies that grant permissions for many common use cases. They are available in your AWS account. We recommend that you reduce permissions further by defining AWS customer managed policies that are specific to your use cases. For more information, see AWS managed policies or AWS managed policies for job functions in the IAM User Guide. • Apply least-privilege permissions – When you set permissions with IAM policies, grant only the permissions required to perform a task. You do this by defining the actions that can be taken on specific resources under specific conditions, also known as least-privilege permissions. For more information about using IAM to apply permissions, see Policies and permissions in IAM in the IAM User Guide. • Use conditions in IAM policies to further restrict access – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as AWS CloudFormation. For more information, see IAM JSON
sns-dg-275
sns-dg.pdf
275
conditions, also known as least-privilege permissions. For more information about using IAM to apply permissions, see Policies and permissions in IAM in the IAM User Guide. • Use conditions in IAM policies to further restrict access – You can add a condition to your policies to limit access to actions and resources. For example, you can write a policy condition to specify that all requests must be sent using SSL. You can also use conditions to grant access to service actions if they are used through a specific AWS service, such as AWS CloudFormation. For more information, see IAM JSON policy elements: Condition in the IAM User Guide. • Use IAM Access Analyzer to validate your IAM policies to ensure secure and functional permissions – IAM Access Analyzer validates new and existing policies so that the policies adhere to the IAM policy language (JSON) and IAM best practices. IAM Access Analyzer provides more than 100 policy checks and actionable recommendations to help you author secure and functional policies. For more information, see Validate policies with IAM Access Analyzer in the IAM User Guide. • Require multi-factor authentication (MFA) – If you have a scenario that requires IAM users or a root user in your AWS account, turn on MFA for additional security. To require MFA when API Identity-based policy examples 1059 Amazon Simple Notification Service Developer Guide operations are called, add MFA conditions to your policies. For more information, see Secure API access with MFA in the IAM User Guide. For more information about best practices in IAM, see Security best practices in IAM in the IAM User Guide. Using the Amazon SNS console To access the Amazon Simple Notification Service console, you must have a minimum set of permissions. These permissions must allow you to list and view details about the Amazon SNS resources in your AWS account. If you create an identity-based policy that is more restrictive than the minimum required permissions, the console won't function as intended for entities (users or roles) with that policy. You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the AWS API. Instead, allow access to only the actions that match the API operation that they're trying to perform. To ensure that users and roles can still use the Amazon SNS console, also attach the Amazon SNS ConsoleAccess or ReadOnly AWS managed policy to the entities. For more information, see Adding permissions to a user in the IAM User Guide. Other policy types AWS supports additional, less-common policy types. These policy types can set the maximum permissions granted to you by the more common policy types. • Permissions boundaries – A permissions boundary is an advanced feature in which you set the maximum permissions that an identity-based policy can grant to an IAM entity (IAM user or role). You can set a permissions boundary for an entity. The resulting permissions are the intersection of an entity's identity-based policies and its permissions boundaries. Resource-based policies that specify the user or role in the Principal field are not limited by the permissions boundary. An explicit deny in any of these policies overrides the allow. For more information about permissions boundaries, see Permissions boundaries for IAM entities in the IAM User Guide. • Service control policies (SCPs) – SCPs are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in AWS Organizations. AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If you enable all features in an organization, then you can apply service control policies (SCPs) to Identity-based policy examples 1060 Amazon Simple Notification Service Developer Guide any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see Service control policies in the AWS Organizations User Guide. • Resource control policies (RCPs) – RCPs are JSON policies that you can use to set the maximum available permissions for resources in your accounts without updating the IAM policies attached to each resource that you own. The RCP limits permissions for resources in member accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come
sns-dg-276
sns-dg.pdf
276
accounts and can impact the effective permissions for identities, including the AWS account root user, regardless of whether they belong to your organization. For more information about Organizations and RCPs, including a list of AWS services that support RCPs, see Resource control policies (RCPs) in the AWS Organizations User Guide. • Session policies – Session policies are advanced policies that you pass as a parameter when you programmatically create a temporary session for a role or federated user. The resulting session's permissions are the intersection of the user or role's identity-based policies and the session policies. Permissions can also come from a resource-based policy. An explicit deny in any of these policies overrides the allow. For more information, see Session policies in the IAM User Guide. Multiple policy types When multiple types of policies apply to a request, the resulting permissions are more complicated to understand. To learn how AWS determines whether to allow a request when multiple policy types are involved, see Policy evaluation logic in the IAM User Guide. Allow users to view their own permissions This example shows how you might create a policy that allows IAM users to view the inline and managed policies that are attached to their user identity. This policy includes permissions to complete this action on the console or programmatically using the AWS CLI or AWS API. { "Version": "2012-10-17", "Statement": [ { "Sid": "ViewOwnUserInfo", "Effect": "Allow", "Action": [ "iam:GetUserPolicy", "iam:ListGroupsForUser", "iam:ListAttachedUserPolicies", "iam:ListUserPolicies", Identity-based policy examples 1061 Amazon Simple Notification Service Developer Guide "iam:GetUser" ], "Resource": ["arn:aws:iam::*:user/${aws:username}"] }, { "Sid": "NavigateInConsole", "Effect": "Allow", "Action": [ "iam:GetGroupPolicy", "iam:GetPolicyVersion", "iam:GetPolicy", "iam:ListAttachedGroupPolicies", "iam:ListGroupPolicies", "iam:ListPolicyVersions", "iam:ListPolicies", "iam:ListUsers" ], "Resource": "*" } ] } Identity-based policies for Amazon SNS Supports identity-based policies: Yes Identity-based policies are JSON permissions policy documents that you can attach to an identity, such as an IAM user, group of users, or role. These policies control what actions users and roles can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see Define custom IAM permissions with customer managed policies in the IAM User Guide. With IAM identity-based policies, you can specify allowed or denied actions and resources as well as the conditions under which actions are allowed or denied. You can't specify the principal in an identity-based policy because it applies to the user or role to which it is attached. To learn about all of the elements that you can use in a JSON policy, see IAM JSON policy elements reference in the IAM User Guide. Identity-based policy examples for Amazon SNS To view examples of Amazon SNS identity-based policies, see Identity-based policy examples for Amazon Simple Notification Service. Identity-based policies 1062 Amazon Simple Notification Service Developer Guide Resource-based policies within Amazon SNS Supports resource-based policies Yes Resource-based policies are JSON policy documents that you attach to a resource. Examples of resource-based policies are IAM role trust policies and Amazon S3 bucket policies. In services that support resource-based policies, service administrators can use them to control access to a specific resource. For the resource where the policy is attached, the policy defines what actions a specified principal can perform on that resource and under what conditions. You must specify a principal in a resource-based policy. Principals can include accounts, users, roles, federated users, or AWS services. To enable cross-account access, you can specify an entire account or IAM entities in another account as the principal in a resource-based policy. Adding a cross-account principal to a resource- based policy is only half of establishing the trust relationship. When the principal and the resource are in different AWS accounts, an IAM administrator in the trusted account must also grant the principal entity (user or role) permission to access the resource. They grant permission by attaching an identity-based policy to the entity. However, if a resource-based policy grants access to a principal in the same account, no additional identity-based policy is required. For more information, see Cross account resource access in IAM in the IAM User Guide. Using identity-based policies with Amazon SNS Amazon Simple Notification Service integrates with AWS Identity and Access Management (IAM) so that you can specify which Amazon SNS actions a user in your AWS account can perform with Amazon SNS resources. You can specify a particular topic in the policy. For example, you could use variables when creating an IAM policy that grants certain users in your organization permission to use the Publish action with specific topics in your AWS account. For more information, see Policy Variables in the Using IAM guide. Important Using Amazon SNS with IAM doesn't change how you use Amazon SNS. There are no changes to Amazon SNS actions, and no new Amazon SNS actions related to users and access control. Resource-based policies 1063 Amazon Simple Notification Service
sns-dg-277
sns-dg.pdf
277
your AWS account can perform with Amazon SNS resources. You can specify a particular topic in the policy. For example, you could use variables when creating an IAM policy that grants certain users in your organization permission to use the Publish action with specific topics in your AWS account. For more information, see Policy Variables in the Using IAM guide. Important Using Amazon SNS with IAM doesn't change how you use Amazon SNS. There are no changes to Amazon SNS actions, and no new Amazon SNS actions related to users and access control. Resource-based policies 1063 Amazon Simple Notification Service Developer Guide For examples of policies that cover Amazon SNS actions and resources, see Example policies for Amazon SNS. IAM and Amazon SNS policies together You use an IAM policy to restrict your users' access to Amazon SNS actions and topics. An IAM policy can restrict access only to users within your AWS account, not to other AWS accounts. You use an Amazon SNS policy with a particular topic to restrict who can work with that topic (for example, who can publish messages to it, who can subscribe to it, etc.). Amazon SNS policies can grant access to other AWS accounts, or to users within your own AWS account. To grant your users permissions for your Amazon SNS topics, you can use IAM policies, Amazon SNS policies, or both. For the most part, you can achieve the same results with either. For example, the following diagram shows an IAM policy and an Amazon SNS policy that are equivalent. The IAM policy allows the Amazon SNS Subscribe action for the topic called topic_xyz in your AWS account The IAM policy is attached to the users Bob and Susan (which means that Bob and Susan have the permissions stated in the policy). The Amazon SNS policy likewise grants Bob and Susan permission to access Subscribe for topic_xyz. Note The preceding example shows simple policies with no conditions. You could specify a particular condition in either policy and get the same result. Using identity-based policies 1064 Amazon Simple Notification Service Developer Guide There is one difference between AWS IAM and Amazon SNS policies: The Amazon SNS policy system lets you grant permission to other AWS accounts, whereas the IAM policy doesn't. It's up to you how you use both of the systems together to manage your permissions, based on your needs. The following examples show how the two policy systems work together. Example 1 In this example, both an IAM policy and an Amazon SNS policy apply to Bob. The IAM policy grants him permission for Subscribe on any of the AWS account's topics, whereas the Amazon SNS policy grants him permission to use Publish on a specific topic (topic_xyz). The following diagram illustrates the concept. If Bob were to send a request to subscribe to any topic in the AWS account, the IAM policy would allow the action. If Bob were to send a request to publish a message to topic_xyz, the Amazon SNS policy would allow the action. Example 2 In this example, we build on example 1 (where Bob has two policies that apply to him). Let's say that Bob publishes messages to topic_xyz that he shouldn't have, so you want to entirely remove his ability to publish to topics. The easiest thing to do is to add an IAM policy that denies him access to the Publish action on all topics. This third policy overrides the Amazon SNS policy that originally gave him permission to publish to topic_xyz, because an explicit deny always overrides an allow (for more information about policy evaluation logic, see Evaluation logic). The following diagram illustrates the concept. Using identity-based policies 1065 Amazon Simple Notification Service Developer Guide For examples of policies that cover Amazon SNS actions and resources, see Example policies for Amazon SNS. Amazon SNS resource ARN format For Amazon SNS, topics are the only resource type you can specify in a policy. The following is the Amazon Resource Name (ARN) format for topics. arn:aws:sns:region:account_ID:topic_name For more information about ARNs, go to ARNs in IAM User Guide. Example The following is an ARN for a topic named MyTopic in the us-east-2 region, belonging to AWS account 123456789012. arn:aws:sns:us-east-2:123456789012:MyTopic Example If you had a topic named MyTopic in each of the different Regions that Amazon SNS supports, you could specify the topics with the following ARN. Using identity-based policies 1066 Amazon Simple Notification Service Developer Guide arn:aws:sns:*:123456789012:MyTopic You can use * and ? wildcards in the topic name. For example, the following could refer to all the topics created by Bob that he has prefixed with bob_. arn:aws:sns:*:123456789012:bob_* As a convenience to you, when you create a topic, Amazon SNS returns the topic's ARN in the response. Amazon SNS API actions In an IAM
sns-dg-278
sns-dg.pdf
278
to AWS account 123456789012. arn:aws:sns:us-east-2:123456789012:MyTopic Example If you had a topic named MyTopic in each of the different Regions that Amazon SNS supports, you could specify the topics with the following ARN. Using identity-based policies 1066 Amazon Simple Notification Service Developer Guide arn:aws:sns:*:123456789012:MyTopic You can use * and ? wildcards in the topic name. For example, the following could refer to all the topics created by Bob that he has prefixed with bob_. arn:aws:sns:*:123456789012:bob_* As a convenience to you, when you create a topic, Amazon SNS returns the topic's ARN in the response. Amazon SNS API actions In an IAM policy, you can specify any actions that Amazon SNS offers. However, the ConfirmSubscription and Unsubscribe actions do not require authentication, which means that even if you specify those actions in a policy, IAM won't restrict users' access to those actions. Each action you specify in a policy must be prefixed with the lowercase string sns:. To specify all Amazon SNS actions, for example, you would use sns:*. For a list of the actions, go to the Amazon Simple Notification Service API Reference. Amazon SNS policy keys Amazon SNS implements the following AWS wide policy keys, plus some service-specific keys. For a list of condition keys supported by each AWS service, see Actions, resources, and condition keys for AWS services in the IAM User Guide. For a list of condition keys that can be used in multiple AWS services, see AWS global condition context keys in the IAM User Guide. Amazon SNS uses the following service-specific keys. Use these keys in policies that restrict access to Subscribe requests. • sns:endpoint—The URL, email address, or ARN from a Subscribe request or a previously confirmed subscription. Use with string conditions (see Example policies for Amazon SNS) to restrict access to specific endpoints (for example, *@yourcompany.com). • sns:protocol—The protocol value from a Subscribe request or a previously confirmed subscription. Use with string conditions (see Example policies for Amazon SNS) to restrict publication to specific delivery protocols (for example, https). Using identity-based policies 1067 Amazon Simple Notification Service Developer Guide Example policies for Amazon SNS This section shows several simple policies for controlling user access to Amazon SNS. Note In the future, Amazon SNS might add new actions that should logically be included in one of the following policies, based on the policy’s stated goals. Example 1: Allow a group to create and manage topics In this example, we create a policy that grants access to CreateTopic, ListTopics, SetTopicAttributes, and DeleteTopic. { "Statement": [{ "Effect": "Allow", "Action": ["sns:CreateTopic", "sns:ListTopics", "sns:SetTopicAttributes", "sns:DeleteTopic"], "Resource": "*" }] } Example 2: Allow the IT group to publish messages to a particular topic In this example, we create a group for IT, and assign a policy that grants access to Publish on the specific topic of interest. { "Statement": [{ "Effect": "Allow", "Action": "sns:Publish", "Resource": "arn:aws:sns:*:123456789012:MyTopic" }] } Example 3: Give users in the AWS account ability to subscribe to topics In this example, we create a policy that grants access to the Subscribeaction, with string matching conditions for the sns:Protocol and sns:Endpoint policy keys. Using identity-based policies 1068 Amazon Simple Notification Service Developer Guide { "Statement": [{ "Effect": "Allow", "Action": ["sns:Subscribe"], "Resource": "*", "Condition": { "StringLike": { "sns:Endpoint": "*@example.com" }, "StringEquals": { "sns:Protocol": "email" } } }] } Example 4: Allow a partner to publish messages to a particular topic You can use an Amazon SNS policy or an IAM policy to allow a partner to publish to a specific topic. If your partner has an AWS account, it might be easier to use an Amazon SNS policy. However, anyone in the partner's company who possesses the AWS security credentials could publish messages to the topic. This example assumes that you want to limit access to a particular person (or application). To do this you need to treat the partner like a user within your own company, and use a IAM policy instead of an Amazon SNS policy. For this example, we create a group called WidgetCo that represents the partner company; we create a user for the specific person (or application) at the partner company who needs access; and then we put the user in the group. We then attach a policy that grants the group Publish access on the specific topic named WidgetPartnerTopic. We also want to prevent the WidgetCo group from doing anything else with topics, so we add a statement that denies permission to any Amazon SNS actions other than Publish on any topics other than WidgetPartnerTopic. This is necessary only if there's a broad policy elsewhere in the system that grants users wide access to Amazon SNS. { "Statement": [{ "Effect": "Allow", "Action": "sns:Publish", Using identity-based policies 1069 Amazon Simple Notification Service Developer Guide "Resource": "arn:aws:sns:*:123456789012:WidgetPartnerTopic" }, { "Effect": "Deny", "NotAction": "sns:Publish", "NotResource": "arn:aws:sns:*:123456789012:WidgetPartnerTopic"
sns-dg-279
sns-dg.pdf
279
then attach a policy that grants the group Publish access on the specific topic named WidgetPartnerTopic. We also want to prevent the WidgetCo group from doing anything else with topics, so we add a statement that denies permission to any Amazon SNS actions other than Publish on any topics other than WidgetPartnerTopic. This is necessary only if there's a broad policy elsewhere in the system that grants users wide access to Amazon SNS. { "Statement": [{ "Effect": "Allow", "Action": "sns:Publish", Using identity-based policies 1069 Amazon Simple Notification Service Developer Guide "Resource": "arn:aws:sns:*:123456789012:WidgetPartnerTopic" }, { "Effect": "Deny", "NotAction": "sns:Publish", "NotResource": "arn:aws:sns:*:123456789012:WidgetPartnerTopic" } ] } Managing custom Amazon SNS IAM policies Custom IAM policies allow you to specify permissions for individual IAM users, groups, or roles, granting or restricting access to specific AWS resources and actions. When managing Amazon SNS resources, custom IAM policies allow you to tailor access permissions according to your organization's security and operational requirements. Use the following steps to manage custom IAM policies for Amazon SNS: 1. Sign in to the AWS Management Console and open the IAM console at https:// 2. 3. 4. console.aws.amazon.com/iam/. From the navigation pane, choose Policies. To create a new custom IAM policy, choose Create policy and choose SNS. To edit an existing policy, select the policy from the list and choose Edit policy. In the policy editor, define the permissions for accessing Amazon SNS resources. You can specify actions, resources, and conditions based on your specific requirements. 5. To grant permissions for Amazon SNS actions, include relevant Amazon SNS actions such as sns:Publish, sns:Subscribe, and sns:DeleteTopic in your IAM policy. Define the ARN (Amazon Resource Name) of the Amazon SNS topics to which the permissions apply. 6. Specify the IAM users, groups, or roles to which the policy should be attached. You can attach the policy directly to IAM users or groups, or associate it with IAM roles used by AWS services or applications. 7. Review the IAM policy configuration to ensure it aligns with your access control requirements. Once verified, save the policy changes. 8. Attach the custom IAM policy to the relevant IAM users, groups, or roles within your AWS account. This grants them the permissions defined in the policy for managing Amazon SNS resources. Managing custom IAM policies 1070 Amazon Simple Notification Service Developer Guide Using temporary security credentials with Amazon SNS AWS Identity and Access Management (IAM) allows you to grant temporary security credentials to users and applications that need access to your AWS resources. These temporary security credentials are primarily used for IAM roles and federated access via industry-standard protocols such as SAML and OpenID Connect (OIDC). To effectively manage access to AWS resources, it's essential to understand the following key concepts: • IAM Roles – Roles are used to delegate access to AWS resources. Roles can be assumed by entities such as Amazon EC2 instances, Lambda functions, or users from other AWS accounts. • Federated Users – These are users authenticated via external identity providers (IdPs) using SAML or OIDC. Federated access is recommended for human users, while IAM roles should be used for software applications. • Roles Anywhere – For external applications requiring AWS access, you can use IAM Roles Anywhere to securely manage access without creating long-term credentials. You can use temporary security credentials to make requests to Amazon SNS. The SDKs and API libraries compute the necessary signature using these credentials to authenticate your requests. Requests with expired credentials will be denied by Amazon SNS. For more information on temporary security credentials, refer to Using IAM roles and Providing access to externally authenticated users (identity federation) in the IAM User Guide. Example HTTPS request example The following example demonstrates how to authenticate an Amazon SNS request using temporary security credentials obtained from AWS Security Token Service (STS). https://sns.us-east-2.amazonaws.com/ ?Action=CreateTopic &Name=My-Topic &SignatureVersion=4 &SignatureMethod=AWS4-HMAC-SHA256 &Timestamp=2023-07-05T12:00:00Z &X-Amz-Security-Token=SecurityTokenValue &X-Amz-Date=20230705T120000Z &X-Amz-Credential=<your-access-key-id>/20230705/us-east-2/sns/aws4_request Using temporary credentials 1071 Amazon Simple Notification Service Developer Guide &X-Amz-SignedHeaders=host &X-Amz-Signature=<signature-value> Steps to authenticate the request 1. Obtain Temporary Security Credentials – Use AWS STS to assume a role or get federated user credentials. This will provide you with an access key ID, secret access key, and security token. 2. Construct the Request – Include the required parameters for your Amazon SNS action (for example, CreateTopic), and ensure you use HTTPS for secure communication. 3. Sign the Request – Use the AWS Signature Version 4 process to sign your request. This involves creating a canonical request, string-to-sign, and then calculating the signature. For more on AWS Signature Version 4, see Use Signature Version 4 signing in the Amazon EBS User Guide. 4. Send the Request – Include the X-Amz-Security-Token in your request header to pass the temporary security credentials to Amazon SNS. Amazon SNS API permissions: Actions and resources reference The following list grants information specific
sns-dg-280
sns-dg.pdf
280
required parameters for your Amazon SNS action (for example, CreateTopic), and ensure you use HTTPS for secure communication. 3. Sign the Request – Use the AWS Signature Version 4 process to sign your request. This involves creating a canonical request, string-to-sign, and then calculating the signature. For more on AWS Signature Version 4, see Use Signature Version 4 signing in the Amazon EBS User Guide. 4. Send the Request – Include the X-Amz-Security-Token in your request header to pass the temporary security credentials to Amazon SNS. Amazon SNS API permissions: Actions and resources reference The following list grants information specific to the Amazon SNS implementation of access control: • Each policy must cover only a single topic (when writing a policy, don't include statements that cover different topics) • Each policy must have a unique policy Id • Each statement in a policy must have a unique statement sid Policy quotas The following table lists the maximum quotas for a policy statement. Name Bytes Statements Principals Maximum quota 30 kb 100 1 to 200 (0 is invalid.) API permissions reference 1072 Amazon Simple Notification Service Developer Guide Name Resource Maximum quota 1 (0 is invalid. The value must match the ARN of the policy's topic.) Valid Amazon SNS policy actions Amazon SNS supports the actions shown in the following table. Action Description sns:AddPermission Grants permission to add permissions to the topic policy. sns:DeleteTopic Grants permission to delete a topic. sns:GetDataProtectionPolicy Grants permission to retrieve a topic's data protection policy. sns:GetTopicAttributes Grants permission to receive all of the topic attributes. sns:ListSubscriptionsByTopic Grants permission to retrieve all the subscriptions to a specific topic. sns:ListTagsForResource Grants permission to list all tags added to a specific topic. sns:Publish Grants permission to both publish and publish batch to a topic or endpoint. For more information, see Publish and PublishBa tch in the Amazon Simple Notification Service API Reference. sns:PutDataProtectionPolicy Grants permission to set a topic's data protection policy. sns:RemovePermission Grants permission to remove any permissions in the topic policy. sns:SetTopicAttributes Grants permission to set a topic's attributes. sns:Subscribe Grants permission to subscribe to a topic. API permissions reference 1073 Amazon Simple Notification Service Service-specific keys Developer Guide Amazon SNS uses the following service-specific keys. You can use these in policies that restrict access to Subscribe requests. • sns:endpoint—The URL, email address, or ARN from a Subscribe request or a previously confirmed subscription. Use with string conditions (see Example policies for Amazon SNS) to restrict access to specific endpoints (for example, *@example.com). • sns:protocol—The protocol value from a Subscribe request or a previously confirmed subscription. Use with string conditions (see Example policies for Amazon SNS) to restrict publication to specific delivery protocols (for example, https). Important When you use a policy to control access by sns:Endpoint, be aware that DNS issues might affect the endpoint's name resolution in the future. Troubleshooting Amazon Simple Notification Service identity and access Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon SNS and IAM. I am not authorized to perform an action in Amazon SNS If you receive an error that you're not authorized to perform an action, your policies must be updated to allow you to perform the action. The following example error occurs when the mateojackson user tries to use the console to view details about a fictional my-example-widget resource but does not have the fictional sns:GetWidget permissions. User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: sns:GetWidget on resource: my-example-widget In this case, Mateo's policy must be updated to allow him to access the my-example-widget resource using the sns:GetWidget action. API permissions reference 1074 Amazon Simple Notification Service Developer Guide If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. I am not authorized to perform iam:PassRole If you receive an error that you're not authorized to perform the iam:PassRole action, your policies must be updated to allow you to pass a role to Amazon SNS. Some AWS services allow you to pass an existing role to that service instead of creating a new service role or service-linked role. To do this, you must have permissions to pass the role to the service. The following example error occurs when an IAM user named marymajor tries to use the console to perform an action in Amazon SNS. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service. User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole In this case, Mary's policies must be updated to allow her to perform the iam:PassRole action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials.
sns-dg-281
sns-dg.pdf
281
the role to the service. The following example error occurs when an IAM user named marymajor tries to use the console to perform an action in Amazon SNS. However, the action requires the service to have permissions that are granted by a service role. Mary does not have permissions to pass the role to the service. User: arn:aws:iam::123456789012:user/marymajor is not authorized to perform: iam:PassRole In this case, Mary's policies must be updated to allow her to perform the iam:PassRole action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. I want to allow people outside of my AWS account to access my Amazon SNS resources You can create a role that users in other accounts or people outside of your organization can use to access your resources. You can specify who is trusted to assume the role. For services that support resource-based policies or access control lists (ACLs), you can use those policies to grant people access to your resources. To learn more, consult the following: • To learn whether Amazon SNS supports these features, see How Amazon SNS works with IAM. • To learn how to provide access to your resources across AWS accounts that you own, see Providing access to an IAM user in another AWS account that you own in the IAM User Guide. • To learn how to provide access to your resources to third-party AWS accounts, see Providing access to AWS accounts owned by third parties in the IAM User Guide. • To learn how to provide access through identity federation, see Providing access to externally authenticated users (identity federation) in the IAM User Guide. API permissions reference 1075 Amazon Simple Notification Service Developer Guide • To learn the difference between using roles and resource-based policies for cross-account access, see Cross account resource access in IAM in the IAM User Guide. Logging and monitoring in Amazon SNS Amazon SNS allows you to track and monitor messaging activity by logging API calls with CloudTrail and monitoring topics with CloudWatch. These tools help you gain insights into message delivery, troubleshoot issues, and ensure the health of your messaging workflows. This topic covers the following: • Logging AWS SNS API calls using AWS CloudTrail. This logging enables you to track the actions performed on your Amazon SNS topics, such as topic creation, subscription management, and message publishing. By analyzing CloudTrail logs, you can identify who made specific API requests and when those requests were made, helping you audit and troubleshoot your Amazon SNS usage. • Monitoring Amazon SNS topics using CloudWatch. CloudWatch provides metrics that allow you to observe the performance and health of your Amazon SNS topics in real time. Set up alarms based on these metrics, enabling you to respond promptly to any anomalies, such as delivery failures or high message latency. This monitoring capability ensures that you can maintain the reliability of your SNS-based messaging system by proactively addressing potential issues. Logging AWS SNS API calls using AWS CloudTrail AWS SNS is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user, role, or an AWS service. CloudTrail captures all API calls for SNS as events. The calls captured include calls from the SNS console and code calls to the SNS API operations. Using the information collected by CloudTrail, you can determine the request that was made to SNS, the IP address from which the request was made, when it was made, and additional details. Every event or log entry contains information about who generated the request. The identity information helps you determine the following: • Whether the request was made with root user or user credentials. • Whether the request was made on behalf of an IAM Identity Center user. • Whether the request was made with temporary security credentials for a role or federated user. • Whether the request was made by another AWS service. Logging and monitoring 1076 Amazon Simple Notification Service Developer Guide CloudTrail is active in your AWS account when you create the account and you automatically have access to the CloudTrail Event history. The CloudTrail Event history provides a viewable, searchable, downloadable, and immutable record of the past 90 days of recorded management events in an AWS Region. For more information, see Working with CloudTrail Event history in the AWS CloudTrail User Guide. There are no CloudTrail charges for viewing the Event history. For an ongoing record of events in your AWS account past 90 days, create a trail or a CloudTrail Lake event data store. CloudTrail trails A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created using the AWS Management Console are multi-Region. You can create a single-Region or a multi-Region trail by using
sns-dg-282
sns-dg.pdf
282
and immutable record of the past 90 days of recorded management events in an AWS Region. For more information, see Working with CloudTrail Event history in the AWS CloudTrail User Guide. There are no CloudTrail charges for viewing the Event history. For an ongoing record of events in your AWS account past 90 days, create a trail or a CloudTrail Lake event data store. CloudTrail trails A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created using the AWS Management Console are multi-Region. You can create a single-Region or a multi-Region trail by using the AWS CLI. Creating a multi-Region trail is recommended because you capture activity in all AWS Regions in your account. If you create a single-Region trail, you can view only the events logged in the trail's AWS Region. For more information about trails, see Creating a trail for your AWS account and Creating a trail for an organization in the AWS CloudTrail User Guide. You can deliver one copy of your ongoing management events to your Amazon S3 bucket at no charge from CloudTrail by creating a trail, however, there are Amazon S3 storage charges. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. For information about Amazon S3 pricing, see Amazon S3 Pricing. CloudTrail Lake event data stores CloudTrail Lake lets you run SQL-based queries on your events. CloudTrail Lake converts existing events in row-based JSON format to Apache ORC format. ORC is a columnar storage format that is optimized for fast retrieval of data. Events are aggregated into event data stores, which are immutable collections of events based on criteria that you select by applying advanced event selectors. The selectors that you apply to an event data store control which events persist and are available for you to query. For more information about CloudTrail Lake, see Working with AWS CloudTrail Lake in the AWS CloudTrail User Guide. CloudTrail Lake event data stores and queries incur costs. When you create an event data store, you choose the pricing option you want to use for the event data store. The pricing option determines the cost for ingesting and storing events, and the default and maximum retention period for the event data store. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. CloudTrail logs 1077 Amazon Simple Notification Service Developer Guide SNS data events in CloudTrail Data events provide information about the resource operations performed on or in a resource (for example, reading or writing to an Amazon S3 object). These are also known as data plane operations. Data events are often high-volume activities. By default, CloudTrail doesn’t log data events. The CloudTrail Event history doesn't record data events. Additional charges apply for data events. For more information about CloudTrail pricing, see AWS CloudTrail Pricing. You can log data events for the SNS resource types by using the CloudTrail console, AWS CLI, or CloudTrail API operations. For more information about how to log data events, see Logging data events with the AWS Management Console and Logging data events with the AWS Command Line Interface in the AWS CloudTrail User Guide. The following table lists the SNS resource types for which you can log data events. The Data event type (console) column shows the value to choose from the Data event type list on the CloudTrail console. The resources.type value column shows the resources.type value, which you would specify when configuring advanced event selectors using the AWS CLI or CloudTrail APIs. The Data APIs logged to CloudTrail column shows the API calls logged to CloudTrail for the resource type. Data event type (console) resources.type value Data APIs logged to CloudTrail SNS topic AWS::SNS::Topic • Publish • PublishBatch SNS platform endpoint AWS::SNS::Platform • Publish Endpoint For additional details, see AdvancedEventSelec tor in the AWS CloudTrail API Reference. Note SNS resource type AWS::SNS::PhoneNumber is not logged by CloudTrail. CloudTrail logs 1078 Amazon Simple Notification Service Developer Guide You can configure advanced event selectors to filter on the eventName, readOnly, and resources.ARN fields to log only those events that are important to you. For more information about these fields, see AdvancedFieldSelector in the AWS CloudTrail API Reference. For information about logging data events, see Logging data events with the AWS Management Console and Logging data events with the AWS CLI in the CloudTrail User Guide. SNS management events in CloudTrail Management events provide information about management operations that are performed on resources in your AWS account. These are also known as control plane operations. By default, CloudTrail logs management events. AWS SNS logs the following SNS control plane operations to CloudTrail as management events. • AddPermission • CheckIfPhoneNumberIsOptedOut • ConfirmSubscription • CreatePlatformApplication • CreatePlatformEndpoint • CreateSMSSandboxPhoneNumber • CreateTopic • DeleteEndpoint • DeletePlatformApplication • DeleteSMSSandboxPhoneNumber • DeleteTopic • GetDataProtectionPolicy • GetEndpointAttributes • GetPlatformApplicationAttributes •
sns-dg-283
sns-dg.pdf
283
see Logging data events with the AWS Management Console and Logging data events with the AWS CLI in the CloudTrail User Guide. SNS management events in CloudTrail Management events provide information about management operations that are performed on resources in your AWS account. These are also known as control plane operations. By default, CloudTrail logs management events. AWS SNS logs the following SNS control plane operations to CloudTrail as management events. • AddPermission • CheckIfPhoneNumberIsOptedOut • ConfirmSubscription • CreatePlatformApplication • CreatePlatformEndpoint • CreateSMSSandboxPhoneNumber • CreateTopic • DeleteEndpoint • DeletePlatformApplication • DeleteSMSSandboxPhoneNumber • DeleteTopic • GetDataProtectionPolicy • GetEndpointAttributes • GetPlatformApplicationAttributes • GetSMSAttributes • GetSMSSandboxAccountStatus • GetSubscriptionAttributes • GetTopicAttributes • ListEndpointsByPlatformApplication CloudTrail logs 1079 Amazon Simple Notification Service Developer Guide • ListOriginationNumbers • ListPhoneNumbersOptedOut • ListPlatformApplications • ListSMSSandboxPhoneNumbers • ListSubscriptions • ListSubscriptionsByTopic • ListTagsForResource • ListTopics • OptInPhoneNumber • PutDataProtectionPolicy • RemovePermission • SetEndpointAttributes • SetPlatformApplicationAttributes • SetSMSAttributes • SetSubscriptionAttributes • SetTopicAttributes • Subscribe • TagResource • Unsubscribe • UntagResource • VerifySMSSandboxPhoneNumber Note When you are not logged in to Amazon Web Services (unauthenticated mode) and either the ConfirmSubscription or Unsubscribe actions are invoked, then they will not be logged to CloudTrail. Such as, when you choose the provided link in an email notification to confirm a pending subscription to a topic, the ConfirmSubscription action is invoked in unauthenticated mode. In this example, the ConfirmSubscription action would not be logged to CloudTrail. CloudTrail logs 1080 Amazon Simple Notification Service SNS event examples Developer Guide An event represents a single request from any source and includes information about the requested API operation, the date and time of the operation, request parameters, and so on. CloudTrail log files aren't an ordered stack trace of the public API calls, so events don't appear in any specific order. The following example shows a CloudTrail event that demonstrates the ListTopics, CreateTopic, and DeleteTopic actions. { "Records": [ { "eventVersion": "1.02", "userIdentity": { "type": "IAMUser", "userName": "Bob", "principalId": "EX_PRINCIPAL_ID", "arn": "arn:aws:iam::123456789012:user/Bob", "accountId": "123456789012", "accessKeyId": "AKIAIOSFODNN7EXAMPLE" }, "eventTime": "2014-09-30T00:00:00Z", "eventSource": "sns.amazonaws.com", "eventName": "ListTopics", "awsRegion": "us-west-2", "sourceIPAddress": "127.0.0.1", "userAgent": "aws-sdk-java/unknown-version", "requestParameters": { "nextToken": "ABCDEF1234567890EXAMPLE==" }, "responseElements": null, "requestID": "example1-b9bb-50fa-abdb-80f274981d60", "eventID": "example0-09a3-47d6-a810-c5f9fd2534fe", "eventType": "AwsApiCall", "recipientAccountId": "123456789012" }, { "eventVersion": "1.02", "userIdentity": { "type": "IAMUser", "userName": "Bob", "principalId": "EX_PRINCIPAL_ID", CloudTrail logs 1081 Amazon Simple Notification Service Developer Guide "arn": "arn:aws:iam::123456789012:user/Bob", "accountId": "123456789012", "accessKeyId": "AKIAIOSFODNN7EXAMPLE" }, "eventTime": "2014-09-30T00:00:00Z", "eventSource": "sns.amazonaws.com", "eventName": "CreateTopic", "awsRegion": "us-west-2", "sourceIPAddress": "127.0.0.1", "userAgent": "aws-sdk-java/unknown-version", "requestParameters": { "name": "hello" }, "responseElements": { "topicArn": "arn:aws:sns:us-west-2:123456789012:hello-topic" }, "requestID": "example7-5cd3-5323-8a00-f1889011fee9", "eventID": "examplec-4f2f-4625-8378-130ac89660b1", "eventType": "AwsApiCall", "recipientAccountId": "123456789012" }, { "eventVersion": "1.02", "userIdentity": { "type": "IAMUser", "userName": "Bob", "principalId": "EX_PRINCIPAL_ID", "arn": "arn:aws:iam::123456789012:user/Bob", "accountId": "123456789012", "accessKeyId": "AKIAIOSFODNN7EXAMPLE" }, "eventTime": "2014-09-30T00:00:00Z", "eventSource": "sns.amazonaws.com", "eventName": "DeleteTopic", "awsRegion": "us-west-2", "sourceIPAddress": "127.0.0.1", "userAgent": "aws-sdk-java/unknown-version", "requestParameters": { "topicArn": "arn:aws:sns:us-west-2:123456789012:hello-topic" }, "responseElements": null, "requestID": "example5-4faa-51d5-aab2-803a8294388d", "eventID": "example8-6443-4b4d-abfd-1b867280d964", "eventType": "AwsApiCall", CloudTrail logs 1082 Amazon Simple Notification Service Developer Guide "recipientAccountId": "123456789012" } ] } The following example shows a CloudTrail event that demonstrates the Publish action. { "eventVersion": "1.09", "userIdentity": { "type": "AssumedRole", "principalId": "EX_PRINCIPAL_ID", "arn": "arn:aws:iam::123456789012:user/Bob", "accountId": "123456789012", "accessKeyId": "AKIAIOSFODNN7EXAMPLE", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "AKIAIOSFODNN7EXAMPLE", "arn": "arn:aws:iam::123456789012:role/Admin", "accountId": "123456789012", "userName": "ExampleUser" }, "attributes": { "creationDate": "2023-08-21T16:44:05Z", "mfaAuthenticated": "false" } } }, "eventTime": "2023-08-21T16:48:37Z", "eventSource": "sns.amazonaws.com", "eventName": "Publish", "awsRegion": "us-east-1", "sourceIPAddress": "192.0.2.0", "userAgent": "aws-cli/1.29.16 md/Botocore#1.31.16 ua/2.0 os/ linux#5.4.250-173.369.amzn2int.x86_64 md/arch#x86_64 lang/python#3.8.17 md/ pyimpl#CPython cfg/retry-mode#legacy botocore/1.31.16", "requestParameters": { "topicArn": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic", "message": "HIDDEN_DUE_TO_SECURITY_REASONS", "subject": "HIDDEN_DUE_TO_SECURITY_REASONS", "messageStructure": "json", "messageAttributes": "HIDDEN_DUE_TO_SECURITY_REASONS" CloudTrail logs 1083 Developer Guide Amazon Simple Notification Service }, "responseElements": { "messageId": "0787cd1e-d92b-521c-a8b4-90434e8ef840" }, "requestID": "0a8ab208-11bf-5e01-bd2d-ef55861b545d", "eventID": "bb3496d4-5252-4660-9c28-3c6aebdb21c0", "readOnly": false, "resources": [ { "accountId": "123456789012", "type": "AWS::SNS::Topic", "ARN": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic" } ], "eventType": "AwsApiCall", "managementEvent": false, "recipientAccountId": "123456789012", "eventCategory": "Data", "tlsDetails": { "tlsVersion": "TLSv1.2", "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256", "clientProvidedHostHeader": "sns.us-east-1.amazonaws.com" } } The following example shows a CloudTrail event that demonstrates the PublishBatch action. { "eventVersion": "1.09", "userIdentity": { "type": "AssumedRole", "principalId": "EX_PRINCIPAL_ID", "arn": "arn:aws:iam::123456789012:user/Bob", "accountId": "123456789012", "accessKeyId": "AKIAIOSFODNN7EXAMPLE", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "AKIAIOSFODNN7EXAMPLE", "arn": "arn:aws:iam::123456789012:role/Admin", "accountId": "123456789012", "userName": "ExampleUser" }, CloudTrail logs 1084 Developer Guide Amazon Simple Notification Service "attributes": { "creationDate": "2023-08-21T19:20:49Z", "mfaAuthenticated": "false" } } }, "eventTime": "2023-08-21T19:22:01Z", "eventSource": "sns.amazonaws.com", "eventName": "PublishBatch", "awsRegion": "us-east-1", "sourceIPAddress": "192.0.2.0", "userAgent": "aws-cli/1.29.16 md/Botocore#1.31.16 ua/2.0 os/ linux#5.4.250-173.369.amzn2int.x86_64 md/arch#x86_64 lang/python#3.8.17 md/ pyimpl#CPython cfg/retry-mode#legacy botocore/1.31.16", "requestParameters": { "topicArn": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic", "publishBatchRequestEntries": [ { "id": "1", "message": "HIDDEN_DUE_TO_SECURITY_REASONS" }, { "id": "2", "message": "HIDDEN_DUE_TO_SECURITY_REASONS" } ] }, "responseElements": { "successful": [ { "id": "1", "messageId": "30d68101-a64a-5573-9e10-dc5c1dd3af2f" }, { "id": "2", "messageId": "c0aa0c5c-561d-5455-b6c4-5101ed84de09" } ], "failed": [] }, "requestID": "e2cdf7f3-1b35-58ad-ac9e-aaaea0ace2f1", "eventID": "10da9a14-0154-4ab6-b3a5-1825b229a7ed", "readOnly": false, "resources": [ CloudTrail logs 1085 Amazon Simple Notification Service { "accountId": "123456789012", "type": "AWS::SNS::Topic", "ARN": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic" Developer Guide } ], "eventType": "AwsApiCall", "managementEvent": false, "recipientAccountId": "123456789012", "eventCategory": "Data", "tlsDetails": { "tlsVersion": "TLSv1.2", "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256", "clientProvidedHostHeader": "sns.us-east-1.amazonaws.com" } } For information about CloudTrail record contents, see CloudTrail record contents in the AWS CloudTrail User Guide. Monitoring Amazon SNS topics using CloudWatch Amazon SNS and Amazon CloudWatch are
sns-dg-284
sns-dg.pdf
284
{ "id": "2", "message": "HIDDEN_DUE_TO_SECURITY_REASONS" } ] }, "responseElements": { "successful": [ { "id": "1", "messageId": "30d68101-a64a-5573-9e10-dc5c1dd3af2f" }, { "id": "2", "messageId": "c0aa0c5c-561d-5455-b6c4-5101ed84de09" } ], "failed": [] }, "requestID": "e2cdf7f3-1b35-58ad-ac9e-aaaea0ace2f1", "eventID": "10da9a14-0154-4ab6-b3a5-1825b229a7ed", "readOnly": false, "resources": [ CloudTrail logs 1085 Amazon Simple Notification Service { "accountId": "123456789012", "type": "AWS::SNS::Topic", "ARN": "arn:aws:sns:us-east-1:123456789012:ExampleSNSTopic" Developer Guide } ], "eventType": "AwsApiCall", "managementEvent": false, "recipientAccountId": "123456789012", "eventCategory": "Data", "tlsDetails": { "tlsVersion": "TLSv1.2", "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256", "clientProvidedHostHeader": "sns.us-east-1.amazonaws.com" } } For information about CloudTrail record contents, see CloudTrail record contents in the AWS CloudTrail User Guide. Monitoring Amazon SNS topics using CloudWatch Amazon SNS and Amazon CloudWatch are integrated so you can collect, view, and analyze metrics for every active Amazon SNS notification. Once you have configured CloudWatch for Amazon SNS, you can gain better insight into the performance of your Amazon SNS topics, push notifications, and SMS deliveries. For example, you can set an alarm to send you an email notification if a specified threshold is met for an Amazon SNS metric, such as NumberOfNotificationsFailed. For a list of all the metrics that Amazon SNS sends to CloudWatch, see Amazon SNS metrics. For more information about Amazon SNS push notifications, see Sending mobile push notifications with Amazon SNS. Note The metrics you configure with CloudWatch for your Amazon SNS topics are automatically collected and pushed to CloudWatch at 1-minute intervals. These metrics are gathered on all topics that meet the CloudWatch guidelines for being active. A topic is considered active by CloudWatch for up to six hours from the last activity (that is, any API call) on the topic. There is no charge for the Amazon SNS metrics reported in CloudWatch; they are provided as part of the Amazon SNS service. Monitoring topics using CloudWatch 1086 Amazon Simple Notification Service Developer Guide View CloudWatch metrics for Amazon SNS You can monitor metrics for Amazon SNS using the CloudWatch console, CloudWatch's own command line interface (CLI), or programmatically using the CloudWatch API. The following procedures show you how to access the metrics using the AWS Management Console. To view metrics using the CloudWatch console 1. Sign in to the CloudWatch console. 2. On the navigation panel, choose Metrics. 3. On the All metrics tab, choose SNS, and then choose one of the following dimensions: • Country, SMS Type • PhoneNumber • Topic Metrics • Metrics with no dimensions 4. 5. To view more detail, choose a specific item. For example, if you choose Topic Metrics and then choose NumberOfMessagesPublished, the average number of published Amazon SNS messages for a 1-minute period throughout the time range of 6 hours is displayed. To view Amazon SNS usage metrics, on the All metrics tab, choose Usage, and select the target Amazon SNS usage metric (for example, NumberOfMessagesPublishedPerAccount). Set CloudWatch alarms for Amazon SNS metrics CloudWatch also allows you to set alarms when a threshold is met for a metric. For example, you could set an alarm for the metric, NumberOfNotificationsFailed, so that when your specified threshold number is met within the sampling period, then an email notification would be sent to inform you of the event. To set alarms using the CloudWatch console 1. Sign in to the AWS Management Console and open the CloudWatch console at https:// console.aws.amazon.com/cloudwatch/. 2. Choose Alarms, and then choose the Create Alarm button. This launches the Create Alarm wizard. Monitoring topics using CloudWatch 1087 Amazon Simple Notification Service Developer Guide 3. 4. Scroll through the Amazon SNS metrics to locate the metric you want to place an alarm on. Select the metric to create an alarm on and choose Continue. Fill in the Name, Description, Threshold, and Time values for the metric, and then choose Continue. 5. Choose Alarm as the alarm state. If you want CloudWatch to send you an email when the alarm state is reached, choose either an existing Amazon SNS topic or choose Create New Email Topic. If you choose Create New Email Topic, you can set the name and email addresses for a new topic. This list will be saved and appear in the drop-down box for future alarms. Choose Continue. Note If you use Create New Email Topic to create a new Amazon SNS topic, the email addresses must be verified before they will receive notifications. Emails are sent only when the alarm enters an alarm state. If this alarm state change happens before the email addresses are verified, they will not receive a notification. 6. At this point, the Create Alarm wizard gives you a chance to review the alarm you’re about to create. If you need to make any changes, you can use the Edit links on the right. Once you are satisfied, choose Create Alarm. For more information about using CloudWatch and alarms, see the CloudWatch Documentation. Amazon SNS metrics Amazon SNS sends the following metrics
sns-dg-285
sns-dg.pdf
285
be verified before they will receive notifications. Emails are sent only when the alarm enters an alarm state. If this alarm state change happens before the email addresses are verified, they will not receive a notification. 6. At this point, the Create Alarm wizard gives you a chance to review the alarm you’re about to create. If you need to make any changes, you can use the Edit links on the right. Once you are satisfied, choose Create Alarm. For more information about using CloudWatch and alarms, see the CloudWatch Documentation. Amazon SNS metrics Amazon SNS sends the following metrics to CloudWatch. Namespace Metric Description AWS/SNS NumberOfMessagesPu blished The number of messages published to your Amazon SNS topics. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Monitoring topics using CloudWatch 1088 Amazon Simple Notification Service Developer Guide Namespace Metric Description Valid statistics: Sum AWS/SNS NumberOfNotificati onsDelivered The number of messages successfu lly delivered from your Amazon SNS topics to subscribing endpoints. For a delivery attempt to succeed, the endpoint's subscription must accept the message. A subscription accepts a message if a.) it lacks a filter policy or b.) its filter policy includes attributes that match those assigned to the message. If the subscription rejects the message, the delivery attempt isn't counted for this metric. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum Monitoring topics using CloudWatch 1089 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS NumberOfNotificati onsFailed The number of messages that Amazon SNS failed to deliver. For Amazon SQS, email, SMS, or mobile push endpoints, the metric increments by 1 when Amazon SNS stops attempting message deliveries. For HTTP or HTTPS endpoints, the metric includes every failed delivery attempt, including retries that follow the initial attempt. For all other endpoints, the count increases by 1 when the message fails to deliver (regardless of the number of attempts). This metric does not include messages that were rejected by subscription filter policies. You can control the number of retries for HTTP endpoints. For more information, see Amazon SNS message delivery retries. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average Monitoring topics using CloudWatch 1090 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS NumberOfNotificati onsFilteredOut The number of messages that were rejected by subscription filter policies. A filter policy rejects a message when the message attributes don't match the policy attributes. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average AWS/SNS NumberOfNotificati onsFilteredOut-Mes The number of messages that were rejected by subscription sageAttributes filter policies for attribute-based filtering. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average Monitoring topics using CloudWatch 1091 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS NumberOfNotificati onsFilteredOut-Mes The number of messages that were rejected by subscription filter sageBody policies for payload-based filtering . Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average AWS/SNS NumberOfNotificati onsFilteredOut-Inv alidAttributes The number of messages that were rejected by subscript ion filter policies because the messages' attributes are invalid – for example, because the attribute JSON is incorrectly formatted. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average Monitoring topics using CloudWatch 1092 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS NumberOfNotificati onsFilteredOut-NoM The number of messages that were rejected by subscription filter essageAttributes policies because the messages have no attributes. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average AWS/SNS NumberOfNotificati onsFilteredOut-Inv The number of messages that were rejected by subscription filter alidMessageBody policies because the message body is invalid for filtering – for example, invalid JSON message body. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average Monitoring topics using CloudWatch 1093 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS NumberOfNotificati onsRedrivenToDlq The number of messages that have been moved to a dead-letter queue. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average AWS/SNS NumberOfNotificati onsFailedToRedrive The number of messages that couldn't be moved to a dead-letter ToDlq queue. Units: Count Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Sum, Average AWS/SNS PublishSize The size of messages published. Units: Bytes Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Minimum, Maximum, Average and Count Monitoring topics using CloudWatch 1094 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS SMSMonthToDateSpen tUSD AWS/SNS SMSSuccessRate The charges you have accrued since the start of the current calendar month for sending SMS messages. You can set an alarm for this metric to know when your month- to-date charges are close to the monthly SMS spend quota for your account. When Amazon SNS determines that sending an SMS message would incur a cost that exceeds
sns-dg-286
sns-dg.pdf
286
AWS/SNS PublishSize The size of messages published. Units: Bytes Valid dimensions: Application, PhoneNumber, Platform, and TopicName Valid statistics: Minimum, Maximum, Average and Count Monitoring topics using CloudWatch 1094 Amazon Simple Notification Service Developer Guide Namespace Metric Description AWS/SNS SMSMonthToDateSpen tUSD AWS/SNS SMSSuccessRate The charges you have accrued since the start of the current calendar month for sending SMS messages. You can set an alarm for this metric to know when your month- to-date charges are close to the monthly SMS spend quota for your account. When Amazon SNS determines that sending an SMS message would incur a cost that exceeds this quota, it stops publishing SMS messages within minutes. For information about setting your monthly SMS spend quota, or for information about requestin g a spend quota increase with AWS, see Setting SMS messaging preferences in Amazon SNS. Units: USD Valid dimensions: None Valid statistics: Sum The rate of successful SMS message deliveries. Units: Count Valid dimensions: PhoneNumber Valid statistics: Sum, Average, Data Samples Monitoring topics using CloudWatch 1095 Amazon Simple Notification Service Developer Guide Dimensions for Amazon SNS metrics Amazon Simple Notification Service sends the following dimensions to CloudWatch. Dimension Description Application Filters on application objects, which represent an app and device registered with one of the supported push notification services, such as APNs and FCM. Application,Platform Filters on application and platform objects, where the platform objects are for the supported push notification services, such as APNs and FCM. Country PhoneNumber Platform TopicName SMSType Filters on the destination country or region of an SMS message. The country or region is represented by its ISO 3166-1 alpha-2 code. Filters on the phone number when you publish SMS directly to a phone number (without a topic). Filters on platform objects for the push notification services, such as APNs and FCM. Filters on Amazon SNS topic names. Filters on the message type of SMS message. Can be promotion al or transactional. Amazon SNS usage metrics Amazon Simple Notification Service sends the following usage metrics to CloudWatch. Namespace Service Metric Resource Type Description AWS/Usage SNS ResourceC NumberOfM Resource • The Monitoring topics using CloudWatch ount essagesPu number of messages 1096 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description blishedPe rAccount published to your Amazon SNS topics across your AWS account. • Units: None • Valid Statistics: Sum AWS/Usage SNS ResourceC Approxima Resource • The ount teNumberO fTopics approxima te number of topics across your AWS account. • Units: None • Valid Statistics: Average, Minimum, Maximum, Sum Monitoring topics using CloudWatch 1097 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description AWS/Usage SNS ResourceC Approxima Resource • The ount teNumberO fFilterPo licies approxima te number of filter policies across your AWS account. • Units: None • Valid Statistics: Average, Minimum, Maximum, Sum AWS/Usage SNS ResourceC Approxima Resource • The ount teNumberO fPendingS ubscripti ons approxima te number of pending subscript ions across your AWS account. • Units: None • Valid Statistics: Average, Minimum, Maximum, Sum Monitoring topics using CloudWatch 1098 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description AWS/Usage SNS CallCount • AddPermis API • The number of API calls for the selected Amazon SNS API across your AWS account. • Content is not allowed in trailing section. Units: None • Valid Statistics: Sum sion • CheckIfPh oneNumber IsOptedOu t • CreatePla tformAppl ication • CreatePla tformEndp oint • ConfirmSu bscriptio n • CreateSMS SandboxPh oneNumber • CreateTop ic • DeleteEnd point • DeletePla tformAppl ication • DeleteSMS SandboxPh oneNumber • DeleteTop ic Monitoring topics using CloudWatch 1099 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description • GetEndpoi ntAttribu tes • GetPlatfo rmApplica tionAttri butes • GetSMSAtt ributes • GetSMSSan dboxAccou ntStatus • GetSubscr iptionAtt ributes • GetTopicA ttributes • ListEndpo intsByPla tformAppl ication • ListOrigi nationNum bers • ListPhone NumbersOp tedOut • ListPlatf ormApplic ations Monitoring topics using CloudWatch 1100 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description • ListSMSSa ndboxPhon eNumbers • ListSubsc riptions • ListSubsc riptionsB yTopic • ListTagsF orResourc e • ListTopic s • OptInPhon eNumber • RemovePer mission • SetEndpoi ntAttribu tes • SetPlatfo rmApplica tionAttri butes • SetSMSAtt ributes • SetSubscr iptionAtt ributes • SetTopicA ttributes Monitoring topics using CloudWatch 1101 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description • Subscribe • Unsubscri be • UntagReso urce • VerifySMS SandboxPh oneNumber Compliance validation for Amazon SNS To learn whether an AWS service is within the scope of specific compliance programs, see AWS services in Scope by Compliance Program and choose the compliance program that you are interested in. For general information, see AWS Compliance Programs. You can download third-party audit reports using AWS Artifact. For more information, see Downloading Reports in AWS Artifact. Your compliance
sns-dg-287
sns-dg.pdf
287
• SetSubscr iptionAtt ributes • SetTopicA ttributes Monitoring topics using CloudWatch 1101 Amazon Simple Notification Service Developer Guide Namespace Service Metric Resource Type Description • Subscribe • Unsubscri be • UntagReso urce • VerifySMS SandboxPh oneNumber Compliance validation for Amazon SNS To learn whether an AWS service is within the scope of specific compliance programs, see AWS services in Scope by Compliance Program and choose the compliance program that you are interested in. For general information, see AWS Compliance Programs. You can download third-party audit reports using AWS Artifact. For more information, see Downloading Reports in AWS Artifact. Your compliance responsibility when using AWS services is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. AWS provides the following resources to help with compliance: • Security Compliance & Governance – These solution implementation guides discuss architectural considerations and provide steps for deploying security and compliance features. • HIPAA Eligible Services Reference – Lists HIPAA eligible services. Not all AWS services are HIPAA eligible. • AWS Compliance Resources – This collection of workbooks and guides might apply to your industry and location. • AWS Customer Compliance Guides – Understand the shared responsibility model through the lens of compliance. The guides summarize the best practices for securing AWS services and map the guidance to security controls across multiple frameworks (including National Institute of Compliance validation 1102 Amazon Simple Notification Service Developer Guide Standards and Technology (NIST), Payment Card Industry Security Standards Council (PCI), and International Organization for Standardization (ISO)). • Evaluating Resources with Rules in the AWS Config Developer Guide – The AWS Config service assesses how well your resource configurations comply with internal practices, industry guidelines, and regulations. • AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS. Security Hub uses security controls to evaluate your AWS resources and to check your compliance against security industry standards and best practices. For a list of supported services and controls, see Security Hub controls reference. • Amazon GuardDuty – This AWS service detects potential threats to your AWS accounts, workloads, containers, and data by monitoring your environment for suspicious and malicious activities. GuardDuty can help you address various compliance requirements, like PCI DSS, by meeting intrusion detection requirements mandated by certain compliance frameworks. • AWS Audit Manager – This AWS service helps you continuously audit your AWS usage to simplify how you manage risk and compliance with regulations and industry standards. Resilience in Amazon SNS Resilience in Amazon SNS is ensured through leveraging the AWS global infrastructure, which revolves around AWS Regions and Availability Zones. AWS Regions offer physically separated and isolated Availability Zones connected by low-latency, high-throughput, and highly redundant networking. This architecture allows for seamless failover between Availability Zones without interruption, making applications and databases inherently more fault tolerant and scalable compared to traditional data center infrastructures. By using Availability Zones, Amazon SNS subscribers benefit from enhanced availability and reliability, guaranteeing message delivery despite potential disruptions. For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure. Additionally, subscriptions to Amazon SNS topics can be configured with delivery retries and dead- letter queues, enabling automatic handling of transient failures and ensuring messages reliably reach their intended destinations. Amazon SNS also supports message filtering and message attributes, which lets you tailor resilience strategies to their specific use cases, enhancing the overall robustness of your applications. Resilience 1103 Amazon Simple Notification Service Developer Guide Infrastructure security in Amazon SNS As a managed service, Amazon SNS is protected by the AWS global network security procedures found in the Best Practices for Security, Identity, & Compliance documentation. Use AWS API actions to access Amazon SNS through the network. Clients must support Transport Layer Security (TLS) 1.2 or later. Clients must also support cipher suites with Perfect Forward Secrecy (PFS), such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman (ECDHE). You must sign requests using both an access key ID and a secret access key associated with an IAM principal. Alternatively, you can use the AWS Security Token Service (AWS STS) to generate temporary security credentials for signing requests. You can call these API actions from any network location, but Amazon SNS supports resource- based access policies, which can include restrictions based on the source IP address. You can also use Amazon SNS policies to control access from specific Amazon VPC endpoints or specific VPCs. This effectively isolates network access to a given Amazon SNS topic from only the specific VPC within the AWS network. For more information, see Restrict publication to an Amazon SNS topic only from a specific VPC endpoint. Amazon SNS security best practices AWS provides many security features for Amazon SNS. Review these security features in the context of your own security policy. Note
sns-dg-288
sns-dg.pdf
288
location, but Amazon SNS supports resource- based access policies, which can include restrictions based on the source IP address. You can also use Amazon SNS policies to control access from specific Amazon VPC endpoints or specific VPCs. This effectively isolates network access to a given Amazon SNS topic from only the specific VPC within the AWS network. For more information, see Restrict publication to an Amazon SNS topic only from a specific VPC endpoint. Amazon SNS security best practices AWS provides many security features for Amazon SNS. Review these security features in the context of your own security policy. Note The guidance for these security features applies to common use cases and implementations. We recommend that you review these best practices in the context of your specific use case, architecture, and threat model. Preventative best practices The following are preventative security best practices for Amazon SNS. Topics Infrastructure security 1104 Amazon Simple Notification Service Developer Guide • Ensure topics aren't publicly accessible • Implement least-privilege access • Use IAM roles for applications and AWS services which require Amazon SNS access • Implement server-side encryption • Enforce encryption of data in transit • Consider using VPC endpoints to access Amazon SNS • Ensure subscriptions are not configured to deliver to raw http endpoints Ensure topics aren't publicly accessible Unless you explicitly require anyone on the internet to be able to read or write to your Amazon SNS topic, you should ensure that your topic isn't publicly accessible (accessible by everyone in the world or by any authenticated AWS user). • Avoid creating policies with Principal set to "". • Avoid using a wildcard (*). Instead, name a specific user or users. Implement least-privilege access When you grant permissions, you decide who receives them, which topics the permissions are for, and specific API actions that you want to allow for these topics. Implementing the principle of least privilege is important to reducing security risks. It also helps to reduce the negative effect of errors or malicious intent. Follow the standard security advice of granting least privilege. That is, grant only the permissions required to perform a specific task. You can implement least privilege by using a combination of security policies pertaining to user access. Amazon SNS uses the publisher-subscriber model, requiring three types of user account access: • Administrators – Access to creating, modifying, and deleting topics. Administrators also control topic policies. • Publishers – Access to sending messages to topics. • Subscribers – Access to subscribing to topics. For more information, see the following sections: Preventative best practices 1105 Amazon Simple Notification Service Developer Guide • Identity and access management in Amazon SNS • Amazon SNS API permissions: Actions and resources reference Use IAM roles for applications and AWS services which require Amazon SNS access For applications or AWS services, such as Amazon EC2, to access Amazon SNS topics, they must use valid AWS credentials in their AWS API requests. Because these credentials aren't rotated automatically, you shouldn't store AWS credentials directly in the application or EC2 instance. You should use an IAM role to manage temporary credentials for applications or services that need to access Amazon SNS. When you use a role, you don't need to distribute long-term credentials (such as a username, password, and access keys) to an EC2 instance or AWS service, such as AWS Lambda. Instead, the role supplies temporary permissions that applications can use when they make calls to other AWS resources. For more information, see IAM Roles and Common Scenarios for Roles: Users, Applications, and Services in the IAM User Guide. Implement server-side encryption To mitigate data leakage issues, use encryption at rest to encrypt your messages using a key stored in a different location from the location that stores your messages. Server-side encryption (SSE) provides data encryption at rest. Amazon SNS encrypts your data at the message level when it stores it, and decrypts the messages for you when you access them. SSE uses keys managed in AWS Key Management Service. When you authenticate your request and have access permissions, there is no difference between accessing encrypted and unencrypted topics. For more information, see Securing Amazon SNS data with server-side encryption and Managing Amazon SNS encryption keys and costs. Enforce encryption of data in transit It's possible, but not recommended, to publish messages that are not encrypted during transit by using HTTP. However, when a topic is encrypted at rest using AWS KMS, it is required to use HTTPS for publishing messages to ensure encryption both at rest and in transit. While the topic does not automatically reject HTTP messages, using HTTPS is necessary to maintain the security standards. Preventative best practices 1106 Amazon Simple Notification Service Developer Guide AWS recommends that you use HTTPS instead of HTTP. When you use HTTPS, messages are
sns-dg-289
sns-dg.pdf
289
SNS encryption keys and costs. Enforce encryption of data in transit It's possible, but not recommended, to publish messages that are not encrypted during transit by using HTTP. However, when a topic is encrypted at rest using AWS KMS, it is required to use HTTPS for publishing messages to ensure encryption both at rest and in transit. While the topic does not automatically reject HTTP messages, using HTTPS is necessary to maintain the security standards. Preventative best practices 1106 Amazon Simple Notification Service Developer Guide AWS recommends that you use HTTPS instead of HTTP. When you use HTTPS, messages are automatically encrypted during transit, even if the SNS topic itself isn't encrypted. Without HTTPS, a network-based attacker can eavesdrop on network traffic or manipulate it using an attack such as man-in-the-middle. To enforce only encrypted connections over HTTPS, add the aws:SecureTransport condition in the IAM policy that's attached to unencrypted SNS topics. This forces message publishers to use HTTPS instead of HTTP. You can use the following example policy as a guide: { "Id": "ExamplePolicy", "Version": "2012-10-17", "Statement": [ { "Sid": "AllowPublishThroughSSLOnly", "Action": "SNS:Publish", "Effect": "Deny", "Resource": [ "arn:aws:sns:us-east-1:1234567890:test-topic" ], "Condition": { "Bool": { "aws:SecureTransport": "false" } }, "Principal": "*" } ] } Consider using VPC endpoints to access Amazon SNS If you have topics that you must be able to interact with, but these topics must absolutely not be exposed to the internet, use VPC endpoints to limit topic access to only the hosts within a particular VPC. You can use topic policies to control access to topics from specific Amazon VPC endpoints or from specific VPCs. Amazon SNS VPC endpoints provide two ways to control access to your messages: • You can control the requests, users, or groups that are allowed through a specific VPC endpoint. • You can control which VPCs or VPC endpoints have access to your topic using a topic policy. Preventative best practices 1107 Amazon Simple Notification Service Developer Guide For more information, see Creating the endpoint and Creating an Amazon VPC endpoint policy for Amazon SNS. Ensure subscriptions are not configured to deliver to raw http endpoints Avoid configuring subscriptions to deliver to a raw http endpoints. Always have subscriptions delivering to an endpoint domain name. For example, a subscription configured to deliver to an endpoint, http://1.2.3.4/my-path, should be changed to http://my.domain.name/my- path. Preventative best practices 1108 Amazon Simple Notification Service Developer Guide Troubleshooting Amazon SNS topics using AWS X-Ray AWS X-Ray collects data about requests that your application serves, and lets you view and filter data to identify potential issues and opportunities for optimization. For any traced request to your application, you can see detailed information about the request, the response, and the calls that your application makes to downstream AWS resources, microservices, databases and HTTP web APIs. You can use X-Ray with Amazon SNS to trace and analyze the messages that travel through your application. You can use the AWS Management Console to view the map of connections between Amazon SNS and other services that your application uses. You can also use the console to view metrics such as average latency and failure rates. For more information, see Amazon SNS and AWS X-Ray in the AWS X-Ray Developer Guide. Active tracing in Amazon SNS Use AWS X-Ray to trace and analyze user requests as they pass through your Amazon SNS topics to Amazon Data Firehose, AWS Lambda, Amazon SQS, and HTTP/S endpoint subscriptions. With X-Ray, you get an end-to-end view of each request, allowing you to: • Identify what is calling your Amazon SNS topic and what services are downstream of its subscriptions. • Analyze latencies, such as: • Time spent in the Amazon SNS topic before processing. • Delivery times for each subscribed endpoint. Important Amazon SNS topics with numerous subscriptions may reach a size limit and not be fully traced. For information about trace document size limits, see X-ray service quotas in AWS General Reference. If you call an Amazon SNS API from a service that's already being traced, Amazon SNS passes the trace through, even if X-Ray tracing isn't enabled on the API. Active tracing 1109 Amazon Simple Notification Service Developer Guide Amazon SNS supports X-Ray tracing for both standard and FIFO topics. You can enable X-Ray for an Amazon SNS topic by using the Amazon SNS console, Amazon SNS SetTopicAttributes API, Amazon Simple Notification Service CLI Reference, or AWS CloudFormation. To learn more about using Amazon SNS with X-Ray, see Amazon SNS and AWS X-Ray in the AWS X- Ray Developer Guide. Active tracing permissions When using the Amazon SNS console, Amazon SNS attempts to create the necessary permissions for the Amazon SNS topic to call X-Ray. The attempt can be rejected if you don't have sufficient permissions to use the Amazon SNS console. For more information,
sns-dg-290
sns-dg.pdf
290
both standard and FIFO topics. You can enable X-Ray for an Amazon SNS topic by using the Amazon SNS console, Amazon SNS SetTopicAttributes API, Amazon Simple Notification Service CLI Reference, or AWS CloudFormation. To learn more about using Amazon SNS with X-Ray, see Amazon SNS and AWS X-Ray in the AWS X- Ray Developer Guide. Active tracing permissions When using the Amazon SNS console, Amazon SNS attempts to create the necessary permissions for the Amazon SNS topic to call X-Ray. The attempt can be rejected if you don't have sufficient permissions to use the Amazon SNS console. For more information, see Identity and access management in Amazon SNS and Example cases for Amazon SNS access control. When using the CLI, you must manually configure the permissions. Those permissions are configured using resource policies. For more on using required permissions in X-Ray, see Amazon SNS and AWS X-Ray. Enabling active tracing on an Amazon SNS topic using the AWS console When active tracing is enabled on an Amazon SNS topic, it reads the trace ID, sends the data to the customer based on the trace ID, and propagates the trace ID to downstream services. 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 a topic type: FIFO or Standard. a. b. Enter a Name for the topic. (Optional) Enter a Display name for the topic. 4. Expand Active tracing, and choose Use active tracing. Once you've enabled X-Ray for your Amazon SNS topic, you can use the X-Ray service map to view the end-to-end traces and service maps for the topic. Enabling active tracing on an Amazon SNS topic using the AWS SDK The following code example shows how to enable active tracing on an Amazon SNS topic by using the AWS SDK for Java. Permissions 1110 Amazon Simple Notification Service Developer Guide public static void enableActiveTracing(SnsClient snsClient, String topicArn) { try { SetTopicAttributesRequest request = SetTopicAttributesRequest.builder() .attributeName("TracingConfig") .attributeValue("Active") .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()); } } Enabling active tracing on an Amazon SNS topic using the AWS CLI The following code example shows how to enable active tracing on an Amazon SNS topic by using the AWS CLI. aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --attribute-name TracingConfig \ --attribute-value Active Enabling active tracing on an Amazon SNS topic using AWS CloudFormation The following AWS CloudFormation stack shows how to enable active tracing on an Amazon SNS topic. AWSTemplateFormatVersion: 2010-09-09 Resources: MyTopicResource: Enabling active tracing on an Amazon SNS topic using the AWS CLI 1111 Amazon Simple Notification Service Developer Guide Type: 'AWS::SNS::Topic' Properties: TopicName: 'MyTopic' TracingConfig: 'Active' Verifying active tracing is enabled for your topic You can use the Amazon SNS console to verify if active tracing is enabled for your topic, or when the resource policy has failed to be added. 1. 2. Sign in to the Amazon SNS console. In the left navigation pane, choose Topics. 3. On the Topics page, select a topic. 4. Choose the Integrations tab. When active tracing is enabled, a green Active icon is displayed. 5. If you have enabled active tracing and you don't see that the resource policy has been added, choose Create policy to add the additional required permissions. Verifying active tracing is enabled 1112 Amazon Simple Notification Service Developer Guide Testing active tracing 1. Sign in to the Amazon SNS console. 2. Create an Amazon SNS topic. For details on how to do this, see To create a topic using the AWS Management Console. 3. Expand Active tracing, and choose Use active tracing. 4. Publish a message to the Amazon SNS topic. For details on how to do this, see To publish messages to Amazon SNS topics using the AWS Management Console. 5. Use the X-Ray service map to view the end-to-end traces and service maps for the topic. Testing 1113 Amazon Simple Notification Service Developer Guide Testing 1114 Amazon Simple Notification Service Developer Guide Amazon SNS documentation history The following table describes recent changes to the Amazon Simple Notification Service Developer Guide. Service features are sometimes rolled out incrementally to the AWS Regions where a service is available. We update this documentation for the first release only. We don't provide information about Region availability or announce subsequent Region rollouts. For information about Region availability of service features and to subscribe to notifications about updates, see What's New with AWS?. Change Description Date Added support for dual-stack (IPv4 and IPv6) endpoints Amazon SNS now supports IPv6 for API requests, April
sns-dg-291
sns-dg.pdf
291
Simple Notification Service Developer Guide Amazon SNS documentation history The following table describes recent changes to the Amazon Simple Notification Service Developer Guide. Service features are sometimes rolled out incrementally to the AWS Regions where a service is available. We update this documentation for the first release only. We don't provide information about Region availability or announce subsequent Region rollouts. For information about Region availability of service features and to subscribe to notifications about updates, see What's New with AWS?. Change Description Date Added support for dual-stack (IPv4 and IPv6) endpoints Amazon SNS now supports IPv6 for API requests, April 3, 2025 Amazon SNS added the FifoThroughputScope attribute for Amazon SNS FIFO topics AmazonSNSFullAccess and AmazonSNSReadOnlyA ccess managed policy updates January 21, 2025 September 24, 2024 allowing clients to connect to public endpoints using IPv4, IPv6, or dual stack. Amazon SNS support the FifoThroughputScope attribute, which specifies the throughput quota and deduplication behaviour to apply for the FIFO topic. Valid values are Topic or MessageGroup . Amazon SNS added new permissions the AmazonSNS FullAccess and AmazonSNS ReadOnlyAccess managed policies, which allows additional access to Amazon SNS via the AWS Managemen t Console. 1115 Amazon Simple Notification Service Developer Guide Amazon SNS integration with AWS End User Messaging SMS Amazon SNS supports new features such as SMS resource September 24, 2024 for delivery of SMS messages management, two-way messaging, granular resource permissions, country block rules, and centralized billing for all AWS SMS messaging without making any changes to configurations or the global AWS SMS network used by Amazon SNS. Canada West (Calgary) support for FIFO topics Amazon SNS supports FIFO topic in Canada West March 28, 2024 (Calgary). Amazon SNS SMS support in five new regions Amazon SNS added SMS support to the following February 8, 2024 regions: Asia Pacific (Hyderabad), Asia Pacific (Melbourne), Middle East (UAE), Europe (Zurich). and Europe (Spain). Firebase Cloud Messaging (FCM) HTTP v1 support Amazon SNS supports FCM v1 credentials. January 18, 2024 Amazon SNS SMS supported in Asia Pacific (Jakarta) Amazon SNS supports SMS messaging in Asia Pacific (Jakarta). December 14, 2023 AWS CloudFormation support for configuring DeliveryS AWS CloudFormation support is available for configuring December 7, 2023 tatusLogging Amazon SNS topics for DeliveryStatusLogg ing while creating or updating Amazon SNS topics. 1116 Amazon Simple Notification Service New message filtering operators added You can now use suffix matching, equals-ignore case, and OR operators when filtering Amazon SNS messages. Developer Guide November 16, 2023 Support added for message archiving and replay Topic owners can archive messages to a topic for up October 26, 2023 to 365 days. Topic subscribe rs can replay the archived messages back to a subscribe d endpoint to recover messages due to a failure in a downstream application, or to replicate the state of an existing application. Support added for subscribi ng a standard queue to a FIFO You can subscribe an Amazon SQS FIFO queue or a standard September 14, 2023 topic queue to an Amazon SNS FIFO topic. Only Amazon SQS FIFO queues guarantee messages are received in order and with no duplicates. SMS support added for Israel (Tel Aviv) Amazon SNS SMS is now supported in the Israel (Tel August 28, 2023 Aviv) region. 1117 Amazon Simple Notification Service Developer Guide Support for X-Ray active tracing added to FIFO topics Previously only supported with Amazon SNS standard May 31, 2023 Enhanced Content-Type header support Active tracing support added topics, AWS X-Ray now traces and analyzes user requests as they travel through your FIFO topics to your Amazon Data Firehose, AWS Lambda, Amazon SQS, and HTTP/S endpoint subscriptions. You can set the Content-Type header in the request policy to specify the media type of the notification. AWS X-Ray traces and analyzes user requests as they travel through your Amazon SNS standard topics to your Amazon Data Firehose, AWS Lambda, Amazon SQS, and HTTP/S endpoint subscript ions. March 23, 2023 February 8, 2023 Singapore Sender ID registrat ion Instructions added for registering Sender IDs in January 10, 2023 Payload-based message filtering Singapore. Payload-based filtering lets you filter messages based on the message payload and avoid the costs associated with processing unwanted data. November 22, 2022 1118 Amazon Simple Notification Service Developer Guide SHA256 hash algorithm added for Amazon SNS Support added for SHA256 hash algorithm when using message signing Amazon SNS message September 15, 2022 signing. Additional regions added to SMS messaging Amazon SNS supports SMS messaging in the following September 9, 2022 Message data protection support added September 8, 2022 regions: Africa (Cape Town), Asia Pacific (Osaka), Europe (Milan) and AWS GovCloud (US-East). Message data protection safeguards the data that's published to your Amazon SNS topics by using data protection policies to audit and block the sensitive information that moves between applications or AWS services. New registration process for toll-free
sns-dg-292
sns-dg.pdf
292
Guide SHA256 hash algorithm added for Amazon SNS Support added for SHA256 hash algorithm when using message signing Amazon SNS message September 15, 2022 signing. Additional regions added to SMS messaging Amazon SNS supports SMS messaging in the following September 9, 2022 Message data protection support added September 8, 2022 regions: Africa (Cape Town), Asia Pacific (Osaka), Europe (Milan) and AWS GovCloud (US-East). Message data protection safeguards the data that's published to your Amazon SNS topics by using data protection policies to audit and block the sensitive information that moves between applications or AWS services. New registration process for toll-free numbers Support added for sending for Amazon SNS messages August 1, 2022 using toll-free phone numbers (TFN) to United States recipients. 1119 Amazon Simple Notification Service Developer Guide Support for Attribute-based access controls (ABAC) Added support for attribute- based access control (ABAC) January 10, 2022 for API actions including Publish and PublishBa tch . ABAC is an authoriza tion strategy that defines access permissions based on tags which can be attached to IAM resources, such as IAM users and roles, and to AWS resources, like Amazon SNS topics, to simplify permission management. Support for Apple token-bas ed authentication for push You can authorize Amazon SNS to send push notificat October 28, 2021 notifications ions to your iOS or macOS app by providing informati on that identifies you as the developer of the app. New senders of SMS messages are placed in the The SMS sandbox exists to help prevent fraud and abuse, June 1, 2021 SMS sandbox and to help protect your reputation as a sender. While your AWS account is in the SMS sandbox, you can send SMS messages only to verified destination phone numbers. 1120 Amazon Simple Notification Service Developer Guide New senders of SMS messages are placed in the The SMS sandbox exists to help prevent fraud and abuse, June 1, 2021 SMS sandbox New attributes for sending SMS messages to recipients in India and to help protect your reputation as a sender. While your AWS account is in the SMS sandbox, you can send SMS messages only to verified destination phone numbers. Two new attributes, Entity ID and Template ID, are now required for sending SMS messages to recipients in India. April 22, 2021 Updates to message filtering operators A new operator, cidr, is available for matching April 7, 2021 message source IP addresses and subnets. You can now also check for the absence of an attribute key, and use a prefix with the anything- but operator for attribute string matching. Ending support for P2P long codes for US destinations Effective June 1, 2021, US telecom providers no longer February 16, 2021 support using person-to -person (P2P) long codes for application-to-person (A2P) communications to US destinations. Instead, you can use short codes, toll-free numbers, or a new type of origination number called 10DLC. 1121 Amazon Simple Notification Service Developer Guide Support for 1-minute Amazon CloudWatch metrics The 1-minute CloudWatch metric for Amazon SNS is now January 28, 2021 Support for Amazon Data Firehose endpoints January 12, 2021 available in all AWS Regions. You can subscribe Firehose delivery streams to SNS topics. This 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. Origination numbers are available You can use origination numbers when sending text October 23, 2020 messages (SMS). Support for Amazon SNS FIFO topics To integrate distributed applications that require October 22, 2020 data consistency in near-real time, you can use Amazon SNS first-in, first-out (FIFO) topics with Amazon SQS FIFO queues. The Amazon SNS Extended Client Library for Java is available You can use this library to publish large Amazon SNS messages. August 25, 2020 SSE is available in the China Regions Server-side encryption (SSE) for Amazon SNS is available in the China Regions. January 20, 2020 1122 Amazon Simple Notification Service Developer Guide Support for using DLQs to capture undeliverable messages To capture undeliverable messages, you can use an Amazon SQS dead-letter queue (DLQ) with an Amazon SNS subscription. November 14, 2019 Support for specifying custom APNs header values You can specify a custom APNs header value. October 18, 2019 Support for the 'apns-push -type ' header field for APNs You can use the apns-push -type header field for mobile notifications sent through APNs. September 10, 2019 Support for topic troublesh ooting using AWS X-Ray You can use X-Ray to troubleshoot messages July 24, 2019 Support for attribute key matching using the 'exists' operator passing through SNS topics. To check whether an incoming message has an attribute whose key is listed in the filter policy, you can use the exists operator. July 5, 2019 Support for anything-but matching of multiple numeric In addition to
sns-dg-293
sns-dg.pdf
293
APNs header value. October 18, 2019 Support for the 'apns-push -type ' header field for APNs You can use the apns-push -type header field for mobile notifications sent through APNs. September 10, 2019 Support for topic troublesh ooting using AWS X-Ray You can use X-Ray to troubleshoot messages July 24, 2019 Support for attribute key matching using the 'exists' operator passing through SNS topics. To check whether an incoming message has an attribute whose key is listed in the filter policy, you can use the exists operator. July 5, 2019 Support for anything-but matching of multiple numeric In addition to multiple strings, Amazon SNS allows anything- July 5, 2019 values Amazon SNS release notes are available as an RSS feed but matching of multiple numeric values. Following the title on this page (Documentation history), choose RSS. June 22, 2019 1123
sns-or-sqs-or-eventbridge-001
sns-or-sqs-or-eventbridge.pdf
1
AWS Decision guide Amazon SQS, Amazon SNS, or EventBridge? Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Amazon SQS, Amazon SNS, or EventBridge?: AWS Decision guide Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Table of Contents Decision guide .................................................................................................................................. 1 Introduction ................................................................................................................................................... 1 Details on the differences ........................................................................................................................... 3 Use ................................................................................................................................................................... 7 Document history .......................................................................................................................... 10 iii Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Amazon SQS, Amazon SNS, or Amazon EventBridge? Understand the differences and pick the one that's right for you Purpose Last updated Covered services Introduction Understand the differences between Amazon SQS, Amazon SNS, and EventBridge and determine which service is the best fit for your needs. July 31, 2024 • Amazon Simple Queue Service • Amazon Simple Notification Service • Amazon EventBridge When building applications on AWS, you might want help in choosing the right service for handling messaging, event-driven architectures, and decoupling components. AWS offers three key services for these purposes—Amazon Simple Queue Service (Amazon SQS), Amazon Simple Notification Service (Amazon SNS), and Amazon EventBridge (formerly known as CloudWatch Events). • Amazon SQS is a fully managed message queuing service that enables decoupling and scaling of microservices, distributed systems, and serverless applications. • Amazon SNS is a highly available, durable, and secure pub/sub messaging service that allows decoupled applications to communicate with each other using a publish-subscribe model. • Amazon EventBridge is a serverless event bus designed to make it easier to build event-driven architectures by allowing you to connect applications using data from various sources and route it to targets like AWS Lambda. While all three services facilitate communication between decoupled components, they differ in their underlying architecture, use cases, and capabilities. Here's a high-level view of the key differences between these services to get you started. Introduction 1 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Category Amazon SQS Amazon SNS EventBridge Communication model Pull-based (consumer s poll messages from Push-based (subscrib ers receive messages Pushed-based. Event- driven (rules match the queue) when published) events and route to targets) Persistence Messages persist until consumed or expired Messages do not persist; delivered in Events do not persist; processed in real- Delivery guarantees At-least-once delivery real-time to subscribe time rs At-least-once delivery At-least-once delivery for HTTP/S, exactly- once for Lambda and Amazon SQS Message ordering FIFO (First-In-First- Out) queues ensure Amazon SNS FIFO topics guarantee No ordering guarantees strict ordering order Message filtering Amazon SQS can’t decide consumer Message filtering using subscript Complex event pattern matching based on message. ion filter policies and content-based Use Amazon SNS based on message filtering message filtering metadata and for with Amazon SQS to FIFO topics, message achieve. content Supported subscribe rs Pull-based consumers (such as Amazon EC2 or Lambda) HTTP/S endpoints, email, SMS, mobile push, Lambda, Amazon SQS AWS services, Lambda, API destinati ons, event buses in other AWS accounts Typical use cases Decoupling microserv ices, buffering requests, processing Fanout notifications, pub/sub messaging, mobile push notificat Event-driven architectures, real- time stream processin tasks asynchronously ions Introduction 2 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Category Amazon SQS Amazon SNS EventBridge Integration with other AWS services Lambda, CloudWatch, AWS KMS, IAM Lambda, Amazon SQS, Mobile Push, AWS KMS, IAM g, cross-account event sharing Lambda, Step Functions, Amazon SQS, Amazon SNS, Kinesis, SageMaker AI, CloudWatch, IAM Details on the differences Explore differences between Amazon SQS, Amazon SNS, and EventBridge in eight key areas. These cover communication model, persistence, message ordering, filtering, integrations, use cases, scalability, and pricing. Communication model Amazon SQS • Pull-based model where consumers actively poll messages from the queue, allowing for fine- grained control over message processing rates and independent scaling of consumers. Amazon SNS • Push-based model where subscribers receive messages in real-time as they are published, enabling immediate message delivery to multiple subscribers. Amazon EventBridge • Event-driven model where events are matched against predefined rules and routed to target services for processing, facilitating the building of reactive, event-driven architectures. Persistence and delivery guarantees Amazon SQS Details on the differences 3 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide • Messages are persisted in the queue until consumed or expired, ensuring no message loss. Provides at-least-once delivery, guaranteeing that every message is delivered at
sns-or-sqs-or-eventbridge-002
sns-or-sqs-or-eventbridge.pdf
2
processing rates and independent scaling of consumers. Amazon SNS • Push-based model where subscribers receive messages in real-time as they are published, enabling immediate message delivery to multiple subscribers. Amazon EventBridge • Event-driven model where events are matched against predefined rules and routed to target services for processing, facilitating the building of reactive, event-driven architectures. Persistence and delivery guarantees Amazon SQS Details on the differences 3 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide • Messages are persisted in the queue until consumed or expired, ensuring no message loss. Provides at-least-once delivery, guaranteeing that every message is delivered at least once, with the possibility of duplicates. Amazon SNS • Messages are not persisted and are delivered to subscribers in real-time. Offers at-least- once delivery for HTTP/S subscribers and exactly-once delivery for Lambda and Amazon SQS subscribers. Amazon EventBridge • Events are not persisted and are processed in real-time. Ensures exactly-once processing, guaranteeing that each event is processed only once by the target services. Message ordering Amazon SQS and Amazon SNS • Amazon SQS FIFO queues and Amazon SNS FIFO topics support First-In-First-Out guaranteed message ordering, making them suitable for scenarios requiring sequential processing. See message ordering details for FIFO topics for more information on message ordering using Amazon SNS and Amazon SQS. Amazon EventBridge • EventBridge does not provide message ordering guarantees, instead delivering events to targets in an arbitrary order. Message filtering and routing Amazon SQS • Offers basic filtering capabilities through visibility timeouts (to prevent duplicate processing) and dead-letter queues (to handle failed messages). Amazon SNS Details on the differences 4 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide • Provides message filtering using subscription filter policies, allowing subscribers to selectively receive messages based on message attributes. Amazon EventBridge • Supports advanced event pattern matching and content-based filtering, enabling fine- grained event processing and routing based on event content. Supported subscribers and integrations Amazon SQS • Supports pull-based consumers, such as Amazon EC2 instances or Lambda functions, which actively retrieve messages from the queue. Amazon SNS • Supports a wide range of subscribers, including HTTP/S endpoints, email, SMS, mobile push notifications, Lambda functions, and Amazon SQS queues. Amazon EventBridge • Integrates with numerous AWS services, such as Lambda, Step Functions, Amazon SQS, Amazon SNS, Kinesis, and SageMaker AI, allowing event routing based on predefined rules. EventBridge also has numerous built-in integrations with third party products such as PagerDuty, DataDog, NewRelilc. To see the complete list visit Amazon EventBridge targets. Typical use cases Amazon SQS • Commonly used for decoupling microservices, buffering requests, and processing tasks asynchronously, enabling independent scaling and graceful failure handling. Amazon SNS Details on the differences 5 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide • Often used for fanout notifications, pub/sub messaging, and mobile push notifications, facilitating the broadcasting of messages to multiple subscribers simultaneously. Amazon EventBridge • Ideal for building event-driven architectures, real-time stream processing, and cross-account event sharing, allowing reactive systems to be built across multiple services. Scalability and performance Amazon SQS • Highly scalable, automatically scaling based on the number of messages and consumers, providing high throughput for message processing. Amazon SNS • Highly scalable, capable of delivering messages to a large number of subscribers, with elastic scaling to handle increasing publish and subscribe demands. Amazon EventBridge • Automatically scales based on incoming event traffic, offering low-latency event processing and near real-time delivery to targets. Pricing Amazon SQS • Pricing based on the number of API requests and data transferred, with a free tier including a monthly allowance of free API requests and data transfer. Amazon SNS • Pricing is based on the number of API requests, notifications delivered, and data transferred. Amazon SNS SMS messages are billed through AWS End User Messaging. Details on the differences 6 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Amazon EventBridge • Pricing based on the number of events published and target invocations, with a free tier that includes a monthly allowance of free events and invocations. Use Amazon SQS • Get started with Amazon SQS Get step-by-step instructions on setting up and using Amazon SQS. It covers topics such as creating a queue, sending and receiving messages, and configuring queue properties. Explore the guide • Amazon SQS tutorial Walk through a practical example of using Amazon SQS to decouple the components of a simple application. It demonstrates how to create a queue, send messages to the queue, and process messages from the queue using AWS SDKs. Explore the tutorial • Orchestrate Queue-based Microservices Learn how to design and run a serverless workflow that orchestrates a message queue-based microservice. Explore the tutorial • Send Fanout Event Notifications Learn how to implement a fanout messaging scenario using Amazon SQS and Amazon SNS. Explore the tutorial Amazon SNS • Get started with
sns-or-sqs-or-eventbridge-003
sns-or-sqs-or-eventbridge.pdf
3
queue properties. Explore the guide • Amazon SQS tutorial Walk through a practical example of using Amazon SQS to decouple the components of a simple application. It demonstrates how to create a queue, send messages to the queue, and process messages from the queue using AWS SDKs. Explore the tutorial • Orchestrate Queue-based Microservices Learn how to design and run a serverless workflow that orchestrates a message queue-based microservice. Explore the tutorial • Send Fanout Event Notifications Learn how to implement a fanout messaging scenario using Amazon SQS and Amazon SNS. Explore the tutorial Amazon SNS • Get started with Amazon SNS Use 7 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide A step-by-step walkthrough of setting up and using Amazon SNS. It covers topics such as creating a topic, subscribing endpoints to a topic, publishing messages, and configuring access permissions. Explore the guide • Filter Messages Published to Topics with Amazon SNS and Amazon SQS Learn how to use the message filtering feature of Amazon SNS Explore the tutorial • Amazon SNS - Troubleshooting Learn how to view configuration information, monitor processes, and gather diagnostic data about Amazon SNS. Explore the course EventBridge • Amazon EventBridge User Guide This comprehensive documentation covers topics such as creating event buses, defining event rules, setting up targets, and integrating with various AWS services. Explore the guide • Amazon EventBridge Tutorials The AWS documentation offers a series of tutorials that walk users through different use cases and scenarios using Amazon EventBridge. These tutorials cover topics like scheduling automated tasks, reacting to changes in AWS resources, and integrating with AWS services. Explore the tutorials • AWS Serverless Workshops - Event-Driven Architecture Build event-driven architectures using Amazon EventBridge and other AWS serverless services. This workshop guides participants through the process of creating event buses, defining event rules, and triggering actions based on events. Explore the workshop Use 8 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide • AWS Online Tech Talk - Introduction to Amazon EventBridge Get an introduction to Amazon EventBridge, explaining key concepts, features, and use cases. The tech talk includes demonstrations and practical examples to help users understand how to leverage EventBridge in their applications. Watch the video • Building Event-Driven Applications with Amazon EventBridge This blog post explores the process of building event-driven applications using Amazon EventBridge. It provides a step-by-step guide on creating event buses, defining event patterns, and setting up targets to process events. Read the blog post • Create Point-to-Point Integrations Between Event Producers and Consumers with Amazon EventBridge Pipes Explore Amazon EventBridge Pipes, a feature of EventBridge that makes it easier for you to build event-driven applications by providing a consistent and cost-effective way to create point-to-point integrations between event producers and consumers, removing the need to write undifferentiated glue code. Read the blog post Use 9 Amazon SQS, Amazon SNS, or EventBridge? AWS Decision guide Document history The following table describes the important changes to this decision guide. For notifications about updates to this guide, you can subscribe to an RSS feed. Change Description Date Initial publication Guide first published. July 31, 2024 10
social-api-001
social-api.pdf
1
API Reference AWS End User Messaging Social API Version 2024-01-01 Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. AWS End User Messaging Social API Reference AWS End User Messaging Social: API Reference Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. AWS End User Messaging Social Table of Contents API Reference Welcome ........................................................................................................................................... 1 Actions .............................................................................................................................................. 2 AssociateWhatsAppBusinessAccount ........................................................................................................ 3 Request Syntax ........................................................................................................................................ 3 URI Request Parameters ........................................................................................................................ 4 Request Body ........................................................................................................................................... 4 Response Syntax ...................................................................................................................................... 4 Response Elements ................................................................................................................................. 5 Errors .......................................................................................................................................................... 5 See Also ..................................................................................................................................................... 6 DeleteWhatsAppMessageMedia ................................................................................................................. 8 Request Syntax ........................................................................................................................................ 8 URI Request Parameters ........................................................................................................................ 8 Request Body ........................................................................................................................................... 8 Response Syntax ...................................................................................................................................... 9 Response Elements ................................................................................................................................. 9 Errors .......................................................................................................................................................... 9 See Also .................................................................................................................................................. 10 DisassociateWhatsAppBusinessAccount ................................................................................................. 12 Request Syntax ...................................................................................................................................... 12 URI Request Parameters ...................................................................................................................... 12 Request Body ......................................................................................................................................... 12 Response Syntax ................................................................................................................................... 12 Response Elements ............................................................................................................................... 12 Errors ....................................................................................................................................................... 12 See Also .................................................................................................................................................. 13 GetLinkedWhatsAppBusinessAccount .................................................................................................... 15 Request Syntax ...................................................................................................................................... 15 URI Request Parameters ...................................................................................................................... 15 Request Body ......................................................................................................................................... 15 Response Syntax ................................................................................................................................... 15 Response Elements ............................................................................................................................... 16 Errors ....................................................................................................................................................... 16 See Also .................................................................................................................................................. 17 API Version 2024-01-01 iii AWS End User Messaging Social API Reference GetLinkedWhatsAppBusinessAccountPhoneNumber .......................................................................... 19 Request Syntax ...................................................................................................................................... 19 URI Request Parameters ...................................................................................................................... 19 Request Body ......................................................................................................................................... 19 Response Syntax ................................................................................................................................... 19 Response Elements ............................................................................................................................... 20 Errors ....................................................................................................................................................... 20 See Also .................................................................................................................................................. 21 GetWhatsAppMessageMedia .................................................................................................................... 23 Request Syntax ...................................................................................................................................... 23 URI Request Parameters ...................................................................................................................... 23 Request Body ......................................................................................................................................... 23 Response Syntax ................................................................................................................................... 25 Response Elements ............................................................................................................................... 25 Errors ....................................................................................................................................................... 25 See Also .................................................................................................................................................. 26 ListLinkedWhatsAppBusinessAccounts ................................................................................................... 28 Request Syntax ...................................................................................................................................... 28 URI Request Parameters ...................................................................................................................... 28 Request Body ......................................................................................................................................... 28 Response Syntax ................................................................................................................................... 28 Response Elements ............................................................................................................................... 29 Errors ....................................................................................................................................................... 29 See Also .................................................................................................................................................. 30 ListTagsForResource ................................................................................................................................... 32 Request Syntax ...................................................................................................................................... 32 URI Request Parameters ...................................................................................................................... 32 Request Body ......................................................................................................................................... 32 Response Syntax ................................................................................................................................... 32 Response Elements ............................................................................................................................... 33 Errors ....................................................................................................................................................... 33 See Also .................................................................................................................................................. 34 PostWhatsAppMessageMedia .................................................................................................................. 35 Request Syntax ...................................................................................................................................... 35 URI Request Parameters ...................................................................................................................... 35 Request Body ......................................................................................................................................... 35 API Version 2024-01-01 iv AWS End User Messaging Social API Reference Response Syntax ................................................................................................................................... 36 Response Elements ............................................................................................................................... 36 Errors ....................................................................................................................................................... 37 See Also .................................................................................................................................................. 38 PutWhatsAppBusinessAccountEventDestinations ................................................................................ 39 Request Syntax ...................................................................................................................................... 39 URI Request Parameters ...................................................................................................................... 39 Request Body ......................................................................................................................................... 39 Response Syntax ................................................................................................................................... 40 Response Elements ............................................................................................................................... 40 Errors ....................................................................................................................................................... 40 See Also .................................................................................................................................................. 41 SendWhatsAppMessage ............................................................................................................................ 42 Request Syntax ...................................................................................................................................... 42 URI Request Parameters ...................................................................................................................... 42 Request Body ......................................................................................................................................... 42 Response Syntax ................................................................................................................................... 43 Response Elements ............................................................................................................................... 43 Errors ....................................................................................................................................................... 43 See Also .................................................................................................................................................. 44 TagResource ................................................................................................................................................. 46 Request Syntax ...................................................................................................................................... 46 URI Request Parameters ...................................................................................................................... 46 Request Body ......................................................................................................................................... 46 Response Syntax ................................................................................................................................... 47 Response Elements ............................................................................................................................... 47 Errors ....................................................................................................................................................... 47 See Also .................................................................................................................................................. 48 UntagResource ............................................................................................................................................ 49 Request Syntax ...................................................................................................................................... 49 URI Request Parameters ...................................................................................................................... 49 Request Body ......................................................................................................................................... 49 Response Syntax ................................................................................................................................... 50 Response Elements ............................................................................................................................... 50 Errors ....................................................................................................................................................... 50 See Also .................................................................................................................................................. 51 API Version 2024-01-01 v AWS End User Messaging Social API Reference Data Types ..................................................................................................................................... 52 LinkedWhatsAppBusinessAccount ........................................................................................................... 53 Contents .................................................................................................................................................. 53 See Also .................................................................................................................................................. 54 LinkedWhatsAppBusinessAccountIdMetaData ...................................................................................... 56 Contents .................................................................................................................................................. 56 See Also .................................................................................................................................................. 57 LinkedWhatsAppBusinessAccountSummary ......................................................................................... 58 Contents .................................................................................................................................................. 58 See Also .................................................................................................................................................. 59 S3File ............................................................................................................................................................ 60 Contents .................................................................................................................................................. 60 See Also .................................................................................................................................................. 60 S3PresignedUrl ............................................................................................................................................ 61 Contents .................................................................................................................................................. 61 See Also .................................................................................................................................................. 61 Tag ................................................................................................................................................................. 62 Contents .................................................................................................................................................. 62 See Also .................................................................................................................................................. 62 WabaPhoneNumberSetupFinalization ................................................................................................... 63 Contents .................................................................................................................................................. 63 See Also .................................................................................................................................................. 64 WabaSetupFinalization .............................................................................................................................. 66 Contents .................................................................................................................................................. 66 See Also .................................................................................................................................................. 66 WhatsAppBusinessAccountEventDestination ........................................................................................ 68 Contents .................................................................................................................................................. 68 See Also .................................................................................................................................................. 68 WhatsAppPhoneNumberDetail ................................................................................................................ 69 Contents .................................................................................................................................................. 69 See Also .................................................................................................................................................. 70 WhatsAppPhoneNumberSummary ......................................................................................................... 72 Contents .................................................................................................................................................. 72 See Also .................................................................................................................................................. 73 WhatsAppSetupFinalization ..................................................................................................................... 75 Contents .................................................................................................................................................. 75 API Version 2024-01-01 vi AWS End User Messaging Social API Reference See Also .................................................................................................................................................. 76 WhatsAppSignupCallback ......................................................................................................................... 77 Contents .................................................................................................................................................. 77 See Also .................................................................................................................................................. 77 WhatsAppSignupCallbackResult .............................................................................................................. 78 Contents .................................................................................................................................................. 78 See Also .................................................................................................................................................. 78 Common Parameters ..................................................................................................................... 79 Common Errors .............................................................................................................................. 82 API Version 2024-01-01 vii AWS End User Messaging Social API Reference Welcome AWS End User Messaging Social, also referred to as Social messaging, is a messaging service that enables application developers to incorporate WhatsApp into their existing workflows. The AWS End User Messaging Social API provides information about the AWS End User Messaging Social API resources, including supported HTTP methods, parameters, and schemas. The AWS End User
social-api-002
social-api.pdf
2
Reference See Also .................................................................................................................................................. 76 WhatsAppSignupCallback ......................................................................................................................... 77 Contents .................................................................................................................................................. 77 See Also .................................................................................................................................................. 77 WhatsAppSignupCallbackResult .............................................................................................................. 78 Contents .................................................................................................................................................. 78 See Also .................................................................................................................................................. 78 Common Parameters ..................................................................................................................... 79 Common Errors .............................................................................................................................. 82 API Version 2024-01-01 vii AWS End User Messaging Social API Reference Welcome AWS End User Messaging Social, also referred to as Social messaging, is a messaging service that enables application developers to incorporate WhatsApp into their existing workflows. The AWS End User Messaging Social API provides information about the AWS End User Messaging Social API resources, including supported HTTP methods, parameters, and schemas. The AWS End User Messaging Social API provides programmatic access to options that are unique to the WhatsApp Business Platform. If you're new to the AWS End User Messaging Social API, it's also helpful to review What is AWS End User Messaging Social in the AWS End User Messaging Social User Guide. The AWS End User Messaging Social User Guide provides tutorials, code samples, and procedures that demonstrate how to use AWS End User Messaging Social API features programmatically and how to integrate functionality into applications. The guide also provides key information, such as integration with other AWS services, and the quotas that apply to use of the service. Regional availability The AWS End User Messaging Social API is available across several AWS Regions and it provides a dedicated endpoint for each of these Regions. For a list of all the Regions and endpoints where the API is currently available, see AWS Service Endpoints and AWS End User Messaging endpoints and quotas in the AWS General Reference. To learn more about AWS Regions, see Managing AWS Regions in the AWS General Reference. In each Region, AWS maintains multiple Availability Zones. These Availability Zones are physically isolated from each other, but are united by private, low-latency, high-throughput, and highly redundant network connections. These Availability Zones enable us to provide very high levels of availability and redundancy, while also minimizing latency. To learn more about the number of Availability Zones that are available in each Region, see AWS Global Infrastructure. This document was last published on May 21, 2025. API Version 2024-01-01 1 AWS End User Messaging Social API Reference Actions The following actions are supported: • AssociateWhatsAppBusinessAccount • DeleteWhatsAppMessageMedia • DisassociateWhatsAppBusinessAccount • GetLinkedWhatsAppBusinessAccount • GetLinkedWhatsAppBusinessAccountPhoneNumber • GetWhatsAppMessageMedia • ListLinkedWhatsAppBusinessAccounts • ListTagsForResource • PostWhatsAppMessageMedia • PutWhatsAppBusinessAccountEventDestinations • SendWhatsAppMessage • TagResource • UntagResource API Version 2024-01-01 2 AWS End User Messaging Social API Reference AssociateWhatsAppBusinessAccount This is only used through the AWS console during sign-up to associate your WhatsApp Business Account to your AWS account. Request Syntax POST /v1/whatsapp/signup HTTP/1.1 Content-type: application/json { "setupFinalization": { "associateInProgressToken": "string", "phoneNumberParent": "string", "phoneNumbers": [ { "dataLocalizationRegion": "string", "id": "string", "tags": [ { "key": "string", "value": "string" } ], "twoFactorPin": "string" } ], "waba": { "eventDestinations": [ { "eventDestinationArn": "string", "roleArn": "string" } ], "id": "string", "tags": [ { "key": "string", "value": "string" } ] } }, AssociateWhatsAppBusinessAccount API Version 2024-01-01 3 AWS End User Messaging Social API Reference "signupCallback": { "accessToken": "string" } } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. setupFinalization A JSON object that contains the phone numbers and WhatsApp Business Account to link to your account. Type: WhatsAppSetupFinalization object Required: No signupCallback Contains the callback access token. Type: WhatsAppSignupCallback object Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "signupCallbackResult": { "associateInProgressToken": "string", "linkedAccountsWithIncompleteSetup": { "string" : { "accountName": "string", "registrationStatus": "string", URI Request Parameters API Version 2024-01-01 4 AWS End User Messaging Social API Reference "unregisteredWhatsAppPhoneNumbers": [ { "arn": "string", "displayPhoneNumber": "string", "displayPhoneNumberName": "string", "metaPhoneNumberId": "string", "phoneNumber": "string", "phoneNumberId": "string", "qualityRating": "string" } ], "wabaId": "string" } } }, "statusCode": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. signupCallbackResult Contains your WhatsApp registration status. Type: WhatsAppSignupCallbackResult object statusCode The status code for the response. Type: Integer Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. Response Elements API Version 2024-01-01 5 AWS End User Messaging Social HTTP Status Code: 403 DependencyException API Reference Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ •
social-api-003
social-api.pdf
3
Messaging Social HTTP Status Code: 403 DependencyException API Reference Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 6 AWS End User Messaging Social API Reference See Also API Version 2024-01-01 7 AWS End User Messaging Social API Reference DeleteWhatsAppMessageMedia Delete a media object from the WhatsApp service. If the object is still in an Amazon S3 bucket you should delete it from there too. Request Syntax DELETE /v1/whatsapp/media? mediaId=mediaId&originationPhoneNumberId=originationPhoneNumberId HTTP/1.1 URI Request Parameters The request uses the following URI parameters. mediaId The unique identifier of the media file to delete. Use the mediaId returned from PostWhatsAppMessageMedia. Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [A-Za-z0-9]+ Required: Yes originationPhoneNumberId The unique identifier of the originating phone number associated with the media. Phone number identifiers are formatted as phone-number- id-01234567890123456789012345678901. Use GetLinkedWhatsAppBusinessAccount to find a phone number's id. Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes Request Body The request does not have a request body. DeleteWhatsAppMessageMedia API Version 2024-01-01 8 API Reference AWS End User Messaging Social Response Syntax HTTP/1.1 200 Content-type: application/json { "success": boolean } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. success Success indicator for deleting the media file. Type: Boolean Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedByMetaException You do not have sufficient access to perform this action. HTTP Status Code: 403 AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 DependencyException Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 Response Syntax API Version 2024-01-01 9 AWS End User Messaging Social InternalServiceException API Reference The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin See Also API Version 2024-01-01 10 AWS End User Messaging Social • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 11 AWS End User Messaging Social API Reference DisassociateWhatsAppBusinessAccount Disassociate a WhatsApp Business Account (WABA) from your AWS account. Request Syntax DELETE /v1/whatsapp/waba/disassociate?id=id HTTP/1.1 URI Request Parameters The request uses the following URI parameters. id The unique identifier of your WhatsApp Business Account. WABA identifiers are formatted as waba-01234567890123456789012345678901. Use ListLinkedWhatsAppBusinessAccounts to list all WABAs and their details. Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: Yes Request Body The request does not have a request body. Response Syntax HTTP/1.1 200 Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. DisassociateWhatsAppBusinessAccount API Version 2024-01-01 12 API Reference AWS End User Messaging Social AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 DependencyException Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also
social-api-004
social-api.pdf
4
actions, see Common Errors. DisassociateWhatsAppBusinessAccount API Version 2024-01-01 12 API Reference AWS End User Messaging Social AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 DependencyException Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ See Also API Version 2024-01-01 13 AWS End User Messaging Social • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 14 AWS End User Messaging Social API Reference GetLinkedWhatsAppBusinessAccount Get the details of your linked WhatsApp Business Account. Request Syntax GET /v1/whatsapp/waba/details?id=id HTTP/1.1 URI Request Parameters The request uses the following URI parameters. id The unique identifier, from AWS, of the linked WhatsApp Business Account. WABA identifiers are formatted as waba-01234567890123456789012345678901. Use ListLinkedWhatsAppBusinessAccounts to list all WABAs and their details. Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: Yes Request Body The request does not have a request body. Response Syntax HTTP/1.1 200 Content-type: application/json { "account": { "arn": "string", "eventDestinations": [ { "eventDestinationArn": "string", "roleArn": "string" GetLinkedWhatsAppBusinessAccount API Version 2024-01-01 15 AWS End User Messaging Social API Reference } ], "id": "string", "linkDate": number, "phoneNumbers": [ { "arn": "string", "displayPhoneNumber": "string", "displayPhoneNumberName": "string", "metaPhoneNumberId": "string", "phoneNumber": "string", "phoneNumberId": "string", "qualityRating": "string" } ], "registrationStatus": "string", "wabaId": "string", "wabaName": "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. account The details of the linked WhatsApp Business Account. Type: LinkedWhatsAppBusinessAccount object Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 Response Elements API Version 2024-01-01 16 AWS End User Messaging Social DependencyException API Reference Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ See Also API Version 2024-01-01 17 AWS End User Messaging Social • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 18 AWS End User Messaging Social API Reference GetLinkedWhatsAppBusinessAccountPhoneNumber Use your WhatsApp phone number id to get the WABA account id and phone number details. Request Syntax GET /v1/whatsapp/waba/phone/details?id=id HTTP/1.1 URI Request Parameters The request uses the following URI parameters. id The unique identifier of the phone number. Phone number identifiers are formatted as phone-number-id-01234567890123456789012345678901. Use GetLinkedWhatsAppBusinessAccount to find a phone number's id. Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes Request Body The request does not have a request body. Response Syntax HTTP/1.1 200 Content-type: application/json { "linkedWhatsAppBusinessAccountId": "string", "phoneNumber": { "arn": "string", "displayPhoneNumber": "string", "displayPhoneNumberName": "string", GetLinkedWhatsAppBusinessAccountPhoneNumber API Version 2024-01-01 19 AWS End User Messaging Social API Reference "metaPhoneNumberId": "string", "phoneNumber": "string", "phoneNumberId": "string", "qualityRating": "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. linkedWhatsAppBusinessAccountId The WABA identifier linked to the phone number, formatted as waba-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* phoneNumber The details of your WhatsApp phone number. Type: WhatsAppPhoneNumberDetail object Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException
social-api-005
social-api.pdf
5
API Version 2024-01-01 19 AWS End User Messaging Social API Reference "metaPhoneNumberId": "string", "phoneNumber": "string", "phoneNumberId": "string", "qualityRating": "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. linkedWhatsAppBusinessAccountId The WABA identifier linked to the phone number, formatted as waba-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* phoneNumber The details of your WhatsApp phone number. Type: WhatsAppPhoneNumberDetail object Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 DependencyException Thrown when performing an action because a dependency would be broken. Response Elements API Version 2024-01-01 20 AWS End User Messaging Social HTTP Status Code: 502 InternalServiceException API Reference The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 See Also API Version 2024-01-01 21 AWS End User Messaging Social • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 22 AWS End User Messaging Social API Reference GetWhatsAppMessageMedia Get a media file from the WhatsApp service. On successful completion the media file is retrieved from Meta and stored in the specified Amazon S3 bucket. Use either destinationS3File or destinationS3PresignedUrl for the destination. If both are used then an InvalidParameterException is returned. Request Syntax POST /v1/whatsapp/media/get HTTP/1.1 Content-type: application/json { "destinationS3File": { "bucketName": "string", "key": "string" }, "destinationS3PresignedUrl": { "headers": { "string" : "string" }, "url": "string" }, "mediaId": "string", "metadataOnly": boolean, "originationPhoneNumberId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. destinationS3File The bucketName and key of the S3 media file. Type: S3File object GetWhatsAppMessageMedia API Version 2024-01-01 23 API Reference AWS End User Messaging Social Required: No destinationS3PresignedUrl The presign url of the media file. Type: S3PresignedUrl object Required: No mediaId The unique identifier for the media file. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [A-Za-z0-9]+ Required: Yes metadataOnly Set to True to get only the metadata for the file. Type: Boolean Required: No originationPhoneNumberId The unique identifier of the originating phone number for the WhatsApp message media. The phone number identifiers are formatted as phone-number- id-01234567890123456789012345678901. Use GetLinkedWhatsAppBusinessAccount to find a phone number's id. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes Request Body API Version 2024-01-01 24 API Reference AWS End User Messaging Social Response Syntax HTTP/1.1 200 Content-type: application/json { "fileSize": number, "mimeType": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. fileSize The file size of the media, in KB. Type: Long mimeType The MIME type of the media. Type: String Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedByMetaException You do not have sufficient access to perform this action. HTTP Status Code: 403 AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 Response Syntax API Version 2024-01-01 25 AWS End User Messaging Social DependencyException API Reference Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ See Also API Version 2024-01-01 26 AWS End User Messaging Social • AWS SDK
social-api-006
social-api.pdf
6
500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ See Also API Version 2024-01-01 26 AWS End User Messaging Social • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 27 AWS End User Messaging Social API Reference ListLinkedWhatsAppBusinessAccounts List all WhatsApp Business Accounts linked to your AWS account. Request Syntax GET /v1/whatsapp/waba/list?maxResults=maxResults&nextToken=nextToken HTTP/1.1 URI Request Parameters The request uses the following URI parameters. maxResults The maximum number of results to return. Valid Range: Minimum value of 1. Maximum value of 100. nextToken The next token for pagination. Length Constraints: Minimum length of 1. Maximum length of 600. Request Body The request does not have a request body. Response Syntax HTTP/1.1 200 Content-type: application/json { "linkedAccounts": [ { "arn": "string", "eventDestinations": [ { "eventDestinationArn": "string", ListLinkedWhatsAppBusinessAccounts API Version 2024-01-01 28 AWS End User Messaging Social API Reference "roleArn": "string" } ], "id": "string", "linkDate": number, "registrationStatus": "string", "wabaId": "string", "wabaName": "string" } ], "nextToken": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. linkedAccounts A list of WhatsApp Business Accounts linked to your AWS account. Type: Array of LinkedWhatsAppBusinessAccountSummary objects nextToken The next token for pagination. Type: String Length Constraints: Minimum length of 1. Maximum length of 600. Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 Response Elements API Version 2024-01-01 29 AWS End User Messaging Social InternalServiceException API Reference The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin See Also API Version 2024-01-01 30 AWS End User Messaging Social • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 31 AWS End User Messaging Social API Reference ListTagsForResource List all tags associated with a resource, such as a phone number or WABA. Request Syntax GET /v1/tags/list?resourceArn=resourceArn HTTP/1.1 URI Request Parameters The request uses the following URI parameters. resourceArn The Amazon Resource Name (ARN) of the resource to retrieve the tags from. Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.* Required: Yes Request Body The request does not have a request body. Response Syntax HTTP/1.1 200 Content-type: application/json { "statusCode": number, "tags": [ { "key": "string", "value": "string" } ] } ListTagsForResource API Version 2024-01-01 32 AWS End User Messaging Social Response Elements API Reference If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. statusCode The status code of the response. Type: Integer tags The tags for the resource. Type: Array of Tag objects Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 Response Elements API Version 2024-01-01 33 AWS End User Messaging Social ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also API Reference For more information about using this API in
social-api-007
social-api.pdf
7
see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 Response Elements API Version 2024-01-01 33 AWS End User Messaging Social ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 34 AWS End User Messaging Social API Reference PostWhatsAppMessageMedia Upload a media file to the WhatsApp service. Only the specified originationPhoneNumberId has the permissions to send the media file when using SendWhatsAppMessage. You must use either sourceS3File or sourceS3PresignedUrl for the source. If both or neither are specified then an InvalidParameterException is returned. Request Syntax POST /v1/whatsapp/media HTTP/1.1 Content-type: application/json { "originationPhoneNumberId": "string", "sourceS3File": { "bucketName": "string", "key": "string" }, "sourceS3PresignedUrl": { "headers": { "string" : "string" }, "url": "string" } } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. originationPhoneNumberId The ID of the phone number to associate with the WhatsApp media file. The phone number identifiers are formatted as phone-number-id-01234567890123456789012345678901. Use GetLinkedWhatsAppBusinessAccount to find a phone number's id. Type: String PostWhatsAppMessageMedia API Version 2024-01-01 35 AWS End User Messaging Social API Reference Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes sourceS3File The source S3 url for the media file. Type: S3File object Required: No sourceS3PresignedUrl The source presign url of the media file. Type: S3PresignedUrl object Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "mediaId": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. mediaId The unique identifier of the posted WhatsApp message. Type: String Response Syntax API Version 2024-01-01 36 AWS End User Messaging Social API Reference Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [A-Za-z0-9]+ Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedByMetaException You do not have sufficient access to perform this action. HTTP Status Code: 403 AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 DependencyException Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. Errors API Version 2024-01-01 37 AWS End User Messaging Social HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 38 AWS End User Messaging Social API Reference PutWhatsAppBusinessAccountEventDestinations Add an event destination to log event data from WhatsApp for a WhatsApp Business Account (WABA). A WABA can only have one event destination at a time. All resources associated with the WABA use the same event destination. Request Syntax PUT /v1/whatsapp/waba/eventdestinations HTTP/1.1 Content-type: application/json { "eventDestinations": [ { "eventDestinationArn": "string", "roleArn": "string" } ], "id": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. eventDestinations An array of WhatsAppBusinessAccountEventDestination event destinations. Type: Array of WhatsAppBusinessAccountEventDestination objects Array Members: Minimum number of 0 items. Maximum number of 1 item. Required: Yes PutWhatsAppBusinessAccountEventDestinations API Version 2024-01-01 39 AWS End User Messaging Social id API Reference The unique identifier of your WhatsApp Business Account. WABA identifiers are formatted as waba-01234567890123456789012345678901. Use ListLinkedWhatsAppBusinessAccounts to list all WABAs
social-api-008
social-api.pdf
8
Syntax PUT /v1/whatsapp/waba/eventdestinations HTTP/1.1 Content-type: application/json { "eventDestinations": [ { "eventDestinationArn": "string", "roleArn": "string" } ], "id": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. eventDestinations An array of WhatsAppBusinessAccountEventDestination event destinations. Type: Array of WhatsAppBusinessAccountEventDestination objects Array Members: Minimum number of 0 items. Maximum number of 1 item. Required: Yes PutWhatsAppBusinessAccountEventDestinations API Version 2024-01-01 39 AWS End User Messaging Social id API Reference The unique identifier of your WhatsApp Business Account. WABA identifiers are formatted as waba-01234567890123456789012345678901. Use ListLinkedWhatsAppBusinessAccounts to list all WABAs and their details. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: Yes Response Syntax HTTP/1.1 200 Response Elements If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body. Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 Response Syntax API Version 2024-01-01 40 API Reference AWS End User Messaging Social ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 41 AWS End User Messaging Social API Reference SendWhatsAppMessage Send a WhatsApp message. For examples of sending a message using the AWS CLI, see Sending messages in the AWS End User Messaging Social User Guide . Request Syntax POST /v1/whatsapp/send HTTP/1.1 Content-type: application/json { "message": blob, "metaApiVersion": "string", "originationPhoneNumberId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. message The message to send through WhatsApp. The length is in KB. The message field passes through a WhatsApp Message object, see Messages in the WhatsApp Business Platform Cloud API Reference. Type: Base64-encoded binary data object Length Constraints: Minimum length of 1. Maximum length of 2048000. Required: Yes metaApiVersion The API version for the request formatted as v{VersionNumber}. For a list of supported API versions and AWS Regions, see AWS End User Messaging Social API Service Endpoints in the AWS General Reference. Type: String SendWhatsAppMessage API Version 2024-01-01 42 AWS End User Messaging Social Required: Yes originationPhoneNumberId API Reference The ID of the phone number used to send the WhatsApp message. If you are sending a media file only the originationPhoneNumberId used to upload the file can be used. Phone number identifiers are formatted as phone-number-id-01234567890123456789012345678901. Use GetLinkedWhatsAppBusinessAccount to find a phone number's id. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { "messageId": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. messageId The unique identifier of the message. Type: String Errors For information about the errors that are common to all actions, see Common Errors. Response Syntax API Version 2024-01-01 43 AWS End User Messaging Social AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 DependencyException API Reference Thrown when performing an action because a dependency would be broken. HTTP Status Code: 502 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 ResourceNotFoundException The resource was not found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: See Also API Version 2024-01-01 44 API Reference AWS End User Messaging Social • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin
social-api-009
social-api.pdf
9
found. HTTP Status Code: 404 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: See Also API Version 2024-01-01 44 API Reference AWS End User Messaging Social • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 45 AWS End User Messaging Social TagResource API Reference Adds or overwrites only the specified tags for the specified resource. When you specify an existing tag key, the value is overwritten with the new value. Request Syntax POST /v1/tags/tag-resource HTTP/1.1 Content-type: application/json { "resourceArn": "string", "tags": [ { "key": "string", "value": "string" } ] } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. resourceArn The Amazon Resource Name (ARN) of the resource to tag. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.* Required: Yes tags The tags to add to the resource. TagResource API Version 2024-01-01 46 API Reference AWS End User Messaging Social Type: Array of Tag objects Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { "statusCode": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. statusCode The status code of the tag resource operation. Type: Integer Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 Response Syntax API Version 2024-01-01 47 AWS End User Messaging Social InvalidParametersException API Reference One or more parameters provided to the action are not valid. HTTP Status Code: 400 ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 48 API Reference AWS End User Messaging Social UntagResource Removes the specified tags from a resource. Request Syntax POST /v1/tags/untag-resource HTTP/1.1 Content-type: application/json { "resourceArn": "string", "tagKeys": [ "string" ] } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. resourceArn The Amazon Resource Name (ARN) of the resource to remove tags from. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.* Required: Yes tagKeys The keys of the tags to remove from the resource. Type: Array of strings Required: Yes UntagResource API Version 2024-01-01 49 API Reference AWS End User Messaging Social Response Syntax HTTP/1.1 200 Content-type: application/json { "statusCode": number } Response Elements If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. statusCode The status code of the untag resource operation. Type: Integer Errors For information about the errors that are common to all actions, see Common Errors. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 InternalServiceException The request processing has failed because of an unknown error, exception, or failure. HTTP Status Code: 500 InvalidParametersException One or more parameters provided to the action are not valid. HTTP Status Code: 400 Response Syntax API Version 2024-01-01 50 API Reference AWS End User Messaging Social ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS
social-api-010
social-api.pdf
10
Status Code: 400 Response Syntax API Version 2024-01-01 50 API Reference AWS End User Messaging Social ThrottledRequestException The request was denied due to request throttling. HTTP Status Code: 429 ValidationException The request contains an invalid parameter value. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS Command Line Interface • AWS SDK for .NET • AWS SDK for C++ • AWS SDK for Go v2 • AWS SDK for Java V2 • AWS SDK for JavaScript V3 • AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 See Also API Version 2024-01-01 51 AWS End User Messaging Social API Reference Data Types The AWS End User Messaging Social API contains several data types that various actions use. This section describes each data type in detail. Note The order of each element in a data type structure is not guaranteed. Applications should not assume a particular order. The following data types are supported: • LinkedWhatsAppBusinessAccount • LinkedWhatsAppBusinessAccountIdMetaData • LinkedWhatsAppBusinessAccountSummary • S3File • S3PresignedUrl • Tag • WabaPhoneNumberSetupFinalization • WabaSetupFinalization • WhatsAppBusinessAccountEventDestination • WhatsAppPhoneNumberDetail • WhatsAppPhoneNumberSummary • WhatsAppSetupFinalization • WhatsAppSignupCallback • WhatsAppSignupCallbackResult API Version 2024-01-01 52 AWS End User Messaging Social API Reference LinkedWhatsAppBusinessAccount The details of your linked WhatsApp Business Account. Contents arn The ARN of the linked WhatsApp Business Account. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.*:waba/[0-9a-zA-Z]+ Required: Yes eventDestinations The event destinations for the linked WhatsApp Business Account. Type: Array of WhatsAppBusinessAccountEventDestination objects Array Members: Minimum number of 0 items. Maximum number of 1 item. Required: Yes id The ID of the linked WhatsApp Business Account, formatted as waba-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: Yes linkDate The date the WhatsApp Business Account was linked. LinkedWhatsAppBusinessAccount API Version 2024-01-01 53 API Reference AWS End User Messaging Social Type: Timestamp Required: Yes phoneNumbers The phone numbers associated with the Linked WhatsApp Business Account. Type: Array of WhatsAppPhoneNumberSummary objects Required: Yes registrationStatus The registration status of the linked WhatsApp Business Account. Type: String Valid Values: COMPLETE | INCOMPLETE Required: Yes wabaId The WhatsApp Business Account ID from meta. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Required: Yes wabaName The name of the linked WhatsApp Business Account. Type: String Length Constraints: Minimum length of 0. Maximum length of 200. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: See Also API Version 2024-01-01 54 AWS End User Messaging Social • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 55 AWS End User Messaging Social API Reference LinkedWhatsAppBusinessAccountIdMetaData Contains your WhatsApp registration status and details of any unregistered WhatsApp phone number. Contents accountName The name of your account. Type: String Length Constraints: Minimum length of 0. Maximum length of 200. Required: No registrationStatus The registration status of the linked WhatsApp Business Account. Type: String Valid Values: COMPLETE | INCOMPLETE Required: No unregisteredWhatsAppPhoneNumbers The details for unregistered WhatsApp phone numbers. Type: Array of WhatsAppPhoneNumberDetail objects Required: No wabaId The Amazon Resource Name (ARN) of the WhatsApp Business Account ID. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* LinkedWhatsAppBusinessAccountIdMetaData API Version 2024-01-01 56 AWS End User Messaging Social Required: No See Also API Reference For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 57 AWS End User Messaging Social API Reference LinkedWhatsAppBusinessAccountSummary The details of a linked WhatsApp Business Account. Contents arn The ARN of the linked WhatsApp Business Account. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.*:waba/[0-9a-zA-Z]+ Required: Yes eventDestinations The event destinations for the linked WhatsApp Business Account. Type: Array of WhatsAppBusinessAccountEventDestination objects Array Members: Minimum number of 0 items. Maximum number of 1 item. Required: Yes id The ID of the linked WhatsApp Business Account, formatted as waba-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: Yes linkDate The date the WhatsApp Business Account was linked. LinkedWhatsAppBusinessAccountSummary API Version 2024-01-01 58 API Reference AWS End User Messaging Social Type: Timestamp Required: Yes registrationStatus The registration status of the linked WhatsApp Business Account. Type: String Valid Values: COMPLETE | INCOMPLETE Required: Yes wabaId The WhatsApp Business Account ID provided by Meta. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Required: Yes wabaName The name
social-api-011
social-api.pdf
11
Required: Yes id The ID of the linked WhatsApp Business Account, formatted as waba-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: Yes linkDate The date the WhatsApp Business Account was linked. LinkedWhatsAppBusinessAccountSummary API Version 2024-01-01 58 API Reference AWS End User Messaging Social Type: Timestamp Required: Yes registrationStatus The registration status of the linked WhatsApp Business Account. Type: String Valid Values: COMPLETE | INCOMPLETE Required: Yes wabaId The WhatsApp Business Account ID provided by Meta. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Required: Yes wabaName The name of the linked WhatsApp Business Account. Type: String Length Constraints: Minimum length of 0. Maximum length of 200. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 59 AWS End User Messaging Social S3File Contains information for the S3 bucket that contains media files. API Reference Contents bucketName The bucket name. Type: String Length Constraints: Minimum length of 3. Maximum length of 63. Pattern: [a-z0-9][a-z0-9.-]*[a-z0-9] Required: Yes key The object key of the media file. Type: String Length Constraints: Minimum length of 0. Maximum length of 1024. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 S3File API Version 2024-01-01 60 AWS End User Messaging Social S3PresignedUrl API Reference You can use presigned URLs to grant time-limited access to objects in Amazon S3 without updating your bucket policy. For more information, see Working with presigned URLs in the Amazon S3 User Guide. Contents headers A map of headers and their values. You must specify the Content-Type header when using PostWhatsAppMessageMedia. For a list of common headers, see Common Request Headers in the Amazon S3 API Reference Type: String to string map Required: Yes url The presign url to the object. Type: String Length Constraints: Minimum length of 1. Maximum length of 2000. Pattern: https://(.*)s3(.*).amazonaws.com/(.*) Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 S3PresignedUrl API Version 2024-01-01 61 AWS End User Messaging Social API Reference Tag The tag for a resource. Contents key The tag key. Type: String Length Constraints: Minimum length of 1. Maximum length of 128. Required: Yes value The tag value. Type: String Length Constraints: Minimum length of 0. Maximum length of 256. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 Tag API Version 2024-01-01 62 AWS End User Messaging Social API Reference WabaPhoneNumberSetupFinalization The registration details for a linked phone number. Contents id The unique identifier of the originating phone number associated with the media. Phone number identifiers are formatted as phone-number- id-01234567890123456789012345678901. Use GetLinkedWhatsAppBusinessAccount to find a phone number's id. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Required: Yes twoFactorPin The PIN to use for two-step verification. To reset your PIN follow the directions in Updating PIN in the WhatsApp Business Platform Cloud API Reference. Type: String Length Constraints: Minimum length of 1. Maximum length of 6. Required: Yes dataLocalizationRegion The two letter ISO region for the location of where Meta will store data. Asia–Pacific (APAC) • Australia AU • Indonesia ID • India IN • Japan JP • Singapore SG • South Korea KR WabaPhoneNumberSetupFinalization API Version 2024-01-01 63 API Reference AWS End User Messaging Social Europe • Germany DE • Switzerland CH • United Kingdom GB Latin America (LATAM) • Brazil BR Middle East and Africa (MEA) • Bahrain BH • South Africa ZA • United Arab Emirates AE North America (NORAM) • Canada CA Type: String Pattern: [A-Z]{2} Required: No tags An array of key and value pair tags. Type: Array of Tag objects Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 64 AWS End User Messaging Social API Reference See Also API Version 2024-01-01 65 AWS End User Messaging Social API Reference WabaSetupFinalization The registration details for a linked WhatsApp Business Account. Contents eventDestinations The event destinations for the linked WhatsApp Business Account. Type: Array of WhatsAppBusinessAccountEventDestination objects Array
social-api-012
social-api.pdf
12
and value pair tags. Type: Array of Tag objects Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 64 AWS End User Messaging Social API Reference See Also API Version 2024-01-01 65 AWS End User Messaging Social API Reference WabaSetupFinalization The registration details for a linked WhatsApp Business Account. Contents eventDestinations The event destinations for the linked WhatsApp Business Account. Type: Array of WhatsAppBusinessAccountEventDestination objects Array Members: Minimum number of 0 items. Maximum number of 1 item. Required: No id The ID of the linked WhatsApp Business Account, formatted as waba-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Required: No tags An array of key and value pair tags. Type: Array of Tag objects Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 WabaSetupFinalization API Version 2024-01-01 66 AWS End User Messaging Social • AWS SDK for Ruby V3 API Reference See Also API Version 2024-01-01 67 AWS End User Messaging Social API Reference WhatsAppBusinessAccountEventDestination Contains information on the event destination. Contents eventDestinationArn The ARN of the event destination. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.*:[a-z-]+([/:](.*))? Required: Yes roleArn The Amazon Resource Name (ARN) of an AWS Identity and Access Management role that is able to import phone numbers and write events. Type: String Pattern: arn:aws:iam::\d{12}:role\/[a-zA-Z0-9+=,.@\-_]+ Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 WhatsAppBusinessAccountEventDestination API Version 2024-01-01 68 AWS End User Messaging Social API Reference WhatsAppPhoneNumberDetail The details of your WhatsApp phone number. Contents arn The ARN of the WhatsApp phone number. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.*:phone-number-id/[0-9a-zA-Z]+ Required: Yes displayPhoneNumber The phone number that appears in the recipients display. Type: String Length Constraints: Minimum length of 0. Maximum length of 20. Required: Yes displayPhoneNumberName The display name for this phone number. Type: String Length Constraints: Minimum length of 0. Maximum length of 200. Required: Yes metaPhoneNumberId The phone number ID from Meta. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. WhatsAppPhoneNumberDetail API Version 2024-01-01 69 API Reference AWS End User Messaging Social Required: Yes phoneNumber The phone number for sending WhatsApp. Type: String Length Constraints: Minimum length of 1. Maximum length of 20. Required: Yes phoneNumberId The phone number ID. Phone number identifiers are formatted as phone-number- id-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes qualityRating The quality rating of the phone number. Type: String Length Constraints: Minimum length of 0. Maximum length of 10. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 70 AWS End User Messaging Social API Reference See Also API Version 2024-01-01 71 AWS End User Messaging Social API Reference WhatsAppPhoneNumberSummary The details of a linked phone number. Contents arn The full Amazon Resource Name (ARN) for the phone number. Type: String Length Constraints: Minimum length of 0. Maximum length of 2048. Pattern: arn:.*:phone-number-id/[0-9a-zA-Z]+ Required: Yes displayPhoneNumber The phone number that appears in the recipients display. Type: String Length Constraints: Minimum length of 0. Maximum length of 20. Required: Yes displayPhoneNumberName The display name for this phone number. Type: String Length Constraints: Minimum length of 0. Maximum length of 200. Required: Yes metaPhoneNumberId The phone number ID from Meta. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. WhatsAppPhoneNumberSummary API Version 2024-01-01 72 AWS End User Messaging Social Required: Yes phoneNumber API Reference The phone number associated with the Linked WhatsApp Business Account. Type: String Length Constraints: Minimum length of 1. Maximum length of 20. Required: Yes phoneNumberId The phone number ID. Phone number identifiers are formatted as phone-number- id-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes qualityRating The quality rating of the phone number. This is from Meta. Type: String Length Constraints: Minimum length of 0. Maximum length of 10. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for
social-api-013
social-api.pdf
13
Constraints: Minimum length of 1. Maximum length of 20. Required: Yes phoneNumberId The phone number ID. Phone number identifiers are formatted as phone-number- id-01234567890123456789012345678901. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^phone-number-id-.*$)|(^arn:.*:phone-number-id/[0-9a-zA-Z]+$).* Required: Yes qualityRating The quality rating of the phone number. This is from Meta. Type: String Length Constraints: Minimum length of 0. Maximum length of 10. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 73 AWS End User Messaging Social API Reference See Also API Version 2024-01-01 74 AWS End User Messaging Social API Reference WhatsAppSetupFinalization The details of linking a WhatsApp Business Account to your AWS account. Contents associateInProgressToken An AWS access token generated by WhatsAppSignupCallback and used by WhatsAppSetupFinalization. Type: String Length Constraints: Minimum length of 0. Maximum length of 50. Required: Yes phoneNumbers An array of WabaPhoneNumberSetupFinalization objects containing the details of each phone number associated with the WhatsApp Business Account. Type: Array of WabaPhoneNumberSetupFinalization objects Required: Yes phoneNumberParent Used to add a new phone number to an existing WhatsApp Business Account. This field can't be used when the waba field is present. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: .*(^waba-.*$)|(^arn:.*:waba/[0-9a-zA-Z]+$).* Required: No waba Used to create a new WhatsApp Business Account and add a phone number. This field can't be used when the phoneNumberParent field is present. WhatsAppSetupFinalization API Version 2024-01-01 75 AWS End User Messaging Social API Reference Type: WabaSetupFinalization object Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 See Also API Version 2024-01-01 76 AWS End User Messaging Social API Reference WhatsAppSignupCallback Contains the accessToken provided by Meta during signup. Contents accessToken The access token for your WhatsApp Business Account. The accessToken value is provided by Meta. Type: String Length Constraints: Minimum length of 0. Maximum length of 1000. Required: Yes See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 WhatsAppSignupCallback API Version 2024-01-01 77 AWS End User Messaging Social API Reference WhatsAppSignupCallbackResult Contains the results of WhatsAppSignupCallback. Contents associateInProgressToken An AWS access token generated by WhatsAppSignupCallback and used by WhatsAppSetupFinalization. Type: String Length Constraints: Minimum length of 0. Maximum length of 50. Required: No linkedAccountsWithIncompleteSetup A LinkedWhatsAppBusinessAccountIdMetaData object map containing the details of any WhatsAppBusiness accounts that have incomplete setup. Type: String to LinkedWhatsAppBusinessAccountIdMetaData object map Key Length Constraints: Minimum length of 1. Maximum length of 100. Required: No See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ • AWS SDK for Java V2 • AWS SDK for Ruby V3 WhatsAppSignupCallbackResult API Version 2024-01-01 78 AWS End User Messaging Social API Reference Common Parameters The following list contains the parameters that all actions use for signing Signature Version 4 requests with a query string. Any action-specific parameters are listed in the topic for that action. For more information about Signature Version 4, see Signing AWS API requests in the IAM User Guide. Action The action to be performed. Type: string Required: Yes Version The API version that the request is written for, expressed in the format YYYY-MM-DD. Type: string Required: Yes X-Amz-Algorithm The hash algorithm that you used to create the request signature. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Valid Values: AWS4-HMAC-SHA256 Required: Conditional X-Amz-Credential The credential scope value, which is a string that includes your access key, the date, the region you are targeting, the service you are requesting, and a termination string ("aws4_request"). The value is expressed in the following format: access_key/YYYYMMDD/region/service/ aws4_request. API Version 2024-01-01 79 AWS End User Messaging Social API Reference For more information, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional X-Amz-Date The date that is used to create the signature. The format must be ISO 8601 basic format (YYYYMMDD'T'HHMMSS'Z'). For example, the following date time is a valid X-Amz-Date value: 20120325T120000Z. Condition: X-Amz-Date is optional for all requests; it can be used to override the date used for signing requests. If the Date header is specified in the ISO 8601 basic
social-api-014
social-api.pdf
14
For more information, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional X-Amz-Date The date that is used to create the signature. The format must be ISO 8601 basic format (YYYYMMDD'T'HHMMSS'Z'). For example, the following date time is a valid X-Amz-Date value: 20120325T120000Z. Condition: X-Amz-Date is optional for all requests; it can be used to override the date used for signing requests. If the Date header is specified in the ISO 8601 basic format, X-Amz-Date is not required. When X-Amz-Date is used, it always overrides the value of the Date header. For more information, see Elements of an AWS API request signature in the IAM User Guide. Type: string Required: Conditional X-Amz-Security-Token The temporary security token that was obtained through a call to AWS Security Token Service (AWS STS). For a list of services that support temporary security credentials from AWS STS, see AWS services that work with IAM in the IAM User Guide. Condition: If you're using temporary security credentials from AWS STS, you must include the security token. Type: string Required: Conditional X-Amz-Signature Specifies the hex-encoded signature that was calculated from the string to sign and the derived signing key. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. API Version 2024-01-01 80 AWS End User Messaging Social Type: string Required: Conditional X-Amz-SignedHeaders API Reference Specifies all the HTTP headers that were included as part of the canonical request. For more information about specifying signed headers, see Create a signed AWS API request in the IAM User Guide. Condition: Specify this parameter when you include authentication information in a query string instead of in the HTTP authorization header. Type: string Required: Conditional API Version 2024-01-01 81 AWS End User Messaging Social API Reference Common Errors This section lists the errors common to the API actions of all AWS services. For errors specific to an API action for this service, see the topic for that API action. AccessDeniedException You do not have sufficient access to perform this action. HTTP Status Code: 403 ExpiredTokenException The security token included in the request is expired HTTP Status Code: 403 IncompleteSignature The request signature does not conform to AWS standards. HTTP Status Code: 403 InternalFailure The request processing has failed because of an unknown error, exception or failure. HTTP Status Code: 500 MalformedHttpRequestException Problems with the request at the HTTP level, e.g. we can't decompress the body according to the decompression algorithm specified by the content-encoding. HTTP Status Code: 400 NotAuthorized You do not have permission to perform this action. HTTP Status Code: 401 OptInRequired The AWS access key ID needs a subscription for the service. API Version 2024-01-01 82 AWS End User Messaging Social HTTP Status Code: 403 RequestAbortedException API Reference Convenient exception that can be used when a request is aborted before a reply is sent back (e.g. client closed connection). HTTP Status Code: 400 RequestEntityTooLargeException Problems with the request at the HTTP level. The request entity is too large. HTTP Status Code: 413 RequestExpired The request reached the service more than 15 minutes after the date stamp on the request or more than 15 minutes after the request expiration date (such as for pre-signed URLs), or the date stamp on the request is more than 15 minutes in the future. HTTP Status Code: 400 RequestTimeoutException Problems with the request at the HTTP level. Reading the Request timed out. HTTP Status Code: 408 ServiceUnavailable The request has failed due to a temporary failure of the server. HTTP Status Code: 503 ThrottlingException The request was denied due to request throttling. HTTP Status Code: 400 UnrecognizedClientException The X.509 certificate or AWS access key ID provided does not exist in our records. HTTP Status Code: 403 API Version 2024-01-01 83 AWS End User Messaging Social UnknownOperationException API Reference The action or operation requested is invalid. Verify that the action is typed correctly. HTTP Status Code: 404 ValidationError The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 API Version 2024-01-01 84
social-ug-001
social-ug.pdf
1
User Guide AWS End User Messaging Social Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. AWS End User Messaging Social User Guide AWS End User Messaging Social: User Guide Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. AWS End User Messaging Social Table of Contents User Guide What is AWS End User Messaging Social? ..................................................................................... 1 Are you a first-time AWS End User Messaging Social user? ................................................................ 1 Features of AWS End User Messaging Social ......................................................................................... 1 Related services ............................................................................................................................................ 2 Accessing AWS End User Messaging Social ............................................................................................. 2 Regional availability ..................................................................................................................................... 3 Setting up AWS End User Messaging Social .................................................................................. 7 Sign up for an AWS account ...................................................................................................................... 7 Create a user with administrative access ................................................................................................ 7 Next steps ...................................................................................................................................................... 9 Getting started .............................................................................................................................. 10 Signing up for WhatsApp ......................................................................................................................... 10 Prerequisites ........................................................................................................................................... 10 Sign up through the console .............................................................................................................. 12 Next steps ............................................................................................................................................... 16 WhatsApp Business Account (WABA) ........................................................................................... 17 View a WABA .............................................................................................................................................. 18 Add a WABA ................................................................................................................................................ 18 WhatsApp business account types ......................................................................................................... 19 Additional resources ............................................................................................................................. 19 Phone numbers .............................................................................................................................. 20 Phone number considerations ................................................................................................................. 20 Add a phone number ................................................................................................................................ 21 Prerequisites ........................................................................................................................................... 21 Add a phone number to a WABA ...................................................................................................... 21 View a phone number's status ................................................................................................................ 23 View a phone number's ID ....................................................................................................................... 24 Increase messaging conversation limits ................................................................................................ 24 Increase message throughput ................................................................................................................. 25 Understanding phone number quality rating ...................................................................................... 26 View a phone number quality rating ............................................................................................... 26 Message templates ........................................................................................................................ 28 Using message templates with WhatsApp Manager .......................................................................... 29 Next steps .................................................................................................................................................... 29 iii AWS End User Messaging Social User Guide Template pacing ......................................................................................................................................... 29 Get feedback on a templates lowered status ...................................................................................... 30 Template status and quality rating ........................................................................................................ 30 Reasons why a template is rejected ....................................................................................................... 32 Message and event destinations ................................................................................................... 33 Add an event destination ......................................................................................................................... 33 Prerequisites ........................................................................................................................................... 33 Add a message and event destination ............................................................................................. 34 Encrypted Amazon SNS topic policies ............................................................................................. 35 IAM policies for Amazon SNS topics ................................................................................................ 36 IAM policies for Amazon Connect ..................................................................................................... 36 Next steps ............................................................................................................................................... 38 Message and event format ...................................................................................................................... 38 AWS End User Messaging Social event header .............................................................................. 38 Example WhatsApp JSON for a message ........................................................................................ 39 Example WhatsApp JSON for a media message ............................................................................ 41 Message status ............................................................................................................................................ 42 Message statuses .................................................................................................................................. 42 Additional resources ............................................................................................................................. 43 Uploading media files ................................................................................................................... 44 Supported media file types ..................................................................................................................... 46 Media file types ..................................................................................................................................... 46 Message types ................................................................................................................................ 48 Additional resources .................................................................................................................................. 48 Sending messages ......................................................................................................................... 49 Send a template message ........................................................................................................................ 50 Sending a media message ....................................................................................................................... 51 Responding to a received message .............................................................................................. 54 Change a message's status to read ........................................................................................................ 54 Respond with a reaction ........................................................................................................................... 55 Download a media file to Amazon S3 from WhatsApp ..................................................................... 55 Example of responding to a message ................................................................................................... 56 Prerequisites ........................................................................................................................................... 56 Responding ............................................................................................................................................. 56 Additional resources ............................................................................................................................. 59 Understanding your bill ................................................................................................................ 60 iv AWS End User Messaging Social User Guide When does the Authentication-International FeeType apply ........................................................... 64 Example 1: Sending a Marketing template message .......................................................................... 65 Example 2: Opening a Service conversation ........................................................................................ 65 Billing ISO codes ........................................................................................................................................ 65 Monitoring ...................................................................................................................................... 79 Monitoring with CloudWatch ................................................................................................................... 79 CloudTrail logs ............................................................................................................................................ 80 AWS End User Messaging Social data events in CloudTrail ......................................................... 82 AWS End User Messaging Social management events in CloudTrail .......................................... 83 AWS End User Messaging Social event examples .......................................................................... 83 Best practices ................................................................................................................................. 86 Up-to-date business profile ..................................................................................................................... 86 Obtain permission ...................................................................................................................................... 86 Prohibited message content .................................................................................................................... 87 Audit your customer lists ......................................................................................................................... 89 Adjust your sending based on engagement ......................................................................................... 89 Send at appropriate times ....................................................................................................................... 89 Security .......................................................................................................................................... 90 Data protection ........................................................................................................................................... 91 Data encryption ..................................................................................................................................... 92 Encryption in transit ............................................................................................................................ 92 Key management .................................................................................................................................. 92 Inter-network traffic privacy .............................................................................................................. 93 Identity and access management ........................................................................................................... 93 Audience .................................................................................................................................................. 94 Authenticating with identities ............................................................................................................ 95 Managing access using policies .......................................................................................................... 98 How AWS End User Messaging Social works with IAM ............................................................... 100 Identity-based policy examples ....................................................................................................... 107 AWS managed policies ...................................................................................................................... 110 Troubleshooting .................................................................................................................................. 111 Compliance validation ............................................................................................................................ 113 Resilience ................................................................................................................................................... 114 Infrastructure Security ............................................................................................................................ 114 Cross-service confused deputy prevention ......................................................................................... 115 Security best practices ............................................................................................................................ 116 v AWS End User Messaging Social User Guide Using service-linked roles ...................................................................................................................... 116 Service-linked role permissions for AWS End User Messaging Social ...................................... 117 Creating a service-linked role for AWS End User Messaging
social-ug-002
social-ug.pdf
2
93 Identity and access management ........................................................................................................... 93 Audience .................................................................................................................................................. 94 Authenticating with identities ............................................................................................................ 95 Managing access using policies .......................................................................................................... 98 How AWS End User Messaging Social works with IAM ............................................................... 100 Identity-based policy examples ....................................................................................................... 107 AWS managed policies ...................................................................................................................... 110 Troubleshooting .................................................................................................................................. 111 Compliance validation ............................................................................................................................ 113 Resilience ................................................................................................................................................... 114 Infrastructure Security ............................................................................................................................ 114 Cross-service confused deputy prevention ......................................................................................... 115 Security best practices ............................................................................................................................ 116 v AWS End User Messaging Social User Guide Using service-linked roles ...................................................................................................................... 116 Service-linked role permissions for AWS End User Messaging Social ...................................... 117 Creating a service-linked role for AWS End User Messaging Social ......................................... 117 Editing a service-linked role for AWS End User Messaging Social ............................................ 118 Deleting a service-linked role for AWS End User Messaging Social ......................................... 118 Supported Regions for AWS End User Messaging Social service-linked roles ........................ 119 AWS PrivateLink .......................................................................................................................... 120 Considerations .......................................................................................................................................... 120 Create an interface endpoint ................................................................................................................ 120 Create an endpoint policy ..................................................................................................................... 121 Quotas .......................................................................................................................................... 123 Document history ........................................................................................................................ 124 vi AWS End User Messaging Social User Guide What is AWS End User Messaging Social? AWS End User Messaging Social, also referred to as Social messaging, is a messaging service that allows developers to integrate WhatsApp into their applications. It provides access to WhatsApp's messaging capabilities, enabling the creation of branded, interactive content with images, videos, and buttons. By using this service, you can add WhatsApp messaging functionality to your applications alongside existing channels like SMS and push notifications. This allows you to engage with customers through their preferred communication channel. To get started, either create a new WhatsApp Business Account (WABA) using the self-guided onboarding process in the AWS End User Messaging Social console, or link an existing WABA to the service. Topics • Are you a first-time AWS End User Messaging Social user? • Features of AWS End User Messaging Social • Related services • Accessing AWS End User Messaging Social • Regional availability Are you a first-time AWS End User Messaging Social user? If you are a first-time user of AWS End User Messaging Social, we recommend that you begin by reading the following sections: • Setting up AWS End User Messaging Social • Getting started with AWS End User Messaging Social • Best practices for AWS End User Messaging Social Features of AWS End User Messaging Social AWS End User Messaging Social provides the following features and capabilities: Are you a first-time AWS End User Messaging Social user? 1 AWS End User Messaging Social User Guide • Design consistent messages and reuse content more effectively by creating and using message templates. A message template contains content and settings that you want to reuse in messages that you send. • Access to rich messaging capabilities for a more engaging experience. Beyond text and media, you can send locations and interactive messages. • Receive incoming text and media messages from your customers. • Build trust with your customers by verifying your business identity through Meta. Related services AWS offers other messaging services that can be used together in a multi-channel workflow: • Use AWS End User Messaging SMS to send SMS messages • Use AWS End User Messaging Push to send push notifications • Use Amazon SES to send email Accessing AWS End User Messaging Social You can access AWS End User Messaging Social using the following: AWS End User Messaging Social console The web interface where you create and manage resources. AWS Command Line Interface Interact with AWS services using commands in your command line shell. The AWS Command Line Interface is supported on Windows, macOS, and Linux. For more information about the AWS CLI, see AWS Command Line Interface User Guide. You can find the AWS End User Messaging Social commands in the AWS CLI Command Reference. AWS SDKs If you prefer to build applications using language-specific APIs instead of submitting a request over HTTP or HTTPS, use the libraries, sample code, tutorials, and other resources provided by AWS. These libraries provide basic functions that automate tasks, such as cryptographically signing your requests, retrying requests, and handling error responses. These functions make it more efficient for you to get started. For more information, see Tools to Build on AWS. Related services 2 AWS End User Messaging Social User Guide Regional availability AWS End User Messaging Social is available in several AWS Regions in North America, Europe, Asia, and Oceania. In each Region, AWS maintains multiple Availability Zones. These Availability Zones are physically isolated from each other, but are united by private, low-latency, high-throughput, and highly redundant network connections. These Availability Zones are used to provide high levels of availability and redundancy, while also minimizing latency. To learn more about AWS Regions, see Specify which AWS Regions your account can use in the Amazon Web Services General Reference. For a list of
social-ug-003
social-ug.pdf
3
2 AWS End User Messaging Social User Guide Regional availability AWS End User Messaging Social is available in several AWS Regions in North America, Europe, Asia, and Oceania. In each Region, AWS maintains multiple Availability Zones. These Availability Zones are physically isolated from each other, but are united by private, low-latency, high-throughput, and highly redundant network connections. These Availability Zones are used to provide high levels of availability and redundancy, while also minimizing latency. To learn more about AWS Regions, see Specify which AWS Regions your account can use in the Amazon Web Services General Reference. For a list of all the Regions where AWS End User Messaging Social is currently available and the endpoint for each Region, see Endpoints and quotas for AWS End User Messaging Social API and AWS service endpoints in the Amazon Web Services General Reference, or the following table. To learn more about the number of Availability Zones that are available in each Region, see AWS global infrastructure. Region availability Region name Region Endpoint US East (N. Virginia) us-east-1 US East (Ohio) us-east-2 social-messaging.u s-east-1.amazonaws .com social-messaging-f ips.us-east-1.api.aws social-messaging.us- east-1.api.aws social-messaging.u s-east-2.amazonaws .com social-messaging-f ips.us-east-2.api.aws social-messaging.us- east-2.api.aws WhatsApp API version Version 17 and later Version 17 and later Regional availability 3 AWS End User Messaging Social User Guide Region name Region Endpoint US West (Oregon) us-west-2 Africa (Cape Town) af-south-1 Asia Pacific (Hyderabad) ap-south-2 Asia Pacific (Mumbai) ap-south-1 social-messaging.us- west-2.amazonaws .com social-messaging-f ips.us-west-2.api.aws social-messaging.us- west-2.api.aws social-messaging.af- south-1.amazonaw s.com social-messaging.af- south-1.api.aws social-messaging.ap- south-2.amazonaw s.com social-messaging.ap- south-2.api.aws social-messaging.ap- south-1.amazonaw s.com social-messaging.ap- south-1.api.aws WhatsApp API version Version 17 and later Version 20 and later Version 20 and later Version 17 and later Regional availability 4 AWS End User Messaging Social User Guide Region name Region Endpoint Asia Pacific (Seoul) ap-northeast-2 Asia Pacific (Singapor e) ap-southeast-1 Asia Pacific (Sydney) ap-southeast-2 Asia Pacific (Tokyo) ap-northeast-1 Canada (Central) ca-central-1 social-messaging.a p-northeast-2.amaz onaws.com social-messaging.ap- northeast-2.api.aws social-messaging.a p-southeast-1.amaz onaws.com social-messaging.ap- southeast-1.api.aws social-messaging.a p-southeast-2.amaz onaws.com social-messaging.ap- southeast-2.api.aws social-messaging.a p-northeast-1.amaz onaws.com social-messaging.ap- northeast-1.api.aws social-messaging.c a-central-1.amazon aws.com social-messaging.ca- central-1.api.aws WhatsApp API version Version 20 and later Version 17 and later Version 20 and later Version 20 and later Version 20 and later Regional availability 5 AWS End User Messaging Social User Guide Region name Region Endpoint Europe (Frankfurt) eu-central-1 Europe (Ireland) eu-west-1 Europe (London) eu-west-2 Europe (Spain) eu-south-2 South America (São Paulo) sa-east-1 social-messaging.e u-central-1.amazon aws.com social-messaging.eu- central-1.api.aws social-messaging.eu- west-1.amazonaws .com social-messaging.eu- west-1.api.aws social-messaging.eu- west-2.amazonaws .com social-messaging.eu- west-2.api.aws social-messaging.eu- south-2.amazonaw s.com social-messaging.eu- south-2.api.aws social-messaging.s a-east-1.amazonaws .com social-messaging.sa- east-1.api.aws WhatsApp API version Version 17 and later Version 17 and later Version 17 and later Version 20 and later Version 20 and later Regional availability 6 AWS End User Messaging Social User Guide Setting up AWS End User Messaging Social Before you can use AWS End User Messaging Social for the first time, you must complete the following steps. Topics • Sign up for an AWS account • Create a user with administrative access • Next steps Sign up for an AWS account If you do not have an AWS account, complete the following steps to create one. To sign up for an AWS account 1. Open https://portal.aws.amazon.com/billing/signup. 2. Follow the online instructions. Part of the sign-up procedure involves receiving a phone call and entering a verification code on the phone keypad. When you sign up for an AWS account, an AWS account root user is created. The root user has access to all AWS services and resources in the account. As a security best practice, assign administrative access to a user, and use only the root user to perform tasks that require root user access. AWS sends you a confirmation email after the sign-up process is complete. At any time, you can view your current account activity and manage your account by going to https://aws.amazon.com/ and choosing My Account. Create a user with administrative access After you sign up for an AWS account, secure your AWS account root user, enable AWS IAM Identity Center, and create an administrative user so that you don't use the root user for everyday tasks. Sign up for an AWS account 7 AWS End User Messaging Social User Guide Secure your AWS account root user 1. Sign in to the AWS Management Console as the account owner by choosing Root user and entering your AWS account email address. On the next page, enter your password. For help signing in by using root user, see Signing in as the root user in the AWS Sign-In User Guide. 2. Turn on multi-factor authentication (MFA) for your root user. For instructions, see Enable a virtual MFA device for your AWS account root user (console) in the IAM User Guide. Create a user with administrative access 1. Enable IAM Identity Center. For instructions, see Enabling AWS IAM Identity Center in the AWS IAM Identity Center User
social-ug-004
social-ug.pdf
4
Console as the account owner by choosing Root user and entering your AWS account email address. On the next page, enter your password. For help signing in by using root user, see Signing in as the root user in the AWS Sign-In User Guide. 2. Turn on multi-factor authentication (MFA) for your root user. For instructions, see Enable a virtual MFA device for your AWS account root user (console) in the IAM User Guide. Create a user with administrative access 1. Enable IAM Identity Center. For instructions, see Enabling AWS IAM Identity Center in the AWS IAM Identity Center User Guide. 2. In IAM Identity Center, grant administrative access to a user. For a tutorial about using the IAM Identity Center directory as your identity source, see Configure user access with the default IAM Identity Center directory in the AWS IAM Identity Center User Guide. Sign in as the user with administrative access • To sign in with your IAM Identity Center user, use the sign-in URL that was sent to your email address when you created the IAM Identity Center user. For help signing in using an IAM Identity Center user, see Signing in to the AWS access portal in the AWS Sign-In User Guide. Assign access to additional users 1. In IAM Identity Center, create a permission set that follows the best practice of applying least- privilege permissions. For instructions, see Create a permission set in the AWS IAM Identity Center User Guide. Create a user with administrative access 8 AWS End User Messaging Social User Guide 2. Assign users to a group, and then assign single sign-on access to the group. For instructions, see Add groups in the AWS IAM Identity Center User Guide. Next steps Now that you're prepared to work with AWS End User Messaging Social, see Getting started with AWS End User Messaging Social for creating your WhatsApp Business Account (WABA) or migrating your existing WhatsApp Business Account. Next steps 9 AWS End User Messaging Social User Guide Getting started with AWS End User Messaging Social These topics guide you through the steps to link or migrate your WhatsApp Business Account (WABA) to AWS End User Messaging Social. Topics • Signing up for WhatsApp Signing up for WhatsApp A WhatsApp Business Account (WABA) allows your business to use the WhatsApp Business Platform to send messages directly to your customers. All of your WABAs are part of your Meta business portfolio. A WABA contains your customer facing assets, like phone number, templates, and WhatsApp Business Profile. A WhatsApp Business Profile contains your business's contact information that users see. For more information on WhatsApp Business Accounts, see WhatsApp Business Account (WABA) in AWS End User Messaging Social. Follow the steps in this section to get started with AWS End User Messaging Social. Use the embedded sign-up process to either create a new WhatsApp Business Account (WABA) or migrate an existing WABA to AWS End User Messaging Social. Prerequisites Important Working with Meta/WhatsApp • Your use of the WhatsApp Business Solution is subject to the terms and conditions of the WhatsApp Business Terms of Service, the WhatsApp Business Solution Terms, the WhatsApp Business Messaging Policy, the WhatsApp Messaging Guidelines, and all other terms, policies, or guidelines incorporated therein by reference (as each may be updated from time to time). • Meta or WhatsApp may at any time prohibit your use of the WhatsApp Business Solution. • You must create a WhatsApp Business Account ("WABA") with Meta and WhatsApp. • You must create a Business Manager account with Meta and link it to your WABA. Signing up for WhatsApp 10 AWS End User Messaging Social User Guide • You must provide control of your WABA to us. At your request, we will transfer control of your WABA back to you in a reasonable and timely manner using the methods Meta makes available to us. • In connection with your use of the WhatsApp Business Solution, you will not submit any content, information, or data that is subject to safeguarding and/or limitations on distribution pursuant to applicable laws and/or regulation. • WhatsApp’s pricing for use of the WhatsApp Business Solution can be found at Conversation-Based Pricing. • To create a WhatsApp Business Account (WABA), your business needs a Meta Business Account. Check if your company already has a Meta Business Account. If you don't have a Meta Business Account, you can create one during the sign-up process. • To use a phone number that's already in use with the WhatsApp Messenger application or WhatsApp Business application, you must delete it first. • A phone number that can receive either an SMS or a voice One-Time Passcode (OTP). The phone number used for sign-up becomes associated with your WhatsApp account and the phone number is used when you send messages.
social-ug-005
social-ug.pdf
5
a WhatsApp Business Account (WABA), your business needs a Meta Business Account. Check if your company already has a Meta Business Account. If you don't have a Meta Business Account, you can create one during the sign-up process. • To use a phone number that's already in use with the WhatsApp Messenger application or WhatsApp Business application, you must delete it first. • A phone number that can receive either an SMS or a voice One-Time Passcode (OTP). The phone number used for sign-up becomes associated with your WhatsApp account and the phone number is used when you send messages. The phone number can still be used for SMS, MMS, and voice messaging. • If you are importing an existing WABA, you need the PINs for all the phone numbers associated with the imported WABA. To reset a lost or forgotten PIN, follow the directions in Updating PIN in the WhatsApp Business Platform Cloud API Reference. The following prerequisites must be met to use either an Amazon SNS topic or Amazon Connect instance as a message and event destination. Amazon SNS topic • An Amazon SNS topic has been created and permissions have been added. Note Amazon SNS FIFO topics are not supported. • (Optional) To use an Amazon SNS topic that is encrypted using AWS KMS keys you have to grant AWS End User Messaging Social permissions to the existing key policy. Prerequisites 11 AWS End User Messaging Social Amazon Connect instance User Guide • An Amazon Connect instances has been created and permissions have been added. Sign up through the console Follow these directions to create a new WhatsApp account, migrate your existing account, or add a phone number to an existing WABA. As part of the sign-up process, you give AWS End User Messaging Social access to your WhatsApp Business Account. You also allow AWS End User Messaging Social to bill you for messages. For more information on WhatsApp Business Accounts, see Understanding WhatsApp business account types. 1. Open the AWS End User Messaging Social console at https://console.aws.amazon.com/social- messaging/. 2. Choose Business accounts. 3. On the Link business account page, choose Launch Facebook portal. A new login window from Meta will appear. 4. In the Meta login window, enter your Facebook account credentials. On the WhatsApp business account page, choose Add WhatsApp phone number. On the Add WhatsApp phone number page, choose Launch Facebook portal. A new login window from Meta will appear. 5. In the Meta login window, enter your Facebook account credentials. 6. As part of the sign-up process, you give AWS End User Messaging Social access to your WhatsApp Business Account (WABA). You also allow AWS End User Messaging Social to bill you for messages. Choose Continue. 7. For Meta Business account, choose an existing Meta business account or Create a Meta Business account. a. b. c. d. e. (Optional) If you need to create a Meta Business account, follow these steps: For Business name, enter the name of your business. For Business website or profile page, enter either the URL for your company's website, or if your company doesn't have a website, enter the URL to your social media page. For Country, choose the country your business is located in. (Optional) Choose Add address and enter your business's address. Sign up through the console 12 AWS End User Messaging Social 8. Choose Next. User Guide 9. For Choose a WhatsApp Business Account, choose an existing WhatsApp Business Account (WABA), or if you need to create an account, choose Create a WhatsApp Business Account. For Create or Select a WhatsApp Business Profile, choose an existing WhatsApp business profile, or Create a new WhatsApp Business Profile. 10. Choose Next. 11. For Create a Business Profile, enter the following information: • For WhatsApp Business Account Name, enter a name for your account. This field is not customer facing. • For WhatsApp Business Profile display name, enter the name to display to your customers when they receive a message from you. We recommend that you use your company name as the display name. The name is reviewed by Meta and must comply with WhatsApp display name rules. To use a brand name that is different from your company name, there must be an externally published association between your company and the brand. This association must be displayed on your website and on the brand represented by the display name's website. Once you complete registration, Meta performs a review of your display name. Meta sends you an email telling you whether the display name has been approved or rejected. If your display name is rejected, your per day messaging limit is lowered and you could be disconnected from WhatsApp. Important To change your display name, you have to create a ticket with Meta support. • For Timezone, choose
social-ug-006
social-ug.pdf
6
company name, there must be an externally published association between your company and the brand. This association must be displayed on your website and on the brand represented by the display name's website. Once you complete registration, Meta performs a review of your display name. Meta sends you an email telling you whether the display name has been approved or rejected. If your display name is rejected, your per day messaging limit is lowered and you could be disconnected from WhatsApp. Important To change your display name, you have to create a ticket with Meta support. • For Timezone, choose the time zone the business is located in. • For Category, choose a category that best aligns with your business. Customers can view the category you as part of your contact information. • For Business Description, enter a description of your company. Customers can view your business description as part of your contact information. • For Website, enter your company's website. Customers can view your website as part of your contact information. • Choose Next. Sign up through the console 13 AWS End User Messaging Social User Guide 12. For Add a phone number for WhatsApp, enter a phone number to register. This phone number is displayed to your customers when you send them a message. 13. For Choose how you would like to verify your number, choose either Text message or Phone call. • Once you are ready to receive the verification code, choose Next. • Enter the verification code, and then choose Next. 14. Once your number has been verified, you can choose Next to close the window from Meta. 15. For WhatsApp business account expand Tags - optional to add tags to your WhatsApp business account. Tags are pairs of keys and values that you can optionally apply to your AWS resources to control access or usage. Choose Add new tag and enter a key-value pair to attach. 16. A WhatsApp Business Account can have one message and event destination to log events for the WhatsApp Business Account and all resources associated to the WhatsApp Business Account. To enable event logging in Amazon SNS, including logging of receiving a customer message, you must turn on Message and event publishing. For more information, see Message and event destinations in AWS End User Messaging Social. Important To be able to respond to customer messages, you must enable Message and event publishing. In the Message and event destination details section, turn on Event publishing. For Amazon SNS, choose either New Amazon SNS standard topic and enter a name in Topic name, or choose Existing Amazon SNS standard topic and choose a topic from the Topic arn dropdown list. 17. Under Phone numbers: For each phone number under WhatsApp Phone numbers: a. For Phone number verification, enter the existing PIN or enter a new PIN code. To reset a lost or forgotten PIN, follow the directions in Updating PIN in the WhatsApp Business Platform Cloud API Reference. b. For Additional setting: Sign up through the console 14 AWS End User Messaging Social User Guide i. For Data localization region - optional choose one of Meta's regions in which to store your data at rest. For more information on Meta's data privacy policies, see Data Privacy & Security and Cloud API Local Storage in the WhatsApp Business Platform Cloud API Reference. ii. Tags are pairs of keys and values that you can optionally apply to your AWS resources to control access or usage. Choose Add new tag and enter a key-value pair to attach. 18. A WhatsApp Business Account can have one message and event destination to log events for the WhatsApp Business Account and all resources associated to the WhatsApp Business Account. To enable event logging , including logging of receiving a customer message, you need to turn on Message and event publishing. For more information, see Message and event destinations in AWS End User Messaging Social. Important You must enable Message and event publishing to be able to respond to customer messages. In the Message and event destination details section, turn on Event publishing. 19. For Destination type choose either Amazon SNS or Amazon Connect a. To send your events to an Amazon SNS destination, enter an existing topic ARN in Topic ARN. For example IAM policies, see IAM policies for Amazon SNS topics. b. For Amazon Connect i. ii. For Connect instance choose an instance from the drop down. For Role ARN, choose either: A. Choose existing IAM role – Choose an existing IAM policy from the Existing IAM roles drop down. For example IAM policies, see IAM policies for Amazon Connect. B. Enter IAM role ARN – Enter the ARN of the IAM policy into Use existing IAM role Arn. For example IAM policies, see IAM policies for
social-ug-007
social-ug.pdf
7
to an Amazon SNS destination, enter an existing topic ARN in Topic ARN. For example IAM policies, see IAM policies for Amazon SNS topics. b. For Amazon Connect i. ii. For Connect instance choose an instance from the drop down. For Role ARN, choose either: A. Choose existing IAM role – Choose an existing IAM policy from the Existing IAM roles drop down. For example IAM policies, see IAM policies for Amazon Connect. B. Enter IAM role ARN – Enter the ARN of the IAM policy into Use existing IAM role Arn. For example IAM policies, see IAM policies for Amazon Connect. 20. To complete setup, choose Add phone number. Sign up through the console 15 AWS End User Messaging Social Next steps User Guide Once you've completed sign-up, you can start sending messages. When you're ready to start sending messages at scale, complete Business Verification. Now that your WhatsApp Business Account and AWS End User Messaging Social accounts are linked, see the following topics: • Learn about event destination to log events and receive incoming messages. • Learn how to create message templates. • Learn how to send a text or media message. • Learn how to receive a message. • Learn about Official Business Accounts to have a green check mark beside your display name and increase your message throughput. Next steps 16 AWS End User Messaging Social User Guide WhatsApp Business Account (WABA) in AWS End User Messaging Social With a WhatsApp Business Account (WABA), you can use the WhatsApp Business Platform to send messages directly to your customers. All of your WABAs are part of your Meta Business Portfolio. A WhatsApp Business Account contains your customer facing assets like phone number, templates, and business contact information. A WABA can only exist in one AWS Region. For more information on WhatsApp Business Accounts, see WhatsApp Business Accounts in the WhatsApp Business Platform Cloud API Reference. Important Working with Meta/WhatsApp • Your use of the WhatsApp Business Solution is subject to the terms and conditions of the WhatsApp Business Terms of Service, the WhatsApp Business Solution Terms, the WhatsApp Business Messaging Policy, the WhatsApp Messaging Guidelines, and all other terms, policies, or guidelines incorporated therein by reference. These might be updated from time to time. • Meta or WhatsApp may at any time prohibit your use of the WhatsApp Business Solution. • You must create a WhatsApp Business Account (WABA) with Meta and WhatsApp. • You must create a Business Manager account with Meta and link it to your WABA. • You must grant control of your WABA to us. At your request, we will transfer control of your WABA back to you in a reasonable and timely manner using the methods Meta makes available to us. • In connection with your use of the WhatsApp Business Solution, you will not submit any content, information, or data that is subject to safeguarding or limitations on distribution pursuant to applicable laws or regulations. • WhatsApp’s pricing for use of the WhatsApp Business Solution can be found at https:// developers.facebook.com/docs/whatsapp/pricing. Topics • View a WhatsApp Business Account (WABA) in AWS End User Messaging Social 17 AWS End User Messaging Social User Guide • Add a WhatsApp Business Account (WABA) in AWS End User Messaging Social • Understanding WhatsApp business account types View a WhatsApp Business Account (WABA) in AWS End User Messaging Social You can view the WABA associated with your AWS account. To view the WABA associated with your account 1. Open the AWS End User Messaging Social console at https://console.aws.amazon.com/social- messaging/. 2. In Business accounts, choose a WABA. 3. On the Phone numbers tab, view your phone number, display name, quality rating, and the number of business initiated conversations that you have left for the day. On the Event destinations tab, view your event destination. To edit your event destination, follow the directions in Message and event destinations in AWS End User Messaging Social. On the Templates tab, choose Manage message templates to edit your WhatsApp templates through Meta. Each WABA has a 250 template limit. On the Tags tab, you can manage your WABA resource tags. Add a WhatsApp Business Account (WABA) in AWS End User Messaging Social Add a new WABA to your account if you already have a WhatsApp Business Profile. As part of creating a new WABA, you must add a phone number to the WABA. • To add a new WABA to your account, follow the steps in Getting started with AWS End User Messaging Social: • In step 8, choose your WhatsApp Business Profile, and then choose a Create a new WhatsApp Business account. View a WABA 18 AWS End User Messaging Social User Guide Understanding WhatsApp business account types Your WhatsApp business account determines how you appear to your customers. When
social-ug-008
social-ug.pdf
8
Social Add a new WABA to your account if you already have a WhatsApp Business Profile. As part of creating a new WABA, you must add a phone number to the WABA. • To add a new WABA to your account, follow the steps in Getting started with AWS End User Messaging Social: • In step 8, choose your WhatsApp Business Profile, and then choose a Create a new WhatsApp Business account. View a WABA 18 AWS End User Messaging Social User Guide Understanding WhatsApp business account types Your WhatsApp business account determines how you appear to your customers. When you create a WhatsApp account, your account will be a Business Account. WhatsApp has two types of business accounts: • Business Account: WhatsApp verifies the authenticity of every account on the WhatsApp Business Platform. If a business account has completed the Business Verification process, the business name will be visible to all users. This feature helps users identify verified business accounts on WhatsApp. • Official Business Account: Along with the benefits of a business account, an official business account has a green checkmark badge in its profile and chat thread headers. Approval for a WhatsApp Official Business Account (OBA) requires providing evidence that the business is well known and recognized by consumers, such as articles, blog posts, or independent reviews. Approval for a WhatsApp OBA is not guaranteed, even if the business provides the required documentation. The approval process is subject to review and approval by WhatsApp. WhatsApp does not publicly disclose the specific criteria they use to evaluate and approve applications for Official Business Accounts. The businesses seeking a WhatsApp OBA must demonstrate their reputation and recognition, but final approval is at the discretion of WhatsApp. When you create a WhatsApp account, your account will be a Business Account. You can provide information to your customers about your business, such as website, address, and hours. For businesses that haven't completed WhatsApp Business Verification, the display name is shown in small text next to the phone number in the contacts view, not in the chat list or individual chat. Once the Meta Business Verification is completed, the WhatsApp Sender's display name will be shown in the chat list and individual chat threads. Additional resources • For more information on Business Account and Official Business Account, see Business Accounts in the WhatsApp Business Platform Cloud API Reference. • For more information on the Business Verification process, see Business Verification in the WhatsApp Business Platform Cloud API Reference. WhatsApp business account types 19 AWS End User Messaging Social User Guide Phone numbers in AWS End User Messaging Social All WhatsApp Business Accounts contain one or more phone numbers used to verify your identity with WhatsApp and are used as part of your sending identity. You can have multiple phone numbers associated with a WhatsApp Business Account (WABA) and use each phone number for a different brand. Topics • Phone number considerations for use with a WhatsApp Business Account • Add a phone number to a WhatsApp Business Account (WABA) • View a phone number's status • View a phone number's ID in AWS End User Messaging Social • Increase messaging conversation limits in WhatsApp • Increase message throughput in WhatsApp • Understanding phone number quality rating in WhatsApp Phone number considerations for use with a WhatsApp Business Account When you link a phone number with your WhatsApp Business Account (WABA), you should consider the following: • Phone numbers can only be linked to one WABA at a time. • The phone number can still be used for SMS, MMS, and voice calls. • Each phone number has a quality rating from Meta. You can obtain an SMS-capable phone number through AWS End User Messaging SMS by doing the following: 1. Make sure that the country or region for the phone number supports two-way SMS. 2. Request the phone number. Depending on the country or region, you may be required to register the phone number. Phone number considerations 20 AWS End User Messaging Social User Guide 3. Enable two-way SMS messaging for the phone number. Once setup is complete, your incoming SMS messages are sent to an event destination. Add a phone number to a WhatsApp Business Account (WABA) You can add phone numbers to an existing WhatsApp Business Account (WABA) or create a new WABA for the phone number. Prerequisites Before you begin, the following prerequisites must be met: • The phone number must be able to receive either an SMS or a voice One-Time Passcode (OTP). This is the phone number that is added to your WABA. • The phone number must not be associated with any other WABA. The following prerequisites must be met to use either an Amazon SNS topic or Amazon Connect instance as a message and event
social-ug-009
social-ug.pdf
9
to a WhatsApp Business Account (WABA) You can add phone numbers to an existing WhatsApp Business Account (WABA) or create a new WABA for the phone number. Prerequisites Before you begin, the following prerequisites must be met: • The phone number must be able to receive either an SMS or a voice One-Time Passcode (OTP). This is the phone number that is added to your WABA. • The phone number must not be associated with any other WABA. The following prerequisites must be met to use either an Amazon SNS topic or Amazon Connect instance as a message and event destination. Amazon SNS topic • An Amazon SNS topic has been created and permissions have been added. Note Amazon SNS FIFO topics are not supported. • (Optional) To use an Amazon SNS topic that is encrypted using AWS KMS keys you have to grant AWS End User Messaging Social permissions to the existing key policy. Amazon Connect instance • An Amazon Connect instances has been created and permissions have been added. Add a phone number to a WABA To add a new phone number to your existing WABA Add a phone number 21 AWS End User Messaging Social User Guide 1. Open the AWS End User Messaging Social console at https://console.aws.amazon.com/social- messaging/. 2. Choose Business Accounts, and then Add WhatsApp phone number. 3. On the Add WhatsApp phone number page, choose Launch Facebook portal. A new login window from Meta will appear. 4. In the Meta login window, enter your Meta developer account credentials and choose your business portfolio. 5. Choose the WABA and WhatsApp Business Profile that you want to add the phone number to. 6. Choose Next. 7. 8. For Add a phone number for WhatsApp, enter a phone number to register. This phone number is displayed to your customers when you send them a message. For Choose how you would like to verify your number, choose either Text message or Phone call. 9. Once you are ready to receive the verification code, choose Next 10. Enter the verification code, and then choose Next. Once your number has been verified, you can choose Next to close the window from Meta. 11. Under WhatsApp Phone numbers: a. For Phone number verification, enter the existing PIN or enter a new PIN code. To reset a lost or forgotten PIN, follow the directions in Updating PIN in the WhatsApp Business Platform Cloud API Reference. b. For Additional setting: i. For Data localization region - optional, choose one of Meta's regions in which to store your data at rest. For more information on Meta's data privacy policies, see Data Privacy & Security and Cloud API Local Storage in the WhatsApp Business Platform Cloud API Reference. ii. Tags are pairs of keys and values that you can optionally apply to your AWS resources to control access or usage. Choose Add new tag and enter a key-value pair to attach. 12. A WhatsApp Business Account can have one message and event destination to log events for the WhatsApp Business Account and all resources associated to the WhatsApp Business Account. To enable event logging, including logging of receiving a customer message, turn on Message and event publishing. For more information, see Message and event destinations in AWS End User Messaging Social. Add a phone number to a WABA 22 AWS End User Messaging Social User Guide Important You must enable Message and event publishing to be able to respond to customer messages. In the Message and event destination details section, turn on Event publishing. 13. For Destination type choose either Amazon SNS or Amazon Connect a. To send your events to an Amazon SNS destination, enter an existing topic ARN in Topic ARN. For example IAM policies, see IAM policies for Amazon SNS topics. b. For Amazon Connect i. ii. For Connect instance choose an instance from the drop down. For Two-way channel role, choose either: A. Choose existing IAM role – Choose an existing IAM policy from the Existing IAM roles drop down. For example IAM policies, see IAM policies for Amazon Connect. B. Enter IAM role ARN – Enter the ARN of the IAM policy into Use existing IAM role Arn. For example IAM policies, see IAM policies for Amazon Connect. 14. To complete setup, choose Add phone number. View a phone number's status To be able to send messages in AWS End User Messaging Social, the phone number's Status must be Active. 1. Open the AWS End User Messaging Social console at https://console.aws.amazon.com/social- messaging/. 2. Choose Phone numbers. 3. In the Phone numbers section, the Status column has each phone number's status. View a phone number's status 23 AWS End User Messaging Social User Guide Note If a phone number's Status is Incomplete setup, you can choose the phone number and then
social-ug-010
social-ug.pdf
10
IAM policies, see IAM policies for Amazon Connect. 14. To complete setup, choose Add phone number. View a phone number's status To be able to send messages in AWS End User Messaging Social, the phone number's Status must be Active. 1. Open the AWS End User Messaging Social console at https://console.aws.amazon.com/social- messaging/. 2. Choose Phone numbers. 3. In the Phone numbers section, the Status column has each phone number's status. View a phone number's status 23 AWS End User Messaging Social User Guide Note If a phone number's Status is Incomplete setup, you can choose the phone number and then choose Complete setup to finish setting up the phone number. View a phone number's ID in AWS End User Messaging Social To be able to send messages with the AWS CLI, you need the Phone number ID to identify the phone number to use when sending. 1. Open the AWS End User Messaging Social console at https://console.aws.amazon.com/social- messaging/. 2. Choose Phone numbers. 3. 4. In the Phone numbers section, choose a phone number. The Phone number details section contains the Phone number ID of the phone number. Increase messaging conversation limits in WhatsApp Messaging limits refer to the maximum number of business-initiated conversations a business phone number can open in a 24-hour period. Business phone numbers are initially limited to 250 business-initiated conversations in a 24-hour moving period. This limit can be increased by Meta based on the quality rating of your messages and how many messages you send. Business-initiated conversations can only use template messages. When a customer messages you, this opens a 24-hour service window. During this time, you can send all message types. You can increase your messaging limit to 1,000 messages on your own by following these guidelines: • Your business phone number must have an Active status. • If your business phone number has a low quality rating, it may continue to be limited to 250 business-initiated conversations per day until its quality rating improves. • Apply for Business Verification. If your business is approved, the messaging quality will be analyzed to determine if your messaging activity warrants an increase to your messaging limit. View a phone number's ID 24 AWS End User Messaging Social User Guide Based on the analysis, your request for a messaging limit increase will either be approved or denied by Meta. • Apply for Identity Verification. If you complete identity verification and your identity is confirmed, Meta will approve a messaging limit increase. • Open 1,000 or more business-initiated conversations in a 30-day moving period using a template with a high quality rating. Once you reach the 1,000 conversation threshold, your messaging quality will be analyzed to determine if your messaging activity warrants an increase to your messaging limit. The goal is to send high-quality messages consistently to potentially get your messaging limit increased. If you completed Business Verification or Identity Verification, or opened 1,000 or more business conversations, and you are still limited to 250 business-initiated conversations, submit a request to Meta for a message tier upgrade. If your business or identity verification is rejected, you can improve your chances of getting approved by sending high-quality messages. By sending high-quality, compliant, and opt-in messages, your messaging activity and quality may be reevaluated, potentially leading to an increase in your approved messaging capabilities. Your messaging quality score on WhatsApp is calculated based on recent user feedback and interactions, with more weight given to more recent data. This helps assess the overall quality and reliability of your messaging on the platform. Message limits level increases • 1K business-initiated conversations • 10K business-initiated conversations • 100K business-initiated conversations • An unlimited number of business-initiated conversations Increase message throughput in WhatsApp Message throughput is the number of incoming and outgoing messages per second (MPS) for a phone number. By default, each phone number has an MPS of 80. Meta can increase your MPS to 1,000 if you meet the following requirements: Increase message throughput 25 AWS End User Messaging Social User Guide • The phone number must be able to send an unlimited number of business-initiated conversations • The phone number must have a quality rating of medium or higher. Understanding phone number quality rating in WhatsApp The quality of your phone number and messages is determined by Meta. Your messaging quality score is based on how your messages have been received by customers over the past seven days, with more recent messages weighted more heavily. The messaging quality score is calculated based on a combination of quality signals from the conversations between you and your WhatsApp users. These signals include user feedback like blocks, reports, and the reasons users provide when they block a business. Meta evaluates the quality of your messages based on how well they are received by your customers