id
stringlengths
8
78
source
stringclasses
743 values
chunk_id
int64
1
5.05k
text
stringlengths
593
49.7k
sqs-dg-130
sqs-dg.pdf
130
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" 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.") Publish messages to queues 509 Amazon Simple Queue Service println( Developer Guide """ 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. 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") Publish messages to queues 510 Amazon Simple Queue Service Developer Guide 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) 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.") Publish messages to queues 511 Amazon Simple Queue Service Developer Guide // 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( """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.") Publish messages to queues 512 Amazon Simple Queue Service Developer Guide 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") 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") }
sqs-dg-131
sqs-dg.pdf
131
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") 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) Publish messages to queues 513 Amazon Simple Queue Service Developer Guide } 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) 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 { Publish messages to queues 514 Amazon Simple Queue Service Developer Guide 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.") } } 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) } Publish messages to queues 515 Amazon Simple Queue Service Developer Guide 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 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.") } } Publish messages to queues 516 Amazon Simple Queue Service Developer Guide 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 { 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) Publish messages to queues 517 Amazon Simple Queue Service Developer Guide 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.") } } } } // 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.
sqs-dg-132
sqs-dg.pdf
132
= "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.") } } } } // 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) Publish messages to queues 518 Amazon Simple Queue Service Developer Guide 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) 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) { Publish messages to queues 519 Amazon Simple Queue Service Developer Guide 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) 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 Publish messages to queues 520 Amazon Simple Queue Service } Developer Guide 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 } 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? { Publish messages to queues 521 Amazon Simple Queue Service Developer Guide 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 • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe Publish messages to queues 522 Amazon Simple Queue Service Swift SDK for Swift Note Developer Guide 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: """ 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)
sqs-dg-133
sqs-dg.pdf
133
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: """ 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: "") Publish messages to queues 523 Amazon Simple Queue Service Developer Guide 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. /// /// - 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)") } Publish messages to queues 524 Amazon Simple Queue Service Developer Guide 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", "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() { Publish messages to queues 525 Amazon Simple Queue Service Developer Guide 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 { filterString += "," } first = false filterString += "\"\(ans)\"" } let filterJSON = "{ \"tone\": [\(filterString)]}" attr["FilterPolicy"] = filterJSON return attr } /// Create a queue, returning its URL string. /// Publish messages to queues 526 Amazon Simple Queue Service Developer Guide /// - 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 { 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.
sqs-dg-134
sqs-dg.pdf
134
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 { 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? { Publish messages to queues 527 Amazon Simple Queue Service Developer Guide 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": """ { "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "\(queueArn)", "Condition": { "ArnEquals": { "aws:SourceArn": "\(topicArn)" } } Publish messages to queues 528 Amazon Simple Queue Service Developer Guide } ] } """ ], 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( 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. Publish messages to queues 529 Amazon Simple Queue Service Developer Guide 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, 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 ?? "..."))") } } Publish messages to queues 530 Amazon Simple Queue Service } Developer Guide /// 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) 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 Publish messages to queues 531 Amazon Simple Queue Service Developer Guide supported. Deduplication IDs
sqs-dg-135
sqs-dg.pdf
135
clients. let snsConfig = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: snsConfig) 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 Publish messages to queues 531 Amazon Simple Queue Service Developer Guide 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 // 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. Publish messages to queues 532 Amazon Simple Queue Service Developer Guide 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 // 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 } Publish messages to queues 533 Amazon Simple Queue Service Developer Guide // 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( """ 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)? Publish messages to queues 534 Amazon Simple Queue Service Developer Guide """ 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!") 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 Publish messages to queues 535 Amazon Simple Queue Service Developer Guide 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:
sqs-dg-136
sqs-dg.pdf
136
to create queue 2!") 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 Publish messages to queues 535 Amazon Simple Queue Service Developer Guide 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!!! 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. Publish messages to queues 536 Amazon Simple Queue Service Developer Guide 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: ") } } // 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 } Publish messages to queues 537 Amazon Simple Queue Service Developer Guide 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:") 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. Publish messages to queues 538 Amazon Simple Queue Service Developer Guide 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) ) } } /// 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) } } } Publish messages to queues 539 Amazon Simple Queue Service Developer Guide • 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 SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Send and receive batches of messages with Amazon SQS using an AWS SDK The following code example shows how to: • Create an Amazon SQS queue. • Send batches of messages to the queue. • Receive batches of messages from the queue. • Delete batches of messages from
sqs-dg-137
sqs-dg.pdf
137
• DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Send and receive batches of messages with Amazon SQS using an AWS SDK The following code example shows how to: • Create an Amazon SQS queue. • Send batches of messages to the queue. • Receive batches of messages from the queue. • Delete batches of messages from the queue. Send and receive batches of messages 540 Amazon Simple Queue Service Python SDK for Python (Boto3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create functions to wrap Amazon SQS message functions. import logging import sys import boto3 from botocore.exceptions import ClientError import queue_wrapper logger = logging.getLogger(__name__) sqs = boto3.resource("sqs") def send_messages(queue, messages): """ Send a batch of messages in a single request to an SQS queue. This request may return overall success even when some messages were not sent. The caller must inspect the Successful and Failed lists in the response and resend any failed messages. :param queue: The queue to receive the messages. :param messages: The messages to send to the queue. These are simplified to contain only the message body and attributes. :return: The response from SQS that contains the list of successful and failed messages. """ try: entries = [ { "Id": str(ind), "MessageBody": msg["body"], Send and receive batches of messages 541 Amazon Simple Queue Service Developer Guide "MessageAttributes": msg["attributes"], } for ind, msg in enumerate(messages) ] response = queue.send_messages(Entries=entries) if "Successful" in response: for msg_meta in response["Successful"]: logger.info( "Message sent: %s: %s", msg_meta["MessageId"], messages[int(msg_meta["Id"])]["body"], ) if "Failed" in response: for msg_meta in response["Failed"]: logger.warning( "Failed to send: %s: %s", msg_meta["MessageId"], messages[int(msg_meta["Id"])]["body"], ) except ClientError as error: logger.exception("Send messages failed to queue: %s", queue) raise error else: return response def receive_messages(queue, max_number, wait_time): """ Receive a batch of messages in a single request from an SQS queue. :param queue: The queue from which to receive messages. :param max_number: The maximum number of messages to receive. The actual number of messages received might be less. :param wait_time: The maximum time to wait (in seconds) before returning. When this number is greater than zero, long polling is used. This can result in reduced costs and fewer false empty responses. :return: The list of Message objects received. These each contain the body of the message and metadata and custom attributes. """ Send and receive batches of messages 542 Amazon Simple Queue Service try: messages = queue.receive_messages( MessageAttributeNames=["All"], MaxNumberOfMessages=max_number, WaitTimeSeconds=wait_time, ) for msg in messages: Developer Guide logger.info("Received message: %s: %s", msg.message_id, msg.body) except ClientError as error: logger.exception("Couldn't receive messages from queue: %s", queue) raise error else: return messages def delete_messages(queue, messages): """ Delete a batch of messages from a queue in a single request. :param queue: The queue from which to delete the messages. :param messages: The list of messages to delete. :return: The response from SQS that contains the list of successful and failed message deletions. """ try: entries = [ {"Id": str(ind), "ReceiptHandle": msg.receipt_handle} for ind, msg in enumerate(messages) ] response = queue.delete_messages(Entries=entries) if "Successful" in response: for msg_meta in response["Successful"]: logger.info("Deleted %s", messages[int(msg_meta["Id"])].receipt_handle) if "Failed" in response: for msg_meta in response["Failed"]: logger.warning( "Could not delete %s", messages[int(msg_meta["Id"])].receipt_handle ) except ClientError: logger.exception("Couldn't delete messages from queue %s", queue) Send and receive batches of messages 543 Amazon Simple Queue Service Developer Guide else: return response Use the wrapper functions to send and receive messages in batches. def usage_demo(): """ Shows how to: * Read the lines from this Python file and send the lines in batches of 10 as messages to a queue. * Receive the messages in batches until the queue is empty. * Reassemble the lines of the file and verify they match the original file. """ def pack_message(msg_path, msg_body, msg_line): return { "body": msg_body, "attributes": { "path": {"StringValue": msg_path, "DataType": "String"}, "line": {"StringValue": str(msg_line), "DataType": "String"}, }, } def unpack_message(msg): return ( msg.message_attributes["path"]["StringValue"], msg.body, int(msg.message_attributes["line"]["StringValue"]), ) print("-" * 88) print("Welcome to the Amazon Simple Queue Service (Amazon SQS) demo!") print("-" * 88) queue = queue_wrapper.create_queue("sqs-usage-demo-message-wrapper") with open(__file__) as file: lines = file.readlines() line = 0 Send and receive batches of messages 544 Amazon Simple Queue Service Developer Guide batch_size = 10 received_lines = [None] * len(lines) print(f"Sending file lines in batches of {batch_size} as messages.") while line < len(lines): messages = [ pack_message(__file__, lines[index], index) for index in range(line, min(line + batch_size, len(lines))) ] line = line + batch_size send_messages(queue, messages) print(".", end="") sys.stdout.flush() print(f"Done. Sent {len(lines) - 1} messages.") print(f"Receiving, handling, and deleting messages in
sqs-dg-138
sqs-dg.pdf
138
print("-" * 88) print("Welcome to the Amazon Simple Queue Service (Amazon SQS) demo!") print("-" * 88) queue = queue_wrapper.create_queue("sqs-usage-demo-message-wrapper") with open(__file__) as file: lines = file.readlines() line = 0 Send and receive batches of messages 544 Amazon Simple Queue Service Developer Guide batch_size = 10 received_lines = [None] * len(lines) print(f"Sending file lines in batches of {batch_size} as messages.") while line < len(lines): messages = [ pack_message(__file__, lines[index], index) for index in range(line, min(line + batch_size, len(lines))) ] line = line + batch_size send_messages(queue, messages) print(".", end="") sys.stdout.flush() print(f"Done. Sent {len(lines) - 1} messages.") print(f"Receiving, handling, and deleting messages in batches of {batch_size}.") more_messages = True while more_messages: received_messages = receive_messages(queue, batch_size, 2) print(".", end="") sys.stdout.flush() for message in received_messages: path, body, line = unpack_message(message) received_lines[line] = body if received_messages: delete_messages(queue, received_messages) else: more_messages = False print("Done.") if all([lines[index] == received_lines[index] for index in range(len(lines))]): print(f"Successfully reassembled all file lines!") else: print(f"Uh oh, some lines were missed!") queue.delete() print("Thanks for watching!") print("-" * 88) Send and receive batches of messages 545 Amazon Simple Queue Service Developer Guide • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • CreateQueue • DeleteMessageBatch • DeleteQueue • ReceiveMessage • SendMessageBatch For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use the AWS Message Processing Framework for .NET to publish and receive Amazon SQS messages The following code example shows how to create applications that publish and receive Amazon SQS messages using the AWS Message Processing Framework for .NET. .NET SDK for .NET Provides a tutorial for the AWS Message Processing Framework for .NET. The tutorial creates a web application that allows the user to publish an Amazon SQS message and a command- line application that receives the message. For complete source code and instructions on how to set up and run, see the full tutorial in the AWS SDK for .NET Developer Guide and the example on GitHub. Services used in this example • Amazon SQS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use the AWS Message Processing Framework for .NET with Amazon SQS 546 Amazon Simple Queue Service Developer Guide Use the Amazon SQS Java Messaging Library to work with the Java Message Service (JMS) interface for Amazon SQS The following code example shows how to use the Amazon SQS Java Messaging Library to work with the JMS interface. 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. The following examples work with standard Amazon SQS queues and include: • Sending a text message. • Receiving messages synchronously. • Receiving messages asynchronously. • Receiving messages using CLIENT_ACKNOWLEDGE mode. • Receiving messages using the UNORDERED_ACKNOWLEDGE mode. • Using Spring to inject dependencies. • A utility class that provides common methods used by the other examples. For more information on using JMS with Amazon SQS, see the Amazon SQS Developer Guide. Sending a text message. /** * This method establishes a connection to a standard Amazon SQS queue using the Amazon SQS * Java Messaging Library and sends text messages to it. It uses JMS (Java Message Service) API * with automatic acknowledgment mode to ensure reliable message delivery, and automatically * manages all messaging resources. * Use the Amazon SQS Java Messaging Library to work with the JMS interface 547 Amazon Simple Queue Service Developer Guide * @throws JMSException If there is a problem connecting to or sending messages to the queue */ public static void doSendTextMessage() throws JMSException { // Create a connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); // Create the connection in a try-with-resources statement so that it's closed automatically. try (SQSConnection connection = connectionFactory.createConnection()) { // Create the queue if needed. SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT); // Create a session that uses the JMS auto-acknowledge mode. Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); createAndSendMessages(session, producer); } // The connection closes automatically. This also closes the session. LOGGER.info("Connection closed"); } /** * This method reads text input from the keyboard and sends each line as a separate message * to a standard Amazon SQS queue using the Amazon SQS Java Messaging Library. It continues * to accept input until the user enters an empty line, using JMS (Java Message Service) API to * handle the message delivery. * * @param session The JMS session used to create messages * @param producer The JMS message producer used to send messages
sqs-dg-139
sqs-dg.pdf
139
Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); createAndSendMessages(session, producer); } // The connection closes automatically. This also closes the session. LOGGER.info("Connection closed"); } /** * This method reads text input from the keyboard and sends each line as a separate message * to a standard Amazon SQS queue using the Amazon SQS Java Messaging Library. It continues * to accept input until the user enters an empty line, using JMS (Java Message Service) API to * handle the message delivery. * * @param session The JMS session used to create messages * @param producer The JMS message producer used to send messages to the queue */ private static void createAndSendMessages(Session session, MessageProducer producer) { Use the Amazon SQS Java Messaging Library to work with the JMS interface 548 Amazon Simple Queue Service Developer Guide BufferedReader inputReader = new BufferedReader( new InputStreamReader(System.in, Charset.defaultCharset())); try { String input; while (true) { LOGGER.info("Enter message to send (leave empty to exit): "); input = inputReader.readLine(); if (input == null || input.isEmpty()) break; TextMessage message = session.createTextMessage(input); producer.send(message); LOGGER.info("Send message {}", message.getJMSMessageID()); } } catch (EOFException e) { // Just return on EOF } catch (IOException e) { LOGGER.error("Failed reading input: {}", e.getMessage(), e); } catch (JMSException e) { LOGGER.error("Failed sending message: {}", e.getMessage(), e); } } Receiving messages synchronously. /** * This method receives messages from a standard Amazon SQS queue using the Amazon SQS Java * Messaging Library. It creates a connection to the queue using JMS (Java Message Service), * waits for messages to arrive, and processes them one at a time. The method handles all * necessary setup and cleanup of messaging resources. * * @throws JMSException If there is a problem connecting to or receiving messages from the queue */ public static void doReceiveMessageSync() throws JMSException { // Create a connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() Use the Amazon SQS Java Messaging Library to work with the JMS interface 549 Amazon Simple Queue Service ); Developer Guide // Create a connection. try (SQSConnection connection = connectionFactory.createConnection() ) { // Create the queue if needed. SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT); // Create a session. Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); connection.start(); receiveMessages(consumer); } // The connection closes automatically. This also closes the session. LOGGER.info("Connection closed"); } /** * This method continuously checks for new messages from a standard Amazon SQS queue using * the Amazon SQS Java Messaging Library. It waits up to 20 seconds for each message, processes * it using JMS (Java Message Service), and confirms receipt. The method stops checking for * messages after 20 seconds of no activity. * * @param consumer The JMS message consumer that receives messages from the queue */ private static void receiveMessages(MessageConsumer consumer) { try { while (true) { LOGGER.info("Waiting for messages..."); // Wait 1 minute for a message Message message = consumer.receive(Duration.ofSeconds(20).toMillis()); if (message == null) { LOGGER.info("Shutting down after 20 seconds of silence."); break; Use the Amazon SQS Java Messaging Library to work with the JMS interface 550 Amazon Simple Queue Service } Developer Guide SqsJmsExampleUtils.handleMessage(message); message.acknowledge(); LOGGER.info("Acknowledged message {}", message.getJMSMessageID()); } } catch (JMSException e) { LOGGER.error("Error receiving from SQS: {}", e.getMessage(), e); } } Receiving messages asynchronously. /** * This method sets up automatic message handling for a standard Amazon SQS queue using the * Amazon SQS Java Messaging Library. It creates a listener that processes messages as soon * as they arrive using JMS (Java Message Service), runs for 5 seconds, then cleans up all * messaging resources. * * @throws JMSException If there is a problem connecting to or receiving messages from the queue */ public static void doReceiveMessageAsync() throws JMSException { // Create a connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); // Create a connection. try (SQSConnection connection = connectionFactory.createConnection() ) { // Create the queue if needed. SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT); // Create a session. Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); Use the Amazon SQS Java Messaging Library to work with the JMS interface 551 Amazon Simple Queue Service Developer Guide try { // Create a consumer for the queue. MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); // Provide an implementation of the MessageListener interface, which has a single 'onMessage' method. // We use a lambda expression for the implementation. consumer.setMessageListener(message -> { try { SqsJmsExampleUtils.handleMessage(message); message.acknowledge(); } catch (JMSException e) { LOGGER.error("Error processing message: {}", e.getMessage()); } }); // Start receiving incoming messages. connection.start(); LOGGER.info("Waiting for messages..."); } catch (JMSException e) { throw new RuntimeException(e); } try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } } // The connection closes automatically. This also closes the session. LOGGER.info( "Connection closed" ); } Receiving messages using CLIENT_ACKNOWLEDGE mode. /** * This method demonstrates how message acknowledgment affects message processing in a standard * Amazon SQS queue using the Amazon SQS
sqs-dg-140
sqs-dg.pdf
140
We use a lambda expression for the implementation. consumer.setMessageListener(message -> { try { SqsJmsExampleUtils.handleMessage(message); message.acknowledge(); } catch (JMSException e) { LOGGER.error("Error processing message: {}", e.getMessage()); } }); // Start receiving incoming messages. connection.start(); LOGGER.info("Waiting for messages..."); } catch (JMSException e) { throw new RuntimeException(e); } try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } } // The connection closes automatically. This also closes the session. LOGGER.info( "Connection closed" ); } Receiving messages using CLIENT_ACKNOWLEDGE mode. /** * This method demonstrates how message acknowledgment affects message processing in a standard * Amazon SQS queue using the Amazon SQS Java Messaging Library. It sends messages to the queue, * then shows how JMS (Java Message Service) client acknowledgment mode handles both explicit Use the Amazon SQS Java Messaging Library to work with the JMS interface 552 Amazon Simple Queue Service Developer Guide * and implicit message confirmations, including how acknowledging one message can automatically * acknowledge previous messages. * * @throws JMSException If there is a problem with the messaging operations */ public static void doReceiveMessagesSyncClientAcknowledge() throws JMSException { // Create a connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); // Create the connection in a try-with-resources statement so that it's closed automatically. try (SQSConnection connection = connectionFactory.createConnection() ) { // Create the queue if needed. SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, TIME_OUT_SECONDS); // Create a session with client acknowledge mode. Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create a producer and consumer. MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); // Open the connection. connection.start(); // Send two text messages. sendMessage(producer, session, "Message 1"); sendMessage(producer, session, "Message 2"); // Receive a message and don't acknowledge it. receiveMessage(consumer, false); // Receive another message and acknowledge it. receiveMessage(consumer, true); Use the Amazon SQS Java Messaging Library to work with the JMS interface 553 Amazon Simple Queue Service Developer Guide // Wait for the visibility time out, so that unacknowledged messages reappear in the queue, LOGGER.info("Waiting for visibility timeout..."); try { Thread.sleep(TIME_OUT_MILLIS); } catch (InterruptedException e) { LOGGER.error("Interrupted while waiting for visibility timeout", e); Thread.currentThread().interrupt(); throw new RuntimeException("Processing interrupted", e); } /* We will attempt to receive another message, but none will be available. This is because in CLIENT_ACKNOWLEDGE mode, when we acknowledged the second message, all previous messages were automatically acknowledged as well. Therefore, although we never directly acknowledged the first message, it was implicitly acknowledged when we confirmed the second one. */ receiveMessage(consumer, true); } // The connection closes automatically. This also closes the session. LOGGER.info("Connection closed."); } /** * Sends a text message using the specified JMS MessageProducer and Session. * * @param producer The JMS MessageProducer used to send the message * @param session The JMS Session used to create the text message * @param messageText The text content to be sent in the message * @throws JMSException If there is an error creating or sending the message */ private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException { // Create a text message and send it. producer.send(session.createTextMessage(messageText)); } /** Use the Amazon SQS Java Messaging Library to work with the JMS interface 554 Amazon Simple Queue Service Developer Guide * Receives and processes a message from a JMS queue using the specified consumer. * The method waits for a message until the configured timeout period is reached. * If a message is received, it is logged and optionally acknowledged based on the * acknowledge parameter. * * @param consumer The JMS MessageConsumer used to receive messages from the queue * @param acknowledge Boolean flag indicating whether to acknowledge the message. * If true, the message will be acknowledged after processing * @throws JMSException If there is an error receiving, processing, or acknowledging the message */ private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException { // Receive a message. Message message = consumer.receive(TIME_OUT_MILLIS); if (message == null) { LOGGER.info("Queue is empty!"); } else { // Since this queue has only text messages, cast the message object and print the text. LOGGER.info("Received: {} Acknowledged: {}", ((TextMessage) message).getText(), acknowledge); // Acknowledge the message if asked. if (acknowledge) message.acknowledge(); } } Receiving messages using the UNORDERED_ACKNOWLEDGE mode. /** * Demonstrates message acknowledgment behavior in UNORDERED_ACKNOWLEDGE mode with Amazon SQS JMS. * In this mode, each message must be explicitly acknowledged regardless of receive order. Use the Amazon SQS Java Messaging Library to work with the JMS interface 555 Amazon Simple Queue Service Developer Guide * Unacknowledged messages return to the queue after the visibility timeout expires, * unlike CLIENT_ACKNOWLEDGE mode where acknowledging one message acknowledges all previous messages. * * @throws JMSException If a JMS-related error occurs during message operations */ public static void doReceiveMessagesUnorderedAcknowledge() throws JMSException { // Create a connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); // Create the connection in a try-with-resources
sqs-dg-141
sqs-dg.pdf
141
JMS. * In this mode, each message must be explicitly acknowledged regardless of receive order. Use the Amazon SQS Java Messaging Library to work with the JMS interface 555 Amazon Simple Queue Service Developer Guide * Unacknowledged messages return to the queue after the visibility timeout expires, * unlike CLIENT_ACKNOWLEDGE mode where acknowledging one message acknowledges all previous messages. * * @throws JMSException If a JMS-related error occurs during message operations */ public static void doReceiveMessagesUnorderedAcknowledge() throws JMSException { // Create a connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); // Create the connection in a try-with-resources statement so that it's closed automatically. try( SQSConnection connection = connectionFactory.createConnection() ) { // Create the queue if needed. SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, TIME_OUT_SECONDS); // Create a session with unordered acknowledge mode. Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE); // Create the producer and consumer. MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME)); MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME)); // Open a connection. connection.start(); // Send two text messages. sendMessage(producer, session, "Message 1"); sendMessage(producer, session, "Message 2"); // Receive a message and don't acknowledge it. receiveMessage(consumer, false); Use the Amazon SQS Java Messaging Library to work with the JMS interface 556 Amazon Simple Queue Service Developer Guide // Receive another message and acknowledge it. receiveMessage(consumer, true); // Wait for the visibility time out, so that unacknowledged messages reappear in the queue. LOGGER.info("Waiting for visibility timeout..."); try { Thread.sleep(TIME_OUT_MILLIS); } catch (InterruptedException e) { LOGGER.error("Interrupted while waiting for visibility timeout", e); Thread.currentThread().interrupt(); throw new RuntimeException("Processing interrupted", e); } /* We will attempt to receive another message, and we'll get the first message again. This occurs because in UNORDERED_ACKNOWLEDGE mode, each message requires its own separate acknowledgment. Since we only acknowledged the second message, the first message remains in the queue for redelivery. */ receiveMessage(consumer, true); LOGGER.info("Connection closed."); } // The connection closes automatically. This also closes the session. } /** * Sends a text message to an Amazon SQS queue using JMS. * * @param producer The JMS MessageProducer for the queue * @param session The JMS Session for message creation * @param messageText The message content * @throws JMSException If message creation or sending fails */ private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException { // Create a text message and send it. producer.send(session.createTextMessage(messageText)); } /** * Synchronously receives a message from an Amazon SQS queue using the JMS API Use the Amazon SQS Java Messaging Library to work with the JMS interface 557 Amazon Simple Queue Service Developer Guide * with an acknowledgment parameter. * * @param consumer The JMS MessageConsumer for the queue * @param acknowledge If true, acknowledges the message after receipt * @throws JMSException If message reception or acknowledgment fails */ private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException { // Receive a message. Message message = consumer.receive(TIME_OUT_MILLIS); if (message == null) { LOGGER.info("Queue is empty!"); } else { // Since this queue has only text messages, cast the message object and print the text. LOGGER.info("Received: {} Acknowledged: {}", ((TextMessage) message).getText(), acknowledge); // Acknowledge the message if asked. if (acknowledge) message.acknowledge(); } } Using Spring to inject dependencies. package com.example.sqs.jms.spring; import com.amazon.sqs.javamessaging.SQSConnection; import com.example.sqs.jms.SqsJmsExampleUtils; import jakarta.jms.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.support.FileSystemXmlApplicationContext; import java.io.File; import java.net.URL; import java.util.concurrent.TimeUnit; /** Use the Amazon SQS Java Messaging Library to work with the JMS interface 558 Amazon Simple Queue Service Developer Guide * Demonstrates how to send and receive messages using the Amazon SQS Java Messaging Library * with Spring Framework integration. This example connects to a standard Amazon SQS message * queue using Spring's dependency injection to configure the connection and messaging components. * The application uses the JMS (Java Message Service) API to handle message operations. */ public class SpringExample { private static final Integer POLLING_SECONDS = 15; private static final String SPRING_XML_CONFIG_FILE = "SpringExampleConfiguration.xml.txt"; private static final Logger LOGGER = LoggerFactory.getLogger(SpringExample.class); /** * Demonstrates sending and receiving messages through a standard Amazon SQS message queue * using Spring Framework configuration. This method loads connection settings from an XML file, * establishes a messaging session using the Amazon SQS Java Messaging Library, and processes * messages using JMS (Java Message Service) operations. If the queue doesn't exist, it will * be created automatically. * * @param args Command line arguments (not used) */ public static void main(String[] args) { URL resource = SpringExample.class.getClassLoader().getResource(SPRING_XML_CONFIG_FILE); File springFile = new File(resource.getFile()); if (!springFile.exists() || !springFile.canRead()) { LOGGER.error("File " + SPRING_XML_CONFIG_FILE + " doesn't exist or isn't readable."); System.exit(1); } try (FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("file://" + springFile.getAbsolutePath())) { Use the Amazon SQS Java Messaging Library to work with the JMS interface 559 Amazon Simple Queue Service Developer Guide Connection connection; try { connection = context.getBean(Connection.class); } catch (NoSuchBeanDefinitionException e) { LOGGER.error("Can't find the JMS connection to use: " + e.getMessage(), e); System.exit(2); return; }
sqs-dg-142
sqs-dg.pdf
142
created automatically. * * @param args Command line arguments (not used) */ public static void main(String[] args) { URL resource = SpringExample.class.getClassLoader().getResource(SPRING_XML_CONFIG_FILE); File springFile = new File(resource.getFile()); if (!springFile.exists() || !springFile.canRead()) { LOGGER.error("File " + SPRING_XML_CONFIG_FILE + " doesn't exist or isn't readable."); System.exit(1); } try (FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("file://" + springFile.getAbsolutePath())) { Use the Amazon SQS Java Messaging Library to work with the JMS interface 559 Amazon Simple Queue Service Developer Guide Connection connection; try { connection = context.getBean(Connection.class); } catch (NoSuchBeanDefinitionException e) { LOGGER.error("Can't find the JMS connection to use: " + e.getMessage(), e); System.exit(2); return; } String queueName; try { queueName = context.getBean("queueName", String.class); } catch (NoSuchBeanDefinitionException e) { LOGGER.error("Can't find the name of the queue to use: " + e.getMessage(), e); System.exit(3); return; } try { if (connection instanceof SQSConnection) { SqsJmsExampleUtils.ensureQueueExists((SQSConnection) connection, queueName, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT); } // Create the JMS session. Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); SqsJmsExampleUtils.sendTextMessage(session, queueName); MessageConsumer consumer = session.createConsumer(session.createQueue(queueName)); receiveMessages(consumer); } catch (JMSException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } } // Spring context autocloses. Managed Spring beans that implement AutoClosable, such as the // 'connection' bean, are also closed. LOGGER.info("Context closed"); } /** Use the Amazon SQS Java Messaging Library to work with the JMS interface 560 Amazon Simple Queue Service Developer Guide * Continuously checks for and processes messages from a standard Amazon SQS message queue * using the Amazon SQS Java Messaging Library underlying the JMS API. This method waits for incoming messages, * processes them when they arrive, and acknowledges their receipt using JMS (Java Message * Service) operations. The method will stop checking for messages after 15 seconds of * inactivity. * * @param consumer The JMS message consumer used to receive messages from the queue */ private static void receiveMessages(MessageConsumer consumer) { try { while (true) { LOGGER.info("Waiting for messages..."); // Wait 15 seconds for a message. Message message = consumer.receive(TimeUnit.SECONDS.toMillis(POLLING_SECONDS)); if (message == null) { LOGGER.info("Shutting down after {} seconds of silence.", POLLING_SECONDS); break; } SqsJmsExampleUtils.handleMessage(message); message.acknowledge(); LOGGER.info("Message acknowledged."); } } catch (JMSException e) { LOGGER.error("Error receiving from SQS.", e); } } } Spring bean definitions. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" Use the Amazon SQS Java Messaging Library to work with the JMS interface 561 Amazon Simple Queue Service Developer Guide http://www.springframework.org/schema/beans http://www.springframework.org/ schema/beans/spring-beans-3.0.xsd "> <!-- Define the AWS Region --> <bean id="region" class="software.amazon.awssdk.regions.Region" factory- method="of"> <constructor-arg value="us-east-1"/> </bean> <bean id="credentialsProviderBean" class="software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider" factory-method="create"/> <bean id="clientBuilder" class="software.amazon.awssdk.services.sqs.SqsClient" factory-method="builder"/> <bean id="regionSetClientBuilder" factory-bean="clientBuilder" factory- method="region"> <constructor-arg ref="region"/> </bean> <!-- Configure the Builder with Credentials Provider --> <bean id="sqsClient" factory-bean="regionSetClientBuilder" factory- method="credentialsProvider"> <constructor-arg ref="credentialsProviderBean"/> </bean> <bean id="providerConfiguration" class="com.amazon.sqs.javamessaging.ProviderConfiguration"> <property name="numberOfMessagesToPrefetch" value="5"/> </bean> <bean id="connectionFactory" class="com.amazon.sqs.javamessaging.SQSConnectionFactory"> <constructor-arg ref="providerConfiguration"/> <constructor-arg ref="clientBuilder"/> </bean> <bean id="connection" factory-bean="connectionFactory" factory-method="createConnection" init-method="start" destroy-method="close"/> Use the Amazon SQS Java Messaging Library to work with the JMS interface 562 Amazon Simple Queue Service Developer Guide <bean id="queueName" class="java.lang.String"> <constructor-arg value="SQSJMSClientExampleQueue"/> </bean> </beans> A utility class that provides common methods used by the other examples. package com.example.sqs.jms; import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazon.sqs.javamessaging.ProviderConfiguration; import com.amazon.sqs.javamessaging.SQSConnection; import com.amazon.sqs.javamessaging.SQSConnectionFactory; import jakarta.jms.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import java.time.Duration; import java.util.Base64; import java.util.Map; /** * This utility class provides helper methods for working with Amazon Simple Queue Service (Amazon SQS) * through the Java Message Service (JMS) interface. It contains common operations for managing message * queues and handling message delivery. */ public class SqsJmsExampleUtils { private static final Logger LOGGER = LoggerFactory.getLogger(SqsJmsExampleUtils.class); public static final Long QUEUE_VISIBILITY_TIMEOUT = 5L; /** * This method verifies that a message queue exists and creates it if necessary. The method checks for * an existing queue first to optimize performance. Use the Amazon SQS Java Messaging Library to work with the JMS interface 563 Amazon Simple Queue Service * Developer Guide * @param connection The active connection to the messaging service * @param queueName The name of the queue to verify or create * @param visibilityTimeout The duration in seconds that messages will be hidden after being received * @throws JMSException If there is an error accessing or creating the queue */ public static void ensureQueueExists(SQSConnection connection, String queueName, Long visibilityTimeout) throws JMSException { AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); /* In most cases, you can do this with just a 'createQueue' call, but 'getQueueUrl' (called by 'queueExists') is a faster operation for the common case where the queue already exists. Also, many users and roles have permission to call 'getQueueUrl' but don't have permission to call 'createQueue'. */ if( !client.queueExists(queueName) ) { CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(Map.of(QueueAttributeName.VISIBILITY_TIMEOUT, String.valueOf(visibilityTimeout))) .build(); client.createQueue( createQueueRequest ); } } /** * This method sends a simple text message to a specified message queue. It handles all necessary * setup for the message delivery process. * * @param session The active messaging session used to create and send the message * @param queueName
sqs-dg-143
sqs-dg.pdf
143
just a 'createQueue' call, but 'getQueueUrl' (called by 'queueExists') is a faster operation for the common case where the queue already exists. Also, many users and roles have permission to call 'getQueueUrl' but don't have permission to call 'createQueue'. */ if( !client.queueExists(queueName) ) { CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(Map.of(QueueAttributeName.VISIBILITY_TIMEOUT, String.valueOf(visibilityTimeout))) .build(); client.createQueue( createQueueRequest ); } } /** * This method sends a simple text message to a specified message queue. It handles all necessary * setup for the message delivery process. * * @param session The active messaging session used to create and send the message * @param queueName The name of the queue where the message will be sent */ public static void sendTextMessage(Session session, String queueName) { // Rest of implementation... try { Use the Amazon SQS Java Messaging Library to work with the JMS interface 564 Amazon Simple Queue Service Developer Guide MessageProducer producer = session.createProducer( session.createQueue( queueName) ); Message message = session.createTextMessage("Hello world!"); producer.send(message); } catch (JMSException e) { LOGGER.error( "Error receiving from SQS", e ); } } /** * This method processes incoming messages and logs their content based on the message type. * It supports text messages, binary data, and Java objects. * * @param message The message to be processed and logged * @throws JMSException If there is an error reading the message content */ public static void handleMessage(Message message) throws JMSException { // Rest of implementation... LOGGER.info( "Got message {}", message.getJMSMessageID() ); LOGGER.info( "Content: "); if(message instanceof TextMessage txtMessage) { LOGGER.info( "\t{}", txtMessage.getText() ); } else if(message instanceof BytesMessage byteMessage){ // Assume the length fits in an int - SQS only supports sizes up to 256k so that // should be true byte[] bytes = new byte[(int)byteMessage.getBodyLength()]; byteMessage.readBytes(bytes); LOGGER.info( "\t{}", Base64.getEncoder().encodeToString( bytes ) ); } else if( message instanceof ObjectMessage) { ObjectMessage objMessage = (ObjectMessage) message; LOGGER.info( "\t{}", objMessage.getObject() ); } } /** * This method sets up automatic message processing for a specified queue. It creates a listener * that will receive and handle incoming messages without blocking the main program. * * @param session The active messaging session * @param queueName The name of the queue to monitor Use the Amazon SQS Java Messaging Library to work with the JMS interface 565 Amazon Simple Queue Service Developer Guide * @param connection The active connection to the messaging service */ public static void receiveMessagesAsync(Session session, String queueName, Connection connection) { // Rest of implementation... try { // Create a consumer for the queue. MessageConsumer consumer = session.createConsumer(session.createQueue(queueName)); // Provide an implementation of the MessageListener interface, which has a single 'onMessage' method. // We use a lambda expression for the implementation. consumer.setMessageListener(message -> { try { SqsJmsExampleUtils.handleMessage(message); message.acknowledge(); } catch (JMSException e) { LOGGER.error("Error processing message: {}", e.getMessage()); } }); // Start receiving incoming messages. connection.start(); } catch (JMSException e) { throw new RuntimeException(e); } try { Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * This method performs cleanup operations after message processing is complete. It receives * any messages in the specified queue, removes the message queue and closes all * active connections to prevent resource leaks. * * @param queueName The name of the queue to be removed * @param visibilityTimeout The duration in seconds that messages are hidden after being received * @throws JMSException If there is an error during the cleanup process Use the Amazon SQS Java Messaging Library to work with the JMS interface 566 Amazon Simple Queue Service */ Developer Guide public static void cleanUpExample(String queueName, Long visibilityTimeout) throws JMSException { LOGGER.info("Performing cleanup."); SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); try (SQSConnection connection = connectionFactory.createConnection() ) { ensureQueueExists(connection, queueName, visibilityTimeout); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); receiveMessagesAsync(session, queueName, connection); SqsClient sqsClient = connection.getWrappedAmazonSQSClient().getAmazonSQSClient(); try { String queueUrl = sqsClient.getQueueUrl(b -> b.queueName(queueName)).queueUrl(); sqsClient.deleteQueue(b -> b.queueUrl(queueUrl)); LOGGER.info("Queue deleted: {}", queueUrl); } catch (SdkException e) { LOGGER.error("Error during SQS operations: ", e); } } LOGGER.info("Clean up: Connection closed"); } /** * This method creates a background task that sends multiple messages to a specified queue * after waiting for a set time period. The task operates independently to ensure efficient * message processing without interrupting other operations. * * @param queueName The name of the queue where messages will be sent * @param secondsToWait The number of seconds to wait before sending messages * @param numMessages The number of messages to send * @param visibilityTimeout The duration in seconds that messages remain hidden after being received * @return A task that can be executed to send the messages Use the Amazon SQS Java Messaging Library to work with the JMS interface 567 Amazon Simple Queue Service */ Developer Guide public static Runnable sendAMessageAsync(String queueName, Long secondsToWait, Integer numMessages, Long visibilityTimeout) { return () -> { try { Thread.sleep(Duration.ofSeconds(secondsToWait).toMillis()); } catch (InterruptedException e)
sqs-dg-144
sqs-dg.pdf
144
name of the queue where messages will be sent * @param secondsToWait The number of seconds to wait before sending messages * @param numMessages The number of messages to send * @param visibilityTimeout The duration in seconds that messages remain hidden after being received * @return A task that can be executed to send the messages Use the Amazon SQS Java Messaging Library to work with the JMS interface 567 Amazon Simple Queue Service */ Developer Guide public static Runnable sendAMessageAsync(String queueName, Long secondsToWait, Integer numMessages, Long visibilityTimeout) { return () -> { try { Thread.sleep(Duration.ofSeconds(secondsToWait).toMillis()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } try { SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), SqsClient.create() ); try (SQSConnection connection = connectionFactory.createConnection()) { ensureQueueExists(connection, queueName, visibilityTimeout); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); for (int i = 1; i <= numMessages; i++) { MessageProducer producer = session.createProducer(session.createQueue(queueName)); producer.send(session.createTextMessage("Hello World " + i + "!")); } } } catch (JMSException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } }; } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateQueue • DeleteQueue Use the Amazon SQS Java Messaging Library to work with the JMS interface 568 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Work with queue tags and Amazon SQS using an AWS SDK The following code example shows how to perform tagging operation with Amazon SQS. 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. The following example creates tags for a queue, lists tags, and removes a tag. import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.ListQueueTagsResponse; import software.amazon.awssdk.services.sqs.model.QueueDoesNotExistException; import software.amazon.awssdk.services.sqs.model.SqsException; import java.util.Map; import java.util.UUID; /** * Before running this Java V2 code example, set up your development environment, including your credentials. For more * information, see the <a href="https://docs.aws.amazon.com/sdk-for-java/latest/ developer-guide/get-started.html">AWS * SDK for Java Developer Guide</a>. */ public class TagExamples { static final SqsClient sqsClient = SqsClient.create(); Work with queue tags 569 Amazon Simple Queue Service Developer Guide static final String queueName = "TagExamples-queue-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20); private static final Logger LOGGER = LoggerFactory.getLogger(TagExamples.class); public static void main(String[] args) { final String queueUrl; try { queueUrl = sqsClient.createQueue(b -> b.queueName(queueName)).queueUrl(); LOGGER.info("Queue created. The URL is: {}", queueUrl); } catch (RuntimeException e) { LOGGER.error("Program ending because queue was not created."); throw new RuntimeException(e); } try { addTags(queueUrl); listTags(queueUrl); removeTags(queueUrl); } catch (RuntimeException e) { LOGGER.error("Program ending because of an error in a method."); } finally { try { sqsClient.deleteQueue(b -> b.queueUrl(queueUrl)); LOGGER.info("Queue successfully deleted. Program ending."); sqsClient.close(); } catch (RuntimeException e) { LOGGER.error("Program ending."); } finally { sqsClient.close(); } } } /** This method demonstrates how to use a Java Map to a tag a aueue. * @param queueUrl The URL of the queue to tag. */ public static void addTags(String queueUrl) { // Build a map of the tags. final Map<String, String> tagsToAdd = Map.of( "Team", "Development", "Priority", "Beta", "Accounting ID", "456def"); Work with queue tags 570 Amazon Simple Queue Service try { Developer Guide // Add tags to the queue using a Consumer<TagQueueRequest.Builder> parameter. sqsClient.tagQueue(b -> b .queueUrl(queueUrl) .tags(tagsToAdd) ); } catch (QueueDoesNotExistException e) { LOGGER.error("Queue does not exist: {}", e.getMessage(), e); throw new RuntimeException(e); } } /** This method demonstrates how to view the tags for a queue. * @param queueUrl The URL of the queue whose tags you want to list. */ public static void listTags(String queueUrl) { ListQueueTagsResponse response; try { // Call the listQueueTags method with a Consumer<ListQueueTagsRequest.Builder> parameter that creates a ListQueueTagsRequest. response = sqsClient.listQueueTags(b -> b .queueUrl(queueUrl)); } catch (SqsException e) { LOGGER.error("Exception thrown: {}", e.getMessage(), e); throw new RuntimeException(e); } // Log the tags. response.tags() .forEach((k, v) -> LOGGER.info("Key: {} -> Value: {}", k, v)); } /** * This method demonstrates how to remove tags from a queue. * @param queueUrl The URL of the queue whose tags you want to remove. */ public static void removeTags(String queueUrl) { try { // Call the untagQueue method with a Consumer<UntagQueueRequest.Builder> parameter. sqsClient.untagQueue(b -> b Work with queue tags 571 Amazon Simple Queue Service Developer Guide .queueUrl(queueUrl) .tagKeys("Accounting ID") // Remove a single tag. ); } catch (SqsException e) { LOGGER.error("Exception thrown: {}", e.getMessage(), e); throw new RuntimeException(e); } } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • ListQueueTags • TagQueue • UntagQueue For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details
sqs-dg-145
sqs-dg.pdf
145
// Call the untagQueue method with a Consumer<UntagQueueRequest.Builder> parameter. sqsClient.untagQueue(b -> b Work with queue tags 571 Amazon Simple Queue Service Developer Guide .queueUrl(queueUrl) .tagKeys("Accounting ID") // Remove a single tag. ); } catch (SqsException e) { LOGGER.error("Exception thrown: {}", e.getMessage(), e); throw new RuntimeException(e); } } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • ListQueueTags • TagQueue • UntagQueue For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Serverless examples for Amazon SQS The following code examples show how to use Amazon SQS with AWS SDKs. Examples • Invoke a Lambda function from an Amazon SQS trigger • Reporting batch item failures for Lambda functions with an Amazon SQS trigger Invoke a Lambda function from an Amazon SQS trigger The following code examples show how to implement a Lambda function that receives an event triggered by receiving messages from an SQS queue. The function retrieves the messages from the event parameter and logs the content of each message. Serverless examples 572 Amazon Simple Queue Service .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an SQS 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.SQSEvents; // 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))] namespace SqsIntegrationSampleCode { public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { foreach (var message in evnt.Records) { await ProcessMessageAsync(message, context); } context.Logger.LogInformation("done"); } private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { try { context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message Invoke a Lambda function from an Amazon SQS trigger 573 Amazon Simple Queue Service Developer Guide 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; } } } 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 SQS event with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package integration_sqs_to_lambda import ( "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) func handler(event events.SQSEvent) error { for _, record := range event.Records { err := processMessage(record) if err != nil { return err } Invoke a Lambda function from an Amazon SQS trigger 574 Amazon Simple Queue Service Developer Guide } fmt.Println("done") return nil } func processMessage(record events.SQSMessage) error { fmt.Printf("Processed message %s\n", record.Body) // TODO: Do interesting work based on the new message return nil } func main() { lambda.Start(handler) } 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 SQS event with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; public class Function implements RequestHandler<SQSEvent, Void> { @Override public Void handleRequest(SQSEvent sqsEvent, Context context) { for (SQSMessage msg : sqsEvent.getRecords()) { processMessage(msg, context); } context.getLogger().log("done"); Invoke a Lambda function from an Amazon SQS trigger 575 Amazon Simple Queue Service Developer Guide return null; } private void processMessage(SQSMessage msg, Context context) { try { context.getLogger().log("Processed message " + msg.getBody()); // TODO: Do interesting work based on the new message } catch (Exception e) { context.getLogger().log("An error occurred"); throw 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 SQS 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 message of event.Records) { await processMessageAsync(message); } console.info("done"); }; async function processMessageAsync(message) { try { console.log(`Processed message ${message.body}`); // TODO: Do interesting work based on the new message Invoke a Lambda function from an Amazon SQS trigger 576 Amazon Simple Queue Service Developer Guide await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } } Consuming an SQS event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SQSEvent, Context, SQSHandler, SQSRecord } from "aws-lambda"; export const functionHandler: SQSHandler = async ( event: SQSEvent, context: Context ): Promise<void> => { for (const message of event.Records) { await processMessageAsync(message); }
sqs-dg-146
sqs-dg.pdf
146
message ${message.body}`); // TODO: Do interesting work based on the new message Invoke a Lambda function from an Amazon SQS trigger 576 Amazon Simple Queue Service Developer Guide await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } } Consuming an SQS event with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SQSEvent, Context, SQSHandler, SQSRecord } from "aws-lambda"; export const functionHandler: SQSHandler = async ( event: SQSEvent, context: Context ): Promise<void> => { for (const message of event.Records) { await processMessageAsync(message); } console.info("done"); }; async function processMessageAsync(message: SQSRecord): Promise<any> { try { console.log(`Processed message ${message.body}`); // TODO: Do interesting work based on the new message await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } } Invoke a Lambda function from an Amazon SQS trigger 577 Amazon Simple Queue Service PHP SDK for PHP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an SQS event with Lambda using PHP. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\InvalidLambdaEvent; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $body = $record->getBody(); // TODO: Do interesting work based on the new message } Invoke a Lambda function from an Amazon SQS trigger 578 Amazon Simple Queue Service Developer Guide } } $logger = new StderrLogger(); return new Handler($logger); 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 SQS 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 message in event['Records']: process_message(message) print("done") def process_message(message): try: print(f"Processed message {message['body']}") # TODO: Do interesting work based on the new message except Exception as err: print("An error occurred") raise err Invoke a Lambda function from an Amazon SQS trigger 579 Amazon Simple Queue Service Ruby SDK for Ruby Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Consuming an SQS 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'].each do |message| process_message(message) end puts "done" end def process_message(message) begin puts "Processed message #{message['body']}" # TODO: Do interesting work based on the new message rescue StandardError => err puts "An error occurred" raise err end 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. Invoke a Lambda function from an Amazon SQS trigger 580 Amazon Simple Queue Service Developer Guide Consuming an SQS 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::sqs::SqsEvent; use lambda_runtime::{run, service_fn, Error, LambdaEvent}; async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<(), Error> { event.payload.records.iter().for_each(|record| { // process the record tracing::info!("Message body: {}", record.body.as_deref().unwrap_or_default()) }); Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) // disable printing the name of the module in every log line. .with_target(false) // disabling time is handy because CloudWatch will add the ingestion time. .without_time() .init(); run(service_fn(function_handler)).await } For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Reporting batch item failures for Lambda functions with an Amazon SQS trigger The following code examples show how to implement partial batch response for Lambda functions that receive events from an SQS queue. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later. Reporting batch item failures for Lambda functions with an Amazon SQS trigger 581 Amazon Simple Queue Service .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Reporting SQS batch item failures 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.SQSEvents; // 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))] namespace sqsSample; public class Function { public async Task<SQSBatchResponse> FunctionHandler(SQSEvent
sqs-dg-147
sqs-dg.pdf
147
Reporting batch item failures for Lambda functions with an Amazon SQS trigger 581 Amazon Simple Queue Service .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Reporting SQS batch item failures 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.SQSEvents; // 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))] namespace sqsSample; public class Function { public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evnt, ILambdaContext context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new List<SQSBatchResponse.BatchItemFailure>(); foreach(var message in evnt.Records) { try { //process your message await ProcessMessageAsync(message, context); } catch (System.Exception) { //Add failed message identifier to the batchItemFailures list batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); } Reporting batch item failures for Lambda functions with an Amazon SQS trigger 582 Amazon Simple Queue Service } return new SQSBatchResponse(batchItemFailures); } Developer Guide private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context) { if (String.IsNullOrEmpty(message.Body)) { throw new Exception("No Body in SQS Message."); } context.Logger.LogInformation($"Processed message {message.Body}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } } 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. Reporting SQS batch item failures with Lambda using Go. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package main import ( "context" "encoding/json" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" ) Reporting batch item failures for Lambda functions with an Amazon SQS trigger 583 Amazon Simple Queue Service Developer Guide func handler(ctx context.Context, sqsEvent events.SQSEvent) (map[string]interface{}, error) { batchItemFailures := []map[string]interface{}{} for _, message := range sqsEvent.Records { if /* Your message processing condition here */ { batchItemFailures = append(batchItemFailures, map[string]interface{} {"itemIdentifier": message.MessageId}) } } sqsBatchResponse := map[string]interface{}{ "batchItemFailures": batchItemFailures, } return sqsBatchResponse, nil } func main() { lambda.Start(handler) } 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. Reporting SQS batch item failures with Lambda using Java. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse; Reporting batch item failures for Lambda functions with an Amazon SQS trigger 584 Amazon Simple Queue Service Developer Guide import java.util.ArrayList; import java.util.List; public class ProcessSQSMessageBatch implements RequestHandler<SQSEvent, SQSBatchResponse> { @Override public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new ArrayList<SQSBatchResponse.BatchItemFailure>(); String messageId = ""; for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) { try { //process your message } catch (Exception e) { //Add failed message identifier to the batchItemFailures list batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(message.getMessageId())); } } return new SQSBatchResponse(batchItemFailures); } } 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. Reporting SQS batch item failures with Lambda using JavaScript. // Node.js 20.x Lambda runtime, AWS SDK for Javascript V3 export const handler = async (event, context) => { const batchItemFailures = []; for (const record of event.Records) { try { await processMessageAsync(record, context); Reporting batch item failures for Lambda functions with an Amazon SQS trigger 585 Amazon Simple Queue Service Developer Guide } catch (error) { batchItemFailures.push({ itemIdentifier: record.messageId }); } } return { batchItemFailures }; }; async function processMessageAsync(record, context) { if (record.body && record.body.includes("error")) { throw new Error("There is an error in the SQS Message."); } console.log(`Processed message: ${record.body}`); } Reporting SQS batch item failures with Lambda using TypeScript. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SQSEvent, SQSBatchResponse, Context, SQSBatchItemFailure, SQSRecord } from 'aws-lambda'; export const handler = async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => { const batchItemFailures: SQSBatchItemFailure[] = []; for (const record of event.Records) { try { await processMessageAsync(record); } catch (error) { batchItemFailures.push({ itemIdentifier: record.messageId }); } } return {batchItemFailures: batchItemFailures}; }; async function processMessageAsync(record: SQSRecord): Promise<void> { if (record.body && record.body.includes("error")) { throw new Error('There is an error in the SQS Message.'); } console.log(`Processed message ${record.body}`); } Reporting batch item failures for Lambda functions with an Amazon SQS trigger 586 Amazon Simple Queue Service PHP SDK for PHP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Reporting SQS batch item failures with Lambda using PHP. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php use Bref\Context\Context; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context
sqs-dg-148
sqs-dg.pdf
148
SQS trigger 586 Amazon Simple Queue Service PHP SDK for PHP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Reporting SQS batch item failures with Lambda using PHP. // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php use Bref\Context\Context; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { $this->logger->info("Processing SQS records"); $records = $event->getRecords(); foreach ($records as $record) { try { // Assuming the SQS message is in JSON format Reporting batch item failures for Lambda functions with an Amazon SQS trigger 587 Amazon Simple Queue Service Developer Guide $message = json_decode($record->getBody(), true); $this->logger->info(json_encode($message)); // TODO: Implement your custom processing logic here } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $this->markAsFailed($record); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords SQS records"); } } $logger = new StderrLogger(); return new Handler($logger); 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. Reporting SQS batch item failures 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): if event: batch_item_failures = [] sqs_batch_response = {} for record in event["Records"]: try: # process message except Exception as e: Reporting batch item failures for Lambda functions with an Amazon SQS trigger 588 Amazon Simple Queue Service Developer Guide batch_item_failures.append({"itemIdentifier": record['messageId']}) sqs_batch_response["batchItemFailures"] = batch_item_failures return sqs_batch_response 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. Reporting SQS batch item failures with Lambda using Ruby. # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require 'json' def lambda_handler(event:, context:) if event batch_item_failures = [] sqs_batch_response = {} event["Records"].each do |record| begin # process message rescue StandardError => e batch_item_failures << {"itemIdentifier" => record['messageId']} end end sqs_batch_response["batchItemFailures"] = batch_item_failures return sqs_batch_response end end Reporting batch item failures for Lambda functions with an Amazon SQS trigger 589 Amazon Simple Queue Service Rust SDK for Rust Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository. Reporting SQS batch item failures 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::sqs::{SqsBatchResponse, SqsEvent}, sqs::{BatchItemFailure, SqsMessage}, }; use lambda_runtime::{run, service_fn, Error, LambdaEvent}; async fn process_record(_: &SqsMessage) -> Result<(), Error> { Err(Error::from("Error processing message")) } async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<SqsBatchResponse, Error> { let mut batch_item_failures = Vec::new(); for record in event.payload.records { match process_record(&record).await { Ok(_) => (), Err(_) => batch_item_failures.push(BatchItemFailure { item_identifier: record.message_id.unwrap(), }), } } Ok(SqsBatchResponse { batch_item_failures, }) } #[tokio::main] async fn main() -> Result<(), Error> { Reporting batch item failures for Lambda functions with an Amazon SQS trigger 590 Amazon Simple Queue Service Developer Guide run(service_fn(function_handler)).await } For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Reporting batch item failures for Lambda functions with an Amazon SQS trigger 591 Amazon Simple Queue Service Developer Guide Troubleshooting issues in Amazon SQS This topic provides troubleshooting advice for common errors and issues that you might encounter when using the Amazon SQS console, Amazon SQS API, or other tools with Amazon SQS. If you find an issue that is not listed here, you can use the Feedback button on this page to report it. For more troubleshooting advice and answers to common support questions, visit the AWS Knowledge Center. Topics • Troubleshoot an access denied error in Amazon SQS • Troubleshoot Amazon SQS API errors • Troubleshoot Amazon SQS dead-letter queue and DLQ redrive issues • Troubleshoot FIFO throttling issues in Amazon SQS • Troubleshoot messages not returned for an Amazon SQS ReceiveMessage API call • Troubleshoot Amazon SQS network errors • Troubleshooting Amazon Simple Queue Service queues using AWS X-Ray Troubleshoot an access denied error in Amazon SQS The following topics cover the most common causes of AccessDenied or AccessDeniedException errors on Amazon SQS API calls. For more information on how to troubleshoot these errors, see How do I troubleshoot "AccessDenied" or "AccessDeniedException" errors on Amazon SQS API calls? in the AWS Knowledge Center Guide. Error message examples: An error occurred (AccessDenied) when calling the SendMessage operation: Access to the resource https://sqs.us-east-1.amazonaws.com/ is denied. - or - An error occurred (KMS.AccessDeniedException) when calling the
sqs-dg-149
sqs-dg.pdf
149
• Troubleshoot Amazon SQS network errors • Troubleshooting Amazon Simple Queue Service queues using AWS X-Ray Troubleshoot an access denied error in Amazon SQS The following topics cover the most common causes of AccessDenied or AccessDeniedException errors on Amazon SQS API calls. For more information on how to troubleshoot these errors, see How do I troubleshoot "AccessDenied" or "AccessDeniedException" errors on Amazon SQS API calls? in the AWS Knowledge Center Guide. Error message examples: An error occurred (AccessDenied) when calling the SendMessage operation: Access to the resource https://sqs.us-east-1.amazonaws.com/ is denied. - or - An error occurred (KMS.AccessDeniedException) when calling the SendMessage operation: User: arn:aws:iam::xxxxx:user/xxxx is not authorized to perform: kms:GenerateDataKey on resource: arn:aws:kms:us-east-1:xxxx:key/xxxx with an explicit Access denied error 592 Amazon Simple Queue Service deny. Developer Guide Amazon SQS queue policy and IAM policy To verify if the requester has proper permissions to perform an Amazon SQS operation, do the following: • Identify the IAM principal that’s making the Amazon SQS API call. If the IAM principal is from the same account, then either the Amazon SQS queue policy or the AWS Identity and Access Management (IAM) policy must include permissions to explicitly allow access for the action. • If the principal is an IAM entity: • You can identify your IAM user or role by checking the upper-right corner of the AWS Management Console, or by using the aws sts get-caller-identity command. • Check the IAM policies that are related to the IAM user or role. You can use one of the following methods: • Test IAM policies with the IAM Policy Simulator. • Review the different IAM policy types. • If needed, edit your IAM user policy. • Check the queue policy and edit if required. • If the principal is an AWS service, then the Amazon SQS queue policy must explicitly allow access. • If the principal is a cross-account principal, then both the Amazon SQS queue policy and the IAM policy must explicitly allow access. • If the policy uses a condition element, then check that the condition restricts access. Important An explicit deny in either policy overrides an explicit allow. Here are some basic examples of Amazon SQS policies. AWS Key Management Service permissions If your Amazon SQS queue has server-side encryption (SSE) turned on with a customer managed AWS KMS key, then permissions must be granted to both producers and consumers. To confirm if Amazon SQS queue policy and IAM policy 593 Amazon Simple Queue Service Developer Guide a queue is encrypted, you can use the GetQueueAttributes API KmsMasterKeyId attribute, or from the queue console under Encryption. • Required permissions for producers: { "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "<Key ARN>" } • Required permissions for consumers: { "Effect": "Allow", "Action": [ "kms:Decrypt" ], "Resource": "<Key ARN>" } • Required permissions for cross-account access: { "Effect": "Allow", "Action": [ "kms:DescribeKey", "kms:Decrypt", "kms:ReEncrypt", "kms:GenerateDataKey" ], "Resource": "<Key ARN>" } Choose one of the following options to enable encryption for an Amazon SQS queue: • SSE-Amazon SQS (Encryption key created and managed by the Amazon SQS service.) • AWS managed default key (alias/aws/sqs) AWS Key Management Service (AWS KMS) permissions 594 Amazon Simple Queue Service • Customer managed key Developer Guide However, if you are using an AWS-managed KMS key, you can't modify the default key policy. Therefore, to provide access to other services and cross-accounts, use customer managed key. Doing this allows you to edit the key policy. VPC endpoint policy If you access Amazon SQS through an Amazon Virtual Private Cloud (Amazon VPC) endpoint, the Amazon SQS VPC endpoint policy must allow access. You can create a policy for Amazon VPC endpoints for Amazon SQS, where you can specify the following: 1. The principal that can perform actions. 2. The actions that can be performed. 3. The resources on which actions can be performed. In the following example, the VPC endpoint policy specifies that the IAM user MyUser is allowed to send messages to the Amazon SQS queue MyQueue. Other actions, IAM users, and Amazon SQS resources are denied access through the VPC endpoint. { "Statement": [{ "Action": ["sqs:SendMessage"], "Effect": "Allow", "Resource": "arn:aws:sqs:us-east-2:123456789012:MyQueue", "Principal": { "AWS": "arn:aws:iam:123456789012:user/MyUser" } }] } Organization service control policy If your AWS account belongs to an organization, AWS Organizations policies can block you from accessing your Amazon SQS queues. By default, AWS Organizations policies do not block any requests to Amazon SQS. However, make sure that your AWS Organizations policies haven’t been configured to block access to Amazon SQS queues. For instructions on how to check your AWS Organizations policies, see Listing all policies in the AWS Organizations User Guide. VPC endpoint policy 595 Amazon Simple Queue Service Developer Guide Troubleshoot Amazon SQS API errors The following topics cover the most common errors returned when making Amazon
sqs-dg-150
sqs-dg.pdf
150
control policy If your AWS account belongs to an organization, AWS Organizations policies can block you from accessing your Amazon SQS queues. By default, AWS Organizations policies do not block any requests to Amazon SQS. However, make sure that your AWS Organizations policies haven’t been configured to block access to Amazon SQS queues. For instructions on how to check your AWS Organizations policies, see Listing all policies in the AWS Organizations User Guide. VPC endpoint policy 595 Amazon Simple Queue Service Developer Guide Troubleshoot Amazon SQS API errors The following topics cover the most common errors returned when making Amazon SQS API calls, and how to troubleshoot them. QueueDoesNotExist error This error will be returned when the Amazon SQS service can't find the mentioned queue for the Amazon SQS action. Possible causes and mitigations: • Incorrect region: Review the Amazon SQS client configuration to confirm that you configured the correct Region on the client. When you don't configure a Region on the client, then the SDK or AWS CLI chooses the Region from the configuration file or the environment variable. If the SDK doesn't find a Region in the configuration file, then the SDK sets the Region to us-east-1 by default. • Queue might be recently deleted: If the queue was deleted before the API call was made, then the API call will return this error. Check CloudTrail for any DeleteQueue operations before the time of the error. • Permission issues: If the requesting AWS Identity and Access Management (IAM) user or role doesn't have the required permissions, then you might receive the following error: The specified queue does not exist or you do not have access to it. Check the permissions, and make the API call with correct permissions. For more details on troubleshooting the QueueDoesNotExist error, see How do I troubleshoot the QueueDoesNotExist error when I make API calls to my Amazon SQS queue? in the AWS Knowledge Center Guide. InvalidAttributeValue error This error will be returned upon updating the Amazon SQS queue resource policy, or properties with an incorrect policy or a principal. Possible causes and mitigations: API errors 596 Amazon Simple Queue Service Developer Guide • Invalid resource policy: Check that the resource policy has all the required fields. For more information, see IAM JSON policy elements reference and Validating IAM policies. You can also use the IAM policy generator to create and test an Amazon SQS resource policy. Make sure that the policy is in JSON format. • Invalid principal: Ensure that the Principal element exists in the resource policy and that the value is valid. If your Amazon SQS resource policy Principal element includes an IAM entity, make sure that the entity exists before you use the policy. Amazon SQS validates the resource policy and checks for the IAM entity. If the IAM entity doesn't exist, you will receive an error. To confirm IAM entities, use the GetRole and GetUser APIs. For additional information on how to troubleshoot an InvalidAttributeValue error, see How do I troubleshoot the QueueDoesNotExist error when I make API calls to my Amazon SQS queue? in the AWS Knowledge Center Guide. ReceiptHandle error Upon making a DeleteMessage API call, the error ReceiptHandleIsInvalid or InvalidParameterValue might be returned if the receipt handle is incorrect or expired. • ReceiptHandleIsInvalid error: If the receipt handle is incorrect, you'll receive an error similar to this example: An error occurred (ReceiptHandleIsInvalid) when calling the DeleteMessage operation: The input receipt handle <YOUR RECEIPT HANDLE> is not a valid receipt handle. • InvalidParameterValue error: If the receipt handle is expired, you'll receive an error similar to this example: An error occurred (InvalidParameterValue) when calling the DeleteMessage operation: Value <YOUR RECEIPT HANDLE> for parameter ReceiptHandle is invalid. Reason: The receipt handle has expired. Possible causes and mitigations: The receipt handle is created for every received message, and is only valid for the visibility timeout period. When the visibility timeout period expires, the message becomes visible on the queue for consumers. When you receive the message again from the consumer, you receive a new receipt ReceiptHandle error 597 Amazon Simple Queue Service Developer Guide handle. To prevent incorrect or expired receipt handle errors, use the correct receipt handle to delete the message within the Amazon SQS queue visibility timeout period. For additional information on how to troubleshoot a ReceiptHandle error, see How do I troubleshoot "ReceiptHandleIsInvalid" and "InvalidParameterValue" errors when I use the Amazon SQS DeleteMessage API call? in the AWS Knowledge Center Guide. Troubleshoot Amazon SQS dead-letter queue and DLQ redrive issues The following topics cover the most common causes of Amazon SQS DLQ and DLQ redrive issues, and how to troubleshoot them. For more information, see How do I troubleshoot Amazon SQS DLQ redrive issues? in the AWS Knowledge Center Guide. DLQ issues Learn about common DLQ
sqs-dg-151
sqs-dg.pdf
151
delete the message within the Amazon SQS queue visibility timeout period. For additional information on how to troubleshoot a ReceiptHandle error, see How do I troubleshoot "ReceiptHandleIsInvalid" and "InvalidParameterValue" errors when I use the Amazon SQS DeleteMessage API call? in the AWS Knowledge Center Guide. Troubleshoot Amazon SQS dead-letter queue and DLQ redrive issues The following topics cover the most common causes of Amazon SQS DLQ and DLQ redrive issues, and how to troubleshoot them. For more information, see How do I troubleshoot Amazon SQS DLQ redrive issues? in the AWS Knowledge Center Guide. DLQ issues Learn about common DLQ issues and how to solve them. Viewing messages using the console might cause messages to be moved to a dead-letter queue Amazon SQS counts viewing a message in the console against the corresponding queue's redrive policy. Therefore, if you view a message in the console the number of times specified in the corresponding queue's redrive policy, the message is moved to the corresponding queue's dead- letter queue. To adjust this behavior, you can do one of the following: • Increase the Maximum Receives setting for the corresponding queue's redrive policy. • Avoid viewing the corresponding queue's messages in the console. The NumberOfMessagesSent and NumberOfMessagesReceived for a dead- letter queue don't match If you send a message to a dead-letter queue manually, it is captured by the NumberOfMessagesSent metric. However, if a message is sent to a dead-letter queue as a result of a failed processing attempt, it isn't captured by this metric. Therefore, it's possible for the values of NumberOfMessagesSent and NumberOfMessagesReceived to be different. DLQ and DLQ redrive issues 598 Amazon Simple Queue Service Developer Guide Creating and configuring a dead-letter queue redrive Dead-letter queue redrive requires you to set appropriate permissions for Amazon SQS to receive messages from the dead-letter queue, and send messages to the destination queue. If you don't have the correct permissions, the dead-letter queue redrive task can fail. You can view the status of your message redrive task to remediate the issues, and try again. Standard and FIFO queue message failure handling Standard queues keep processing messages until the expiration of the retention period. This continuous processing minimizes chances of the queue being blocked by unconsumed messages. Having a large number of messages that the consumer repeatedly fails to delete can increase costs, and place extra load on the hardware. To keep costs down, move failed messages to the dead- letter queue. Standard queues also allow a high number of in-flight messages. If the majority of your messages can't be consumed, and aren't sent to a dead-letter queue, your rate of processing messages can slow down. To maintain the efficiency of your queue, make sure that your application correctly handles message processing. FIFO queues provide exactly-once processing by consuming messages in sequence from a message group. Therefore, although the consumer can continue to retrieve ordered messages from another message group, the first message group remains unavailable until the message blocking the queue is processed successfully or moved to a dead-letter queue. Additionally, FIFO queues allow a lower number of in-flight messages. To keep your FIFO queue from getting blocked by a message, make sure that your application correctly handles message processing. For more information, see Amazon SQS message quotas and Amazon SQS best practices. DLQ-redrive issues Learn about common DLQ-redrive issues and how to solve them. AccessDenied permission issue The AccessDenied error occurs when the DLQ redrive fails because the AWS Identity and Access Management (IAM) entity doesn't have the required permissions. DLQ-redrive issues 599 Amazon Simple Queue Service Example error message: Developer Guide Failed to create redrive task. Error code: AccessDenied - Queue Permissions to Redrive. The following API permissions are required to make DLQ redrive requests: To start a message redrive: • Dead-letter queue permissions: • sqs:StartMessageMoveTask • sqs:ReceiveMessage • sqs:DeleteMessage • sqs:GetQueueAttributes • kms:Decrypt – When either the dead-letter queue or the original source queue are encrypted. • Destination queue permissions: • sqs:SendMessage • kms:GenerateDataKey – When the destination queue is encrypted. • kms:Decrypt – When the destination queue is encrypted. To cancel an in-progress message redrive: • Dead-letter queue permissions: • sqs:CancelMessageMoveTask • sqs:ReceiveMessage • sqs:DeleteMessage • sqs:GetQueueAttributes • kms:Decrypt – When either the dead-letter queue or the original source queue are encrypted. To show a message move status: • Dead-letter queue permissions: DLQ-redrive issues • sqs:ListMessageMoveTasks 600 Amazon Simple Queue Service Developer Guide • sqs:GetQueueAttributes NonExistentQueue error The NonExistentQueue error occurs when the Amazon SQS source queue doesn't exist, or was deleted. Check and redrive to an Amazon SQS queue that is present. Example error message: Failed: AWS.SimpleQueueService.NonExistentQueue CouldNotDetermineMessageSource error The CouldNotDetermineMessageSource error occurs when you attempt to start a DLQ redrive with the following scenarios: • An Amazon SQS message sent directly to the DLQ with SendMessage API.
sqs-dg-152
sqs-dg.pdf
152
– When either the dead-letter queue or the original source queue are encrypted. To show a message move status: • Dead-letter queue permissions: DLQ-redrive issues • sqs:ListMessageMoveTasks 600 Amazon Simple Queue Service Developer Guide • sqs:GetQueueAttributes NonExistentQueue error The NonExistentQueue error occurs when the Amazon SQS source queue doesn't exist, or was deleted. Check and redrive to an Amazon SQS queue that is present. Example error message: Failed: AWS.SimpleQueueService.NonExistentQueue CouldNotDetermineMessageSource error The CouldNotDetermineMessageSource error occurs when you attempt to start a DLQ redrive with the following scenarios: • An Amazon SQS message sent directly to the DLQ with SendMessage API. • A message from the Amazon Simple Notification Service (Amazon SNS) topic or AWS Lambda function with the DLQ configured. To resolve this error, choose Redrive to a custom destination when you start the redrive. Then, enter the Amazon SQS queue ARN to move all messages from the DLQ to the destination queue. Example error message: Failed: CouldNotDetermineMessageSource Troubleshoot FIFO throttling issues in Amazon SQS By default, FIFO queues support 300 transactions per second, per API action for SendMessage, ReceiveMessage, and DeleteMessage. Requests over 300 TPS get the ThrottlingException error even if messages in the queue are available. To mitigate this, you can use following methods: • Enabling high throughput for FIFO queues in Amazon SQS. • Use the Amazon SQS API batch actions SendMessageBatch, DeleteMessageBatch, and ChangeMessageVisibilityBatch to increase the TPS limit of up to 3,000 messages per second per API action, and to reduce cost. For the ReceiveMessage API, set the FIFO throttling issues 601 Amazon Simple Queue Service Developer Guide MaxNumberofMessages parameter to receive up to ten messages per transaction. For more information, see Amazon SQS batch actions. • For FIFO queues with high throughput, follow the recommendations to optimize partition utilization. Send messages with the same message group IDs in batches. Delete messages, or change the message visibility timeout values in batches with receipt handles from the same ReceiveMessage API requests. • Increase the number of unique MessageGroupId values. This allows for an even distribution across FIFO queue partitions. For more information, see Using the Amazon SQS message group ID. For more information, see Why doesn't my Amazon SQS FIFO queue return all messages or messages in other message groups? in the AWS Knowledge Center Guide. Troubleshoot messages not returned for an Amazon SQS ReceiveMessage API call The following topics cover the most common causes why an Amazon SQS message may not be returned to consumers, and how to troubleshoot them. For more information, see Why can't I receive messages from my Amazon SQS queue? in the AWS Knowledge Center Guide. Empty queue To determine if a queue is empty, use long polling to call the ReceiveMessage API. You can also use the ApproximateNumberOfMessagesVisible, ApproximateNumberOfMessagesNotVisible, and ApproximateNumberOfMessagesDelayed CloudWatch metrics. If all the metric values are set to 0 for several minutes, the queue is considered empty. In flight limit reached If you use long polling and if the queue’s in flight limit (20000 for FIFO, 120000 for standard by default) is breached, Amazon SQS won't return error messages that exceed quota limits. Message delay If the Amazon SQS queue is configured as a delay queue, or the messages were sent with message timers, then the messages aren't visible until the delay time ends. To verify if a queue is configured Messages not returned for a ReceiveMessage API call 602 Amazon Simple Queue Service Developer Guide as a delay queue, use the GetQueueAttributes API DelaySeconds attribute, or from the queue console under Delivery delay. Check the ApproximateNumberOfMessagesDelayed CloudWatch metric to understand if any messages are delayed. Message is in flight If a different consumer has polled the message, the message will be in flight or invisible for the visibility timeout period. The additional polls might return an empty receive. Check the ApproximateNumberOfMessagesVisible CloudWatch metric to understand the number of messages that are available to be received. In the case of FIFO queues, if a message with the message group ID is in flight, then no more messages will be returned unless you delete the message, or it becomes visible. This is because message ordering is maintained at the message group level in a FIFO queue. Polling method If you are using short polling, (WaitTimeSeconds is 0) Amazon SQS samples a subset of its servers, and returns messages from only those servers. Therefore, you might not get the messages even if they are available for to be received. Subsequent poll requests will return the messages. If you are using long polling, Amazon SQS polls all the servers and sends a response after collecting at least one available message, and up to the maximum number that's specified. If the value for ReceiveMessage WaitTimeSeconds is too low, you might not receive all the available messages. Troubleshoot Amazon SQS network errors
sqs-dg-153
sqs-dg.pdf
153
If you are using short polling, (WaitTimeSeconds is 0) Amazon SQS samples a subset of its servers, and returns messages from only those servers. Therefore, you might not get the messages even if they are available for to be received. Subsequent poll requests will return the messages. If you are using long polling, Amazon SQS polls all the servers and sends a response after collecting at least one available message, and up to the maximum number that's specified. If the value for ReceiveMessage WaitTimeSeconds is too low, you might not receive all the available messages. Troubleshoot Amazon SQS network errors The following topics cover the most common causes for network issues in Amazon SQS, and how to troubleshoot them. ETIMEOUT error The ETIMEOUT error occurs when the client can't establish a TCP connection to an Amazon SQS endpoint. Troubleshooting: • Check the network connection Message is in flight 603 Amazon Simple Queue Service Developer Guide Test your network connection to Amazon SQS by running commands like telnet. Example: telnet sqs.us-east-1.amazonaws.com 443 • Check network settings • Make sure that your local firewall rules, routes, and access control lists (ACLs) allow traffic on the port that you use. • The security group outbound (egress) rules must allow traffic to the port 80 or 443. • The network ACL outbound (egress) rules must allow traffic to TCP port 80 or 443. • The network ACL inbound (ingress) rules must allow traffic on TCP ports 1024-65535. • Amazon Elastic Compute Cloud (Amazon EC2) instances that connect to the public internet must have internet connectivity. • Amazon Virtual Private Cloud (Amazon VPC) endpoints If you access Amazon SQS through an Amazon VPC endpoint, then the endpoints security group must allow inbound traffic to the clients security group on port 443. The network ACL associated with the subnet of the VPC endpoint must have this configuration: • The network ACL outbound (egress) rules must allow traffic on TCP ports 1024-65535 (ephemeral ports). • The network ACL inbound (ingress) rules must allow traffic on port 443. Also, the Amazon SQS VPC endpoint AWS Identity and Access Management (IAM) policy must allow access. The following example VPC endpoint policy specifies that the IAM user MyUser is allowed to send messages to the Amazon SQS queue MyQueue. Other actions, IAM users, and Amazon SQS resources are denied access through the VPC endpoint. { "Statement": [{ "Action": ["sqs:SendMessage"], "Effect": "Allow", "Resource": "arn:aws:sqs:us-east-2:123456789012:MyQueue", "Principal": { "AWS": "arn:aws:iam:123456789012:user/MyUser" } }] } ETIMEOUT error 604 Amazon Simple Queue Service Developer Guide UnknownHostException error The UnknownHostException error occurs when the host IP address couldn't be determined. Troubleshooting: Use the nslookup utility to return the IP address associated with the host name: • Windows and Linux OS nslookup sqs.<region>.amazonaws.com • AWS CLI or SDK for Python legacy endpoints: nslookup <region>.queue.amazonaws.com If you received an unsuccessful output, follow the instructions in How does DNS work and how do I troubleshoot partial or intermittent DNS failures? in the AWS Knowledge Center Guide. If you received a valid output, then it is likely to be an application-level issue. To resolve application-level issues, try the following methods: • Restart your application. • Confirm that your Java application doesn't have a bad DNS cache. If possible, configure your application to adhere to the DNS TTL. For more information, see Setting the JVM TTL for DNS name lookups. For additional information on how to troubleshoot network errors, see How do I troubleshoot Amazon SQS “ETIMEOUT” and “UnknownHostException” connection errors? in the AWS Knowledge Center Guide. Troubleshooting Amazon Simple Queue Service queues 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 UnknownHostException error 605 Amazon Simple Queue Service Developer Guide your application makes to downstream AWS resources, microservices, databases and HTTP web APIs. To send AWS X-Ray trace headers through Amazon SQS, you can do one of the following: • Use the X-Amzn-Trace-Id tracing header. • Use the AWSTraceHeader message system attribute. To collect data on errors and latency, you must instrument the AmazonSQS client using the AWS X- Ray SDK. You can use the AWS X-Ray console to view the map of connections between Amazon SQS 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 SQS and AWS X-Ray in the AWS X-Ray Developer Guide. Troubleshooting queues using X-Ray 606 Amazon Simple Queue Service Developer Guide Security in Amazon SQS This section provides information about Amazon SQS security, authentication and access control, and the Amazon SQS Access Policy Language. Topics •
sqs-dg-154
sqs-dg.pdf
154
instrument the AmazonSQS client using the AWS X- Ray SDK. You can use the AWS X-Ray console to view the map of connections between Amazon SQS 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 SQS and AWS X-Ray in the AWS X-Ray Developer Guide. Troubleshooting queues using X-Ray 606 Amazon Simple Queue Service Developer Guide Security in Amazon SQS This section provides information about Amazon SQS security, authentication and access control, and the Amazon SQS Access Policy Language. Topics • Data protection in Amazon SQS • Identity and access management in Amazon SQS • Logging and monitoring in Amazon SQS • Compliance validation for Amazon SQS • Resilience in Amazon SQS • Infrastructure security in Amazon SQS • Amazon SQS security best practices Data protection in Amazon SQS The AWS shared responsibility model applies to data protection in Amazon Simple Queue 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. You are also responsible for 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 users with AWS IAM Identity Center or 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 require TLS 1.2 and recommend TLS 1.3. • Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see Working with CloudTrail trails in the AWS CloudTrail User Guide. • Use AWS encryption solutions, along with all default security controls within AWS services. Data protection 607 Amazon Simple Queue Service Developer Guide • Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3. • If you require FIPS 140-3 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-3. We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a Name field. This includes when you work with Amazon SQS or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text 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. The following sections provide information about data protection in Amazon SQS. Data encryption in Amazon SQS Data protection refers to protecting data while in-transit (as it travels to and from Amazon SQS) and at rest (while it is stored on disks in Amazon SQS data centers). You can protect data in transit using Secure Sockets Layer (SSL) or client-side encryption. By default, Amazon SQS stores messages and files using disk encryption. You can protect data at rest by requesting Amazon SQS to encrypt your messages before saving them to the encrypted file system in its data centers. Amazon SQS recommends using SSE for optimized data encryption. Topics • Encryption at rest in Amazon SQS • Amazon SQS Key management Encryption at rest in Amazon SQS Server-side encryption (SSE) lets you transmit sensitive data in encrypted queues. SSE protects the contents of messages in queues using SQS-managed encryption keys (SSE-SQS) or keys managed in the AWS Key Management Service (SSE-KMS). For information about managing SSE using the AWS Management Console, see the following: • Configuring SSE-SQS for a queue (console) • Configuring SSE-KMS for a queue (console) Data encryption 608 Amazon Simple Queue Service Developer Guide For information about managing SSE using the AWS SDK for Java (and the CreateQueue, SetQueueAttributes, and GetQueueAttributes actions), see the following examples: • Using server-side encryption with Amazon SQS queues • Configuring KMS permissions for AWS services SSE encrypts messages as soon as Amazon SQS receives them. The messages are stored in encrypted form and Amazon SQS decrypts messages
sqs-dg-155
sqs-dg.pdf
155
AWS Key Management Service (SSE-KMS). For information about managing SSE using the AWS Management Console, see the following: • Configuring SSE-SQS for a queue (console) • Configuring SSE-KMS for a queue (console) Data encryption 608 Amazon Simple Queue Service Developer Guide For information about managing SSE using the AWS SDK for Java (and the CreateQueue, SetQueueAttributes, and GetQueueAttributes actions), see the following examples: • Using server-side encryption with Amazon SQS queues • Configuring KMS permissions for AWS services SSE encrypts messages as soon as Amazon SQS receives them. The messages are stored in encrypted form and Amazon SQS decrypts messages only when they are sent to an authorized consumer. Important All requests to queues with SSE enabled must use HTTPS and Signature Version 4. An encrypted queue that uses the default key (AWS managed KMS key for Amazon SQS) cannot invoke a Lambda function in a different AWS account. Some features of AWS services that can send notifications to Amazon SQS using the AWS Security Token Service AssumeRole action are compatible with SSE but work only with standard queues: • Auto Scaling Lifecycle Hooks • AWS Lambda Dead-Letter Queues For information about compatibility of other services with encrypted queues, see Configure KMS permissions for AWS services and your service documentation. AWS KMS combines secure, highly available hardware and software to provide a key management system scaled for the cloud. When you use Amazon SQS 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 AWS KMS keys yourself. • You can also use the AWS managed KMS key for Amazon SQS, which is unique for each account and region. Data encryption 609 Amazon Simple Queue Service Developer Guide • 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 SQS queue. SSE doesn't encrypt the following: • Queue metadata (queue name and attributes) • Message metadata (message ID, timestamp, and attributes) • Per-queue metrics Encrypting a message makes its contents unavailable to unauthorized or anonymous users. With SSE enabled, anonymous SendMessage and ReceiveMessage requests to the encrypted queue will be rejected. Amazon SQS security best practices recommends against using anonymous requests. If you wish to send anonymous requests to an Amazon SQS queue, make sure you disable SSE. This doesn't affect the normal functioning of Amazon SQS: • A message is encrypted only if it is sent after the encryption of a queue is enabled. Amazon SQS doesn't encrypt backlogged messages. • Any encrypted message remains encrypted even if the encryption of its queue is disabled. Moving a message to a dead-letter queue doesn't affect its encryption: • When Amazon SQS moves a message from an encrypted source queue to an unencrypted dead- letter queue, the message remains encrypted. • When Amazon SQS moves a message from an unencrypted source queue to an encrypted dead- letter queue, the message remains unencrypted. Key terms The following key terms can help you better understand the functionality of SSE. For detailed descriptions, see the Amazon Simple Queue Service API Reference. Data encryption 610 Amazon Simple Queue Service Data key Developer Guide The key (DEK) responsible for encrypting the contents of Amazon SQS messages. For more information, see Data Keys in the AWS Key Management Service Developer Guide in the AWS Encryption SDK Developer Guide. Data key reuse period The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). The default is 300 (5 minutes). For more information, see Understanding the data key reuse period. Note In the unlikely event of being unable to reach AWS KMS, Amazon SQS continues to use the cached data key until a connection is reestablished. KMS key ID The alias, alias ARN, key ID, or key ARN of an AWS managed KMS key or a custom KMS key —in your account or in another account. While the alias of the AWS managed KMS key for Amazon SQS is always alias/aws/sqs, the alias of a custom KMS key can, for example, be alias/MyAlias. You can use these KMS keys to protect the messages in Amazon SQS queues. Note Keep the following in mind: • If you don't specify a custom KMS key, Amazon SQS uses the AWS managed KMS key for Amazon SQS. • The first time you use the AWS Management Console to specify the AWS managed KMS key for Amazon SQS
sqs-dg-156
sqs-dg.pdf
156
key or a custom KMS key —in your account or in another account. While the alias of the AWS managed KMS key for Amazon SQS is always alias/aws/sqs, the alias of a custom KMS key can, for example, be alias/MyAlias. You can use these KMS keys to protect the messages in Amazon SQS queues. Note Keep the following in mind: • If you don't specify a custom KMS key, Amazon SQS uses the AWS managed KMS key for Amazon SQS. • The first time you use the AWS Management Console to specify the AWS managed KMS key for Amazon SQS for a queue, AWS KMS creates the AWS managed KMS key for Amazon SQS. • Alternatively, the first time you use the SendMessage or SendMessageBatch action on a queue with SSE enabled, AWS KMS creates the AWS managed KMS key for Amazon SQS. Data encryption 611 Amazon Simple Queue Service Developer Guide You can create KMS keys, define the policies that control how KMS keys can be used, and audit KMS key usage using the Customer managed keys section of the AWS KMS console or the CreateKey AWS KMS action. For more information, see KMS keys and Creating Keys in the AWS Key Management Service Developer Guide. For more examples of KMS key identifiers, see KeyId in the AWS Key Management Service API Reference. For information about finding KMS key 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. Envelope Encryption The security of your encrypted data depends in part on protecting the data key that can decrypt it. Amazon SQS uses the KMS key to encrypt the data key and then the encrypted data key is stored with the encrypted message. This practice of using a KMS key to encrypt data keys is known as envelope encryption. For more information, see Envelope Encryption in the AWS Encryption SDK Developer Guide. Amazon SQS Key management Amazon SQS integrates with the AWS Key Management Service (KMS) to manage KMS keys for server-side encryption (SSE). See Encryption at rest in Amazon SQS for SSE information and key management definitions. Amazon SQS uses KMS keys to validate and secure the data keys that encrypt and decrypt the messages. The following sections provide information about working with KMS keys and data keys in the Amazon SQS service. Configuring AWS KMS permissions Every KMS key must have a key policy. Note that you cannot modify the key policy of an AWS managed KMS key for Amazon SQS. The policy for this KMS key includes permissions for all principals in the account (that are authorized to use Amazon SQS) to use encrypted queues. For a customer managed KMS key, you must configure the key policy to add permissions for each queue producer and consumer. To do this, you name the producer and consumer as users in the KMS key policy. For more information about AWS KMS permissions, see AWS KMS resources and Data encryption 612 Amazon Simple Queue Service Developer Guide operations or AWS KMS API permissions reference in the AWS Key Management Service Developer Guide. Alternatively, you can specify the required permissions in an IAM policy assigned to the principals that produce and consume encrypted messages. For more information, see Using IAM Policies with AWS KMS in the AWS Key Management Service Developer Guide. Note While you can configure global permissions to send to and receive from Amazon SQS, AWS KMS requires explicitly naming the full ARN of KMS keys in specific regions in the Resource section of an IAM policy. Configure KMS permissions for AWS services Several AWS services act as event sources that can send events to Amazon SQS queues. To allow these event sources to work with encrypted queues, you must create a customer managed KMS key and add permissions in the key policy for the service to use the required AWS KMS API methods. Perform the following steps to configure the permissions. Warning When changing the KMS key for encrypting your Amazon SQS messages, be aware that existing messages encrypted with the old KMS key will remain encrypted with that key. To decrypt these messages, you must retain the old KMS key and ensure that its key policy grants Amazon SQS the permissions for kms:Decrypt and kms:GenerateDataKey. After updating to a new KMS key for encrypting new messages, ensure all existing messages encrypted with the old KMS key are processed and removed from the queue before deleting or disabling the old KMS key. 1. Create a customer managed KMS key. For more information, see Creating Keys in the AWS Key Management Service Developer Guide. 2. To allow the AWS service event
sqs-dg-157
sqs-dg.pdf
157
the old KMS key will remain encrypted with that key. To decrypt these messages, you must retain the old KMS key and ensure that its key policy grants Amazon SQS the permissions for kms:Decrypt and kms:GenerateDataKey. After updating to a new KMS key for encrypting new messages, ensure all existing messages encrypted with the old KMS key are processed and removed from the queue before deleting or disabling the old KMS key. 1. Create a customer managed KMS key. For more information, see Creating Keys in the AWS Key Management Service Developer Guide. 2. To allow the AWS service event source to use the kms:Decrypt and kms:GenerateDataKey API methods, add the following statement to the KMS key policy. { "Version": "2012-10-17", Data encryption 613 Amazon Simple Queue Service Developer Guide "Statement": [{ "Effect": "Allow", "Principal": { "Service": "service.amazonaws.com" }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "*" }] } Replace "service" in the above example with the Service name of the event source. Event sources include the following services. Event source Service name Amazon CloudWatch Events events.amazonaws.com Amazon S3 event notifications s3.amazonaws.com Amazon SNS topic subscriptions sns.amazonaws.com 3. Configure an existing SSE queue using the ARN of your KMS key. 4. Provide the ARN of the encrypted queue to the event source. Configure AWS KMS permissions for producers When the data key reuse period expires, the producer's next call to SendMessage or SendMessageBatch also triggers calls to kms:Decrypt and kms:GenerateDataKey. The call to kms:Decrypt is to verify the integrity of the new data key before using it. Therefore, the producer must have the kms:Decrypt and kms:GenerateDataKey permissions for the KMS key. Add the following statement to the IAM policy of the producer. Remember to use the correct ARN values for the key resource and the queue resource. { "Version": "2012-10-17", "Statement": [{ Data encryption 614 Amazon Simple Queue Service Developer Guide "Effect": "Allow", "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "arn:aws:kms:us- east-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" }, { "Effect": "Allow", "Action": [ "sqs:SendMessage" ], "Resource": "arn:aws:sqs:*:123456789012:MyQueue" }] } Configure AWS KMS permissions for consumers When the data key reuse period expires, the consumer's next call to ReceiveMessage also triggers a call to kms:Decrypt, to verify the integrity of the new data key before using it. Therefore, the consumer must have the kms:Decrypt permission for any KMS key that is used to encrypt the messages in the specified queue. If the queue acts as a dead-letter queue, the consumer must also have the kms:Decrypt permission for any KMS key that is used to encrypt the messages in the source queue. Add the following statement to the IAM policy of the consumer. Remember to use the correct ARN values for the key resource and the queue resource. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "kms:Decrypt" ], "Resource": "arn:aws:kms:us- east-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" }, { "Effect": "Allow", "Action": [ "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:*:123456789012:MyQueue" }] Data encryption 615 Amazon Simple Queue Service } Developer Guide Configure AWS KMS permissions with confused deputy protection When the principal in a key policy statement is an AWS service principal, you can use the aws:SourceArn or aws:SourceAccount global condition keys to protect against the confused deputy scenario. To use these condition keys, set the value to the Amazon Resource Name (ARN) of the resource that is being encrypted. If you don't know the ARN of the resource, use aws:SourceAccount instead. In this KMS key policy, a specific resource from service that is owned by account 111122223333 is allowed to call KMS for Decrypt and GenerateDataKey actions, which occur during SSE usage of Amazon SQS. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": "<replaceable>service</replaceable>.amazonaws.com" }, "Action": [ "kms:GenerateDataKey", "kms:Decrypt" ], "Resource": "*", "Condition": { "ArnEquals": { "aws:SourceArn": [ "arn:aws:service::111122223333:resource" ] } } }] } When using SSE enabled Amazon SQS queues, the following services support aws:SourceArn: • Amazon SNS • Amazon S3 • CloudWatch Events Data encryption 616 Amazon Simple Queue Service • AWS Lambda • CodeBuild • Amazon Connect Customer Profiles • AWS Auto Scaling • Amazon Chime Understanding the data key reuse period Developer Guide The data key reuse period defines the maximum duration for Amazon SQS to reuse the same data key. When the data key reuse period ends, Amazon SQS generates a new data key. Note the following guidelines about the reuse period. • A shorter reuse period provides better security but results in more calls to AWS KMS, which might incur charges beyond the Free Tier. • Although the data key is cached separately for encryption and for decryption, the reuse period applies to both copies of the data key. • When the data key reuse period ends, the next call to SendMessage or SendMessageBatch typically triggers a call to the AWS KMS GenerateDataKey method to get a new data key. Also, the next calls to SendMessage and ReceiveMessage
sqs-dg-158
sqs-dg.pdf
158
generates a new data key. Note the following guidelines about the reuse period. • A shorter reuse period provides better security but results in more calls to AWS KMS, which might incur charges beyond the Free Tier. • Although the data key is cached separately for encryption and for decryption, the reuse period applies to both copies of the data key. • When the data key reuse period ends, the next call to SendMessage or SendMessageBatch typically triggers a call to the AWS KMS GenerateDataKey method to get a new data key. Also, the next calls to SendMessage and ReceiveMessage will each trigger a call to AWS KMS Decrypt to verify the integrity of the data key before using it. • Principals (AWS accounts or users) don't share data keys (messages sent by unique principals always get unique data keys). Therefore, the volume of calls to AWS KMS is a multiple of the number of unique principals in use during the data key reuse period. Estimating AWS KMS costs To predict costs and better understand your AWS bill, you might want to know how often Amazon SQS uses your 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 SQS. To calculate the number of API requests (R) per queue, use the following formula: Data encryption 617 Amazon Simple Queue Service Developer Guide R = (B / D) * (2 * P + C) B is the billing period (in seconds). D is the data key reuse period (in seconds). P is the number of producing principals that send to the Amazon SQS queue. C is the number of consuming principals that receive from the Amazon SQS queue. Important In general, producing principals incur double the cost of consuming principals. For more information, see Understanding the data key reuse period. If the producer and consumer have different users, the cost increases. 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 2 principals and 1 queue This example assumes the following: • The billing period is January 1-31 (2,678,400 seconds). • The data key reuse period is set to 5 minutes (300 seconds). • There is 1 queue. • There is 1 producing principal and 1 consuming principal. (2,678,400 / 300) * (2 * 1 + 1) = 26,784 Example 2: Calculating the number of AWS KMS API calls for multiple producers and consumers and 2 queues This example assumes the following: • The billing period is February 1-28 (2,419,200 seconds). • The data key reuse period is set to 24 hours (86,400 seconds). • There are 2 queues. Data encryption 618 Amazon Simple Queue Service Developer Guide • The first queue has 3 producing principals and 1 consuming principal. • The second queue has 5 producing principals and 2 consuming principals. (2,419,200 / 86,400 * (2 * 3 + 1)) + (2,419,200 / 86,400 * (2 * 5 + 2)) = 532 AWS KMS errors When you work with Amazon SQS and AWS KMS, you might encounter errors. The following references describe the errors and possible troubleshooting solutions. • Common AWS KMS errors • AWS KMS Decrypt errors • AWS KMS GenerateDataKey errors Internetwork traffic privacy in Amazon SQS An Amazon Virtual Private Cloud (Amazon VPC) endpoint for Amazon SQS is a logical entity within a VPC that allows connectivity only to Amazon SQS. The VPC routes requests to Amazon SQS and routes responses back to the VPC. The following sections provide information about working with VPC endpoints and creating VPC endpoint policies. Amazon Virtual Private Cloud endpoints for Amazon SQS If you use Amazon VPC to host your AWS resources, you can establish a connection between your VPC and Amazon SQS. You can use this connection to send messages to your Amazon SQS queues without crossing the public internet. Amazon VPC lets you launch AWS resources in a custom virtual network. You can use a VPC to control your network settings, such as the IP address range, subnets, route tables, and network gateways. For more information about VPCs, see the Amazon VPC User Guide. To connect your VPC to Amazon SQS, you must first define an interface VPC endpoint, which lets you connect your VPC to other AWS services. The endpoint provides reliable, scalable connectivity to Amazon SQS without requiring an internet gateway, network address translation (NAT) instance, or VPN connection. For more information, see Tutorial: Sending a message to an Amazon SQS queue from Amazon Virtual Private Cloud and Example 5: Deny access if it isn't from a VPC endpoint in this guide and Interface VPC Endpoints (AWS PrivateLink) in the Amazon
sqs-dg-159
sqs-dg.pdf
159
For more information about VPCs, see the Amazon VPC User Guide. To connect your VPC to Amazon SQS, you must first define an interface VPC endpoint, which lets you connect your VPC to other AWS services. The endpoint provides reliable, scalable connectivity to Amazon SQS without requiring an internet gateway, network address translation (NAT) instance, or VPN connection. For more information, see Tutorial: Sending a message to an Amazon SQS queue from Amazon Virtual Private Cloud and Example 5: Deny access if it isn't from a VPC endpoint in this guide and Interface VPC Endpoints (AWS PrivateLink) in the Amazon VPC User Guide. Internetwork traffic privacy 619 Amazon Simple Queue Service Developer Guide Important • You can use Amazon Virtual Private Cloud only with HTTPS Amazon SQS endpoints. • When you configure Amazon SQS to send messages from Amazon VPC, you must enable private DNS and specify endpoints in the format sqs.us-east-2.amazonaws.com or sqs.us-east-2.api.aws for the dual-stack endpoint. • Amazon SQS also supports FIPS endpoints through PrivateLink using the com.amazonaws.region.sqs-fips endpoint service. You can connect to FIPS endpoints in the format sqs-fips.region.amazonaws.com. • When using the dual-stack endpoint in Amazon Virtual Private Cloud, requests will be sent using IPv4 and IPv6. • Private DNS doesn't support legacy endpoints such as queue.amazonaws.com or us- east-2.queue.amazonaws.com. Creating an Amazon VPC endpoint policy for Amazon SQS You can create a policy for Amazon VPC endpoints for Amazon SQS 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 user MyUser is allowed to send messages to the Amazon SQS queue MyQueue. { "Statement": [{ "Action": ["sqs:SendMessage"], "Effect": "Allow", "Resource": "arn:aws:sqs:us-east-2:123456789012:MyQueue", "Principal": { "AWS": "arn:aws:iam:123456789012:user/MyUser" Internetwork traffic privacy 620 Amazon Simple Queue Service Developer Guide } }] } The following are denied: • Other Amazon SQS API actions, such as sqs:CreateQueue and sqs:DeleteQueue. • Other users and rules which attempt to use this VPC endpoint. • MyUser sending messages to a different Amazon SQS queue. Note The user can still use other Amazon SQS API actions from outside the VPC. For more information, see Example 5: Deny access if it isn't from a VPC endpoint. Identity and access management in Amazon SQS 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 SQS 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 SQS. Service user – If you use the Amazon SQS service to do your job, then your administrator provides you with the credentials and permissions that you need. As you use more Amazon SQS 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 SQS, see Troubleshooting Amazon Simple Queue Service identity and access. Service administrator – If you're in charge of Amazon SQS resources at your company, you probably have full access to Amazon SQS. It's your job to determine which Amazon SQS 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 Identity and access management 621 Amazon Simple Queue Service Developer Guide to understand the basic concepts of IAM. To learn more about how your company can use IAM with Amazon SQS, see How Amazon Simple Queue Service 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 SQS. To view example Amazon SQS identity-based policies that you can use in IAM, see Policy best practices. 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
sqs-dg-160
sqs-dg.pdf
160
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. Authenticating with identities 622 Amazon Simple Queue Service Developer Guide 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. Federated identity 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. Authenticating with identities 623 Amazon Simple Queue Service IAM roles Developer Guide 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
sqs-dg-161
sqs-dg.pdf
161
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. Authenticating with identities 623 Amazon Simple Queue Service IAM roles Developer Guide 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 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 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. Authenticating with identities 624 Amazon Simple Queue Service Developer Guide • 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. • 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
sqs-dg-162
sqs-dg.pdf
162
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. Managing access using policies 625 Amazon Simple Queue Service Identity-based policies Developer Guide 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. 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 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. Managing access using policies 626 Amazon Simple Queue Service Other policy types Developer Guide 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
sqs-dg-163
sqs-dg.pdf
163
• 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 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. Managing access using policies 627 Amazon Simple Queue Service Multiple policy types Developer Guide 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. Overview of managing access in Amazon SQS Every AWS resource is owned by an AWS account, and permissions to create or access a resource are governed by permissions policies. An account administrator can attach permissions policies to IAM identities (users, groups, and roles), and some services (such as Amazon SQS) also support attaching permissions policies to resources. Note An account administrator (or administrator user) is a user with administrative privileges. For more information, see IAM Best Practices in the IAM User Guide. When granting permissions, you specify what users get permissions, the resource they get permissions for, and the specific actions that you want to allow on the resource. Amazon Simple Queue Service resource and operations In Amazon SQS, the only resource is the queue. In a policy, use an Amazon Resource Name (ARN) to identify the resource that the policy applies to. The following resource has a unique ARN associated with it: Resource type Queue ARN format arn:aws:sqs: region:account_i d :queue_name The following are examples of the ARN format for queues: • An ARN for a queue named my_queue in the US East (Ohio) region, belonging to AWS Account 123456789012: Overview 628 Amazon Simple Queue Service Developer Guide arn:aws:sqs:us-east-2:123456789012:my_queue • An ARN for a queue named my_queue in each of the different regions that Amazon SQS supports: arn:aws:sqs:*:123456789012:my_queue • An ARN that uses * or ? as a wildcard for the queue name. In the following examples, the ARN matches all queues prefixed with my_prefix_: arn:aws:sqs:*:123456789012:my_prefix_* You can get the ARN value for an existing queue by calling the GetQueueAttributes action. The value of the QueueArn attribute is the ARN of the queue. For more information about ARNs, see IAM ARNs in the IAM User Guide. Amazon SQS provides a set of actions that work with the queue resource. For more information, see Amazon SQS API permissions: Actions and resource reference. Understanding resource ownership The AWS account owns the resources that are created in the account, regardless of who created the resources. Specifically, the resource owner is the AWS account of the principal entity (that is, the root account, a user , or an IAM role) that authenticates the resource creation request. The following examples illustrate how this works: • If you
sqs-dg-164
sqs-dg.pdf
164
queue. For more information about ARNs, see IAM ARNs in the IAM User Guide. Amazon SQS provides a set of actions that work with the queue resource. For more information, see Amazon SQS API permissions: Actions and resource reference. Understanding resource ownership The AWS account owns the resources that are created in the account, regardless of who created the resources. Specifically, the resource owner is the AWS account of the principal entity (that is, the root account, a user , or an IAM role) that authenticates the resource creation request. The following examples illustrate how this works: • If you use the root account credentials of your AWS account to create an Amazon SQS queue, your AWS account is the owner of the resource (in Amazon SQS, the resource is the Amazon SQS queue). • If you create a user in your AWS account and grant permissions to create a queue to the user, the user can create the queue. However, your AWS account (to which the user belongs) owns the queue resource. • If you create an IAM role in your AWS account with permissions to create an Amazon SQS queue, anyone who can assume the role can create a queue. Your AWS account (to which the role belongs) owns the queue resource. Overview 629 Amazon Simple Queue Service Developer Guide Managing access to resources A permissions policy describes the permissions granted to accounts. The following section explains the available options for creating permissions policies. Note This section discusses using IAM in the context of Amazon SQS. It doesn't provide detailed information about the IAM service. For complete IAM documentation, see What is IAM? in the IAM User Guide. For information about IAM policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User Guide. Policies attached to an IAM identity are referred to as identity-based policies (IAM policies) and policies attached to a resource are referred to as resource-based policies. Identity-based policies There are two ways to give your users permissions to your Amazon SQS queues: using the Amazon SQS policy system and using the IAM policy system. You can use either system, or both, to attach policies to users or roles. In most cases, you can achieve the same result using either system. For example, you can do the following: • Attach a permission policy to a user or a group in your account – To grant user permissions to create an Amazon SQS queue, attach a permissions policy to a user or group that the user belongs to. • Attach a permission policy to a user in another AWS account – You can attach a permissions policy to a user in another AWS account to allow them to interact with an Amazon SQS queue. However, cross-account permissions do not apply to the following actions: Cross-account permissions don't apply to the following actions: • AddPermission • CancelMessageMoveTask • CreateQueue • DeleteQueue • ListMessageMoveTask • ListQueues Overview 630 Amazon Simple Queue Service • ListQueueTags • RemovePermission • SetQueueAttributes • StartMessageMoveTask • TagQueue • UntagQueue Developer Guide To grant access for these actions, the user must belong to the same AWS account that owns the Amazon SQS queue. • Attach a permission policy to a role (grant cross-account permissions) – To grant cross- account permissions to an SQS queue, you must combine both IAM and resource-based policies: 1. In Account A (which owns the queue): • Attach a resource-based policy to the SQS queue. This policy must explicitly grant the necessary permissions (for example, SendMessage, ReceiveMessage) to the principal in Account B (such as an IAM role). 2. In Account A, create an IAM role: • A trust policy that allows Account B or an AWS service to assume the role. Note If you want an AWS service (such as Lambda or EventBridge) to assume the role, specify the service principal (for example, lambda.amazonaws.com) in the trust policy. • An identity-based policy that grants the assumed role permissions to interact with the queue. 3. In Account B, grant permission to assume the role in Account A. You must configure the queue’s access policy to allow the cross-account principal. IAM identity- based policies alone aren't sufficient for cross-account access to SQS queues. For more information about using IAM to delegate permissions, see Access Management in the IAM User Guide. Overview 631 Amazon Simple Queue Service Developer Guide While Amazon SQS works with IAM policies, it has its own policy infrastructure. You can use an Amazon SQS policy with a queue to specify which AWS Accounts have access to the queue. You can specify the type of access and conditions (for example, a condition that grants permissions to use SendMessage, ReceiveMessage if the request is made before December 31, 2010). The specific actions you can grant permissions for are
sqs-dg-165
sqs-dg.pdf
165
access to SQS queues. For more information about using IAM to delegate permissions, see Access Management in the IAM User Guide. Overview 631 Amazon Simple Queue Service Developer Guide While Amazon SQS works with IAM policies, it has its own policy infrastructure. You can use an Amazon SQS policy with a queue to specify which AWS Accounts have access to the queue. You can specify the type of access and conditions (for example, a condition that grants permissions to use SendMessage, ReceiveMessage if the request is made before December 31, 2010). The specific actions you can grant permissions for are a subset of the overall list of Amazon SQS actions. When you write an Amazon SQS policy and specify * to "allow all Amazon SQS actions," it means that a user can perform all actions in this subset. The following diagram illustrates the concept of one of these basic Amazon SQS policies that covers the subset of actions. The policy is for queue_xyz, and it gives AWS Account 1 and AWS Account 2 permissions to use any of the allowed actions with the specified queue. Note The resource in the policy is specified as 123456789012/queue_xyz, where 123456789012 is the AWS Account ID of the account that owns the queue. With the introduction of IAM and the concepts of Users and Amazon Resource Names (ARNs), a few things have changed about SQS policies. The following diagram and table describe the changes. Overview 632 Amazon Simple Queue Service Developer Guide For information about giving permissions to users in different accounts, see Tutorial: Delegate Access Across AWS Accounts Using IAM Roles in the IAM User Guide. The subset of actions included in * has expanded. For a list of allowed actions, see Amazon SQS API permissions: Actions and resource reference. You can specify the resource using the Amazon Resource Name (ARN), the standard means of specifying resources in IAM policies. For information about the ARN format for Amazon SQS queues, see Amazon Simple Queue Service resource and operations. For example, according to the Amazon SQS policy in the preceding diagram, anyone who possesses the security credentials for AWS Account 1 or AWS Account 2 can access queue_xyz. In addition, Users Bob and Susan in your own AWS Account (with ID 123456789012) can access the queue. Before the introduction of IAM, Amazon SQS automatically gave the creator of a queue full control over the queue (that is, access to all of the possible Amazon SQS actions on that queue). This is no longer true, unless the creator uses AWS security credentials. Any user who has permissions to create a queue must also have permissions to use other Amazon SQS actions in order to do anything with the created queues. The following is an example policy that allows a user to use all Amazon SQS actions, but only with queues whose names are prefixed with the literal string bob_queue_. Overview 633 Amazon Simple Queue Service Developer Guide { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "sqs:*", "Resource": "arn:aws:sqs:*:123456789012:bob_queue_*" }] } For more information, see Using policies with Amazon SQS, and Identities (Users, Groups, and Roles) in the IAM User Guide. Specifying policy elements: Actions, effects, resources, and principals For each Amazon Simple Queue Service resource, the service defines a set of actions. To grant permissions for these actions, Amazon SQS defines a set of actions that you can specify in a policy. Note Performing an action can require permissions for more than one action. When granting permissions for specific actions, you also identify the resource for which the actions are allowed or denied. The following are the most basic policy elements: • Resource – In a policy, you use an Amazon Resource Name (ARN) to identify the resource to which the policy applies. • Action – You use action keywords to identify resource actions that you want to allow or deny. For example, the sqs:CreateQueue permission allows the user to perform the Amazon Simple Queue Service CreateQueue action. • Effect – You specify the effect when the user requests the specific action—this can be either allow or deny. If you don't explicitly grant access to a resource, access is implicitly denied. You can also explicitly deny access to a resource, which you might do to make sure that a user can't access it, even if a different policy grants access. • Principal – In identity-based policies (IAM policies), the user that the policy is attached to is the implicit principal. For resource-based policies, you specify the user, account, service, or other entity that you want to receive permissions (applies to resource-based policies only). Overview 634 Amazon Simple Queue Service Developer Guide To learn more about Amazon SQS policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User Guide. For a table of
sqs-dg-166
sqs-dg.pdf
166
deny access to a resource, which you might do to make sure that a user can't access it, even if a different policy grants access. • Principal – In identity-based policies (IAM policies), the user that the policy is attached to is the implicit principal. For resource-based policies, you specify the user, account, service, or other entity that you want to receive permissions (applies to resource-based policies only). Overview 634 Amazon Simple Queue Service Developer Guide To learn more about Amazon SQS policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User Guide. For a table of all Amazon Simple Queue Service actions and the resources that they apply to, see Amazon SQS API permissions: Actions and resource reference. How Amazon Simple Queue Service works with IAM Before you use IAM to manage access to Amazon SQS, learn what IAM features are available to use with Amazon SQS. IAM features you can use with Amazon Simple Queue Service IAM feature Amazon SQS 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 Temporary credentials Forward access sessions (FAS) Service roles Service-linked roles Yes Yes Yes No To get a high-level view of how Amazon SQS and other AWS services work with most IAM features, see AWS services that work with IAM in the IAM User Guide. How Amazon Simple Queue Service works with IAM 635 Amazon Simple Queue Service Access control Developer Guide 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. 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. See Limitations of Amazon SQS custom policies for further details on cross-content permissions and condition keys within Amazon SQS custom policies. Identity-based policies for Amazon SQS 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 SQS To view examples of Amazon SQS identity-based policies, see Policy best practices. How Amazon Simple Queue Service works with IAM 636 Amazon Simple Queue Service Developer Guide Resource-based policies within Amazon SQS 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. Policy actions for Amazon SQS Supports policy actions: Yes Administrators can use AWS JSON policies
sqs-dg-167
sqs-dg.pdf
167
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. Policy actions for Amazon SQS 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 SQS actions, see Resources Defined by Amazon Simple Queue Service in the Service Authorization Reference. How Amazon Simple Queue Service works with IAM 637 Amazon Simple Queue Service Developer Guide Policy actions in Amazon SQS use the following prefix before the action: sqs To specify multiple actions in a single statement, separate them with commas. "Action": [ "sqs:action1", "sqs:action2" ] To view examples of Amazon SQS identity-based policies, see Policy best practices. Policy resources for Amazon SQS 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 SQS resource types and their ARNs, see Actions Defined by Amazon Simple Queue 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 Queue Service. To view examples of Amazon SQS identity-based policies, see Policy best practices. How Amazon Simple Queue Service works with IAM 638 Amazon Simple Queue Service Developer Guide Policy condition keys for Amazon SQS 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. 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 SQS condition keys, see Condition Keys for Amazon Simple Queue 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 Queue Service. To view examples of Amazon SQS identity-based policies, see Policy best practices. ACLs in Amazon SQS 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 SQS Supports ABAC (tags in policies): Partial How Amazon Simple Queue
sqs-dg-168
sqs-dg.pdf
168
Condition Keys for Amazon Simple Queue 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 Queue Service. To view examples of Amazon SQS identity-based policies, see Policy best practices. ACLs in Amazon SQS 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 SQS Supports ABAC (tags in policies): Partial How Amazon Simple Queue Service works with IAM 639 Amazon Simple Queue Service Developer Guide 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. 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 SQS 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. How Amazon Simple Queue Service works with IAM 640 Amazon Simple Queue Service Developer Guide Forward access sessions for Amazon SQS 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 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 SQS 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 SQS functionality. Edit service roles only when Amazon SQS provides guidance to do so. Service-linked roles for Amazon SQS 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. How Amazon Simple Queue Service
sqs-dg-169
sqs-dg.pdf
169
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. How Amazon Simple Queue Service works with IAM 641 Amazon Simple Queue Service Developer Guide Amazon SQS updates to AWS managed policies To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write policies yourself. It takes time and expertise to create IAM customer managed policies that provide your team with only the permissions they need. To get started quickly, you can use our AWS managed policies. These policies cover common use cases and are available in your AWS account. For more information about AWS managed policies, see AWS managed policies in the IAM User Guide. AWS services maintain and update AWS managed policies. You can't change the permissions in AWS managed policies. Services occasionally add additional permissions to an AWS managed policy to support new features. This type of update affects all identities (users, groups, and roles) where the policy is attached. Services are most likely to update an AWS managed policy when a new feature is launched or when new operations become available. Services do not remove permissions from an AWS managed policy, so policy updates won't break your existing permissions. Additionally, AWS supports managed policies for job functions that span multiple services. For example, the ReadOnlyAccess AWS managed policy provides read-only access to all AWS services and resources. When a service launches a new feature, AWS adds read-only permissions for new operations and resources. For a list and descriptions of job function policies, see AWS managed policies for job functions in the IAM User Guide. AWS managed policy: AmazonSQSFullAccess You can attach the AmazonSQSFullAccess policy to your Amazon SQS identities. This policy grants permissions that allow full access to Amazon SQS. To view the permissions for this policy, see AmazonSQSFullAccess in the AWS Managed Policy Reference. AWS managed policy: AmazonSQSReadOnlyAccess You can attach the AmazonSQSReadOnlyAccess policy to your Amazon SQS identities. This policy grants permissions that allow read-only access to Amazon SQS. To view the permissions for this policy, see AmazonSQSReadOnlyAccess in the AWS Managed Policy Reference. AWS managed policies 642 Amazon Simple Queue Service Developer Guide AWS managed policy: SQSUnlockQueuePolicy If you incorrectly configured your queue policy for a member account to deny all users access to your Amazon SQS queue, you can use the SQSUnlockQueuePolicy AWS managed policy to unlock the queue. For more information on how to remove a misconfigured queue policy that denies all principals from accessing an Amazon SQS queue, see Perform a privileged task on an AWS Organizations member account in the IAM User Guide. Amazon SQS updates to AWS managed policies View details about updates to AWS managed policies for Amazon SQS since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Amazon SQS Document history page. Change Description Date November 15, 2024 SQSUnlockQueuePolicy Amazon SQS added a new AWS-managed policy called SQSUnlockQueuePolicy to unlock a queue and remov e a misconfigured queue policy that denies all principal s from accessing an Amazon SQS queue. AmazonSQSReadOnlyAccess Amazon SQS added the June 20, 2024 ListQueueTags action, which retrieves all tags associated with a specified Amazon SQS queue. It allows you to view the key-value pairs that have been assigned to the queue for organizat ional or metadata purposes. This action is associated with AWS managed policies 643 Amazon Simple Queue Service Developer Guide Change Description Date AmazonSQSReadOnlyAccess June 9, 2023 the ListQueueTags API operation. Amazon SQS added a new action that allows you to list the most recent message movement tasks (up to 10) under a specific source qu eue. This action is associate d with the ListMessa geMoveTasks API opera tion. Troubleshooting Amazon Simple Queue Service identity and access Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon SQS and IAM. I am not authorized to perform an action in Amazon SQS 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
sqs-dg-170
sqs-dg.pdf
170
the ListMessa geMoveTasks API opera tion. Troubleshooting Amazon Simple Queue Service identity and access Use the following information to help you diagnose and fix common issues that you might encounter when working with Amazon SQS and IAM. I am not authorized to perform an action in Amazon SQS 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 sqs:GetWidget permissions. User: arn:aws:iam::123456789012:user/mateojackson is not authorized to perform: sqs: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 sqs:GetWidget action. If you need help, contact your AWS administrator. Your administrator is the person who provided you with your sign-in credentials. Troubleshooting 644 Amazon Simple Queue Service Developer Guide 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 SQS. 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 SQS. 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 SQS 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 SQS supports these features, see How Amazon Simple Queue Service 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. Troubleshooting 645 Amazon Simple Queue 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. I want to unlock my queue If your AWS account belongs to an organization, AWS Organizations policies can block you from accessing Amazon SQS resources. By default, AWS Organizations policies don't block any requests to Amazon SQS. However, make sure that your AWS Organizations policies haven’t been configured to block access to Amazon SQS queues. For instructions on how to check your AWS Organizations policies, see Listing all policies in the AWS Organizations User Guide. Additionally, if you incorrectly configured your queue policy for a member account to deny all users access to your Amazon SQS queue, you can unlock the queue by launching a privileged session for the member account in IAM. Once you launch a privileged session, you can delete the misconfigured queue policy to regain access to the queue. For more information, see Perform a privileged task on an AWS Organizations member account in the IAM User Guide. Using policies with Amazon SQS This topic provides examples of identity-based policies in which an account administrator can attach permissions policies to IAM identities (users, groups, and roles). Important We recommend that you first review the introductory topics that explain the basic concepts and options available for you to manage access to your Amazon Simple Queue Service resources. For more information, see Overview of managing access in Amazon SQS. With the exception of ListQueues, all Amazon SQS actions support resource-level permissions. For more information, see Amazon SQS API permissions: Actions and resource reference. Using Amazon SQS and IAM policies There are two
sqs-dg-171
sqs-dg.pdf
171
with Amazon SQS This topic provides examples of identity-based policies in which an account administrator can attach permissions policies to IAM identities (users, groups, and roles). Important We recommend that you first review the introductory topics that explain the basic concepts and options available for you to manage access to your Amazon Simple Queue Service resources. For more information, see Overview of managing access in Amazon SQS. With the exception of ListQueues, all Amazon SQS actions support resource-level permissions. For more information, see Amazon SQS API permissions: Actions and resource reference. Using Amazon SQS and IAM policies There are two ways to give your users permissions to your Amazon SQS resources: using the Amazon SQS policy system (resource-based policies) and using the IAM policy system (identity- based policies). You can use one or both methods, with the exception of the ListQueues action, which is a regional permission that can only be set in an IAM policy. Using policies 646 Amazon Simple Queue Service Developer Guide For example, the following diagram shows an IAM policy and an Amazon SQS policy equivalent to it. The IAM policy grants the rights to the Amazon SQS ReceiveMessage and SendMessage actions for the queue called queue_xyz in your AWS Account, and the policy is attached to users named Bob and Susan (Bob and Susan have the permissions stated in the policy). This Amazon SQS policy also gives Bob and Susan rights to the ReceiveMessage and SendMessage actions for the same queue. Note The following example shows simple policies without conditions. You can specify a particular condition in either policy and get the same result. There is one major difference between IAM and Amazon SQS policies: the Amazon SQS policy system lets you grant permission to other AWS Accounts, whereas IAM doesn't. It is up to you how you use both of the systems together to manage your permissions. The following examples show how the two policy systems work together. • In the first example, Bob has both an IAM policy and an Amazon SQS policy that apply to his account. The IAM policy grants his account permission for the ReceiveMessage action on queue_xyz, whereas the Amazon SQS policy gives his account permission for the SendMessage action on the same queue. The following diagram illustrates the concept. Using policies 647 Amazon Simple Queue Service Developer Guide If Bob sends a ReceiveMessage request to queue_xyz, the IAM policy allows the action. If Bob sends a SendMessage request to queue_xyz, the Amazon SQS policy allows the action. • In the second example, Bob abuses his access to queue_xyz, so it becomes necessary to remove his entire access to the queue. The easiest thing to do is to add a policy that denies him access to all actions for the queue. This policy overrides the other two because an explicit deny always overrides an allow. For more information about policy evaluation logic, see Using custom policies with the Amazon SQS Access Policy Language. The following diagram illustrates the concept. Using policies 648 Amazon Simple Queue Service Developer Guide You can also add an additional statement to the Amazon SQS policy that denies Bob any type of access to the queue. It has the same effect as adding an IAM policy that denies Bob access to the queue. For examples of policies that cover Amazon SQS actions and resources, see Basic examples of Amazon SQS policies. For more information about writing Amazon SQS policies, see Using custom policies with the Amazon SQS Access Policy Language. Permissions required to use the Amazon SQS console A user who wants to work with the Amazon SQS console must have the minimum set of permissions to work with the Amazon SQS queues in the user's AWS account. For example, the user must have the permission to call the ListQueues action to be able to list queues, or the permission to call the CreateQueue action to be able to create queues. In addition to Amazon SQS permissions, to subscribe an Amazon SQS queue to an Amazon SNS topic, the console also requires permissions for Amazon SNS actions. If you create an IAM policy that is more restrictive than the minimum required permissions, the console might not function as intended for users with that IAM policy. You don't need to allow minimum console permissions for users that make calls only to the AWS CLI or Amazon SQS actions. Identity-based policy examples for Amazon SQS By default, users and roles don't have permission to create or modify Amazon SQS 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
sqs-dg-172
sqs-dg.pdf
172
not function as intended for users with that IAM policy. You don't need to allow minimum console permissions for users that make calls only to the AWS CLI or Amazon SQS actions. Identity-based policy examples for Amazon SQS By default, users and roles don't have permission to create or modify Amazon SQS 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. 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 SQS, including the format of the ARNs for each of the resource types, see Actions, Resources, and Condition Keys for Amazon Simple Queue Service in the Service Authorization Reference. Using policies 649 Amazon Simple Queue Service Developer Guide Note When you configure lifecycle hooks for Amazon EC2 Auto Scaling, you don't need to write a policy to send messages to an Amazon SQS queue. For more information, see Amazon EC2 Auto Scaling Lifecycle Hooks in the Amazon EC2 User Guide. Policy best practices Identity-based policies determine whether someone can create, access, or delete Amazon SQS 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 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 Using policies 650 Amazon Simple Queue 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 SQS console To access the Amazon Simple Queue Service console, you must have a minimum set of permissions. These permissions must allow you to list and view details about the Amazon SQS 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 SQS console, also attach the Amazon SQS AmazonSQSReadOnlyAccess AWS managed policy to the entities. For more information, see Adding permissions to a user in the IAM User Guide.
sqs-dg-173
sqs-dg.pdf
173
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 SQS console, also attach the Amazon SQS AmazonSQSReadOnlyAccess AWS managed policy to the entities. For more information, see Adding permissions to a user 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", "iam:GetUser" Using policies 651 Amazon Simple Queue Service ], "Resource": ["arn:aws:iam::*:user/${aws:username}"] }, Developer Guide { "Sid": "NavigateInConsole", "Effect": "Allow", "Action": [ "iam:GetGroupPolicy", "iam:GetPolicyVersion", "iam:GetPolicy", "iam:ListAttachedGroupPolicies", "iam:ListGroupPolicies", "iam:ListPolicyVersions", "iam:ListPolicies", "iam:ListUsers" ], "Resource": "*" } ] } Allow a user to create queues In the following example, we create a policy for Bob that lets him access all Amazon SQS actions, but only with queues whose names are prefixed with the literal string alice_queue_. Amazon SQS doesn't automatically grant the creator of a queue permissions to use the queue. Therefore, we must explicitly grant Bob permissions to use all Amazon SQS actions in addition to CreateQueue action in the IAM policy. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "sqs:*", "Resource": "arn:aws:sqs:*:123456789012:alice_queue_*" }] } Using policies 652 Amazon Simple Queue Service Developer Guide Allow developers to write messages to a shared queue In the following example, we create a group for developers and attach a policy that lets the group use the Amazon SQS SendMessage action, but only with the queue that belongs to the specified AWS account and is named MyCompanyQueue. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:*:123456789012:MyCompanyQueue" }] } You can use * instead of SendMessage to grant the following actions to a principal on a shared queue: ChangeMessageVisibility, DeleteMessage, GetQueueAttributes, GetQueueUrl, ReceiveMessage, and SendMessage. Note Although * includes access provided by other permission types, Amazon SQS considers permissions separately. For example, it is possible to grant both * and SendMessage permissions to a user, even though a * includes the access provided by SendMessage. This concept also applies when you remove a permission. If a principal has only a * permission, requesting to remove a SendMessage permission doesn't leave the principal with an everything-but permission. Instead, the request has no effect, because the principal doesn't possess an explicit SendMessage permission. To leave the principal with only the ReceiveMessage permission, first add the ReceiveMessage permission and then remove the * permission. Allow managers to get the general size of queues In the following example, we create a group for managers and attach a policy that lets the group use the Amazon SQS GetQueueAttributes action with all of the queues that belong to the specified AWS account. { "Version": "2012-10-17", Using policies 653 Amazon Simple Queue Service "Statement": [{ "Effect": "Allow", "Action": "sqs:GetQueueAttributes", "Resource": "*" }] } Allow a partner to send messages to a specific queue Developer Guide You can accomplish this task using an Amazon SQS policy or an IAM policy. If your partner has an AWS account, it might be easier to use an Amazon SQS policy. However, any user in the partner's company who possesses the AWS security credentials can send messages to the queue. If you want to limit access to a particular user or application, you must treat the partner like a user in your own company and use an IAM policy instead of an Amazon SQS policy. This example performs the following actions: 1. Create a group called WidgetCo to represent the partner company. 2. Create a user for the specific user or application at the partner's company who needs access. 3. Add the user to the group. 4. Attach a policy that gives the group access only to the SendMessage action for only the queue named WidgetPartnerQueue. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:*:123456789012:WidgetPartnerQueue" }] } Basic examples of Amazon SQS policies This section shows example policies for common Amazon SQS use cases. You can use the console to verify the effects of each policy as you attach the policy to the user. Initially, the user doesn't have permissions and won't be able to do anything in the console. As you attach policies to the user, you can verify that the user can perform various
sqs-dg-174
sqs-dg.pdf
174
a policy that gives the group access only to the SendMessage action for only the queue named WidgetPartnerQueue. { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:*:123456789012:WidgetPartnerQueue" }] } Basic examples of Amazon SQS policies This section shows example policies for common Amazon SQS use cases. You can use the console to verify the effects of each policy as you attach the policy to the user. Initially, the user doesn't have permissions and won't be able to do anything in the console. As you attach policies to the user, you can verify that the user can perform various actions in the console. Using policies 654 Amazon Simple Queue Service Developer Guide Note We recommend that you use two browser windows: one to grant permissions and the other to sign into the AWS Management Console using the user's credentials to verify permissions as you grant them to the user. Example 1: Grant one permission to one AWS account The following example policy grants AWS account number 111122223333 the SendMessage permission for the queue named 444455556666/queue1 in the US East (Ohio) region. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_SendMessage", "Effect": "Allow", "Principal": { "AWS": [ "111122223333" ] }, "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-east-2:444455556666:queue1" }] } Example 2: Grant two permissions to one AWS account The following example policy grants AWS account number 111122223333 both the SendMessage and ReceiveMessage permission for the queue named 444455556666/queue1. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_Send_Receive", "Effect": "Allow", "Principal": { "AWS": [ "111122223333" Using policies 655 Developer Guide Amazon Simple Queue Service ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:*:444455556666:queue1" }] } Example 3: Grant all permissions to two AWS accounts The following example policy grants two different AWS accounts numbers (111122223333 and 444455556666) permission to use all actions to which Amazon SQS allows shared access for the queue named 123456789012/queue1 in the US East (Ohio) region. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_AllActions", "Effect": "Allow", "Principal": { "AWS": [ "111122223333", "444455556666" ] }, "Action": "sqs:*", "Resource": "arn:aws:sqs:us-east-2:123456789012:queue1" }] } Example 4: Grant cross-account permissions to a role and a username The following example policy grants role1 and username1 under AWS account number 111122223333 cross-account permission to use all actions to which Amazon SQS allows shared access for the queue named 123456789012/queue1 in the US East (Ohio) region. Cross-account permissions don't apply to the following actions: • AddPermission Using policies 656 Developer Guide Amazon Simple Queue Service • CancelMessageMoveTask • CreateQueue • DeleteQueue • ListMessageMoveTask • ListQueues • ListQueueTags • RemovePermission • SetQueueAttributes • StartMessageMoveTask • TagQueue • UntagQueue { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_AllActions", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::111122223333:role/role1", "arn:aws:iam::111122223333:user/username1" ] }, "Action": "sqs:*", "Resource": "arn:aws:sqs:us-east-2:123456789012:queue1" }] } Example 5: Grant a permission to all users The following example policy grants all users (anonymous users) ReceiveMessage permission for the queue named 111122223333/queue1. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", Using policies 657 Developer Guide Amazon Simple Queue Service "Statement": [{ "Sid":"Queue1_AnonymousAccess_ReceiveMessage", "Effect": "Allow", "Principal": "*", "Action": "sqs:ReceiveMessage", "Resource": "arn:aws:sqs:*:111122223333:queue1" }] } Example 6: Grant a time-limited permission to all users The following example policy grants all users (anonymous users) ReceiveMessage permission for the queue named 111122223333/queue1, but only between 12:00 p.m. (noon) and 3:00 p.m. on January 31, 2009. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_AnonymousAccess_ReceiveMessage_TimeLimit", "Effect": "Allow", "Principal": "*", "Action": "sqs:ReceiveMessage", "Resource": "arn:aws:sqs:*:111122223333:queue1", "Condition" : { "DateGreaterThan" : { "aws:CurrentTime":"2009-01-31T12:00Z" }, "DateLessThan" : { "aws:CurrentTime":"2009-01-31T15:00Z" } } }] } Example 7: Grant all permissions to all users in a CIDR range The following example policy grants all users (anonymous users) permission to use all possible Amazon SQS actions that can be shared for the queue named 111122223333/queue1, but only if the request comes from the 192.0.2.0/24 CIDR range. { Using policies 658 Amazon Simple Queue Service Developer Guide "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_AnonymousAccess_AllActions_AllowlistIP", "Effect": "Allow", "Principal": "*", "Action": "sqs:*", "Resource": "arn:aws:sqs:*:111122223333:queue1", "Condition" : { "IpAddress" : { "aws:SourceIp":"192.0.2.0/24" } } }] } Example 8: Allowlist and blocklist permissions for users in different CIDR ranges The following example policy has two statements: • The first statement grants all users (anonymous users) in the 192.0.2.0/24 CIDR range (except for 192.0.2.188) permission to use the SendMessage action for the queue named 111122223333/queue1. • The second statement blocks all users (anonymous users) in the 12.148.72.0/23 CIDR range from using the queue. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_AnonymousAccess_SendMessage_IPLimit", "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:*:111122223333:queue1", "Condition" : { "IpAddress" : { "aws:SourceIp":"192.0.2.0/24" }, "NotIpAddress" : { "aws:SourceIp":"192.0.2.188/32" Using policies 659 Amazon Simple Queue Service Developer Guide } } }, { "Sid":"Queue1_AnonymousAccess_AllActions_IPLimit_Deny", "Effect": "Deny", "Principal": "*", "Action": "sqs:*", "Resource": "arn:aws:sqs:*:111122223333:queue1", "Condition" : { "IpAddress" : { "aws:SourceIp":"12.148.72.0/23" } } }] } Using custom policies with the Amazon SQS Access Policy Language To grant basic permissions (such as SendMessage
sqs-dg-175
sqs-dg.pdf
175
the queue named 111122223333/queue1. • The second statement blocks all users (anonymous users) in the 12.148.72.0/23 CIDR range from using the queue. { "Version": "2012-10-17", "Id": "Queue1_Policy_UUID", "Statement": [{ "Sid":"Queue1_AnonymousAccess_SendMessage_IPLimit", "Effect": "Allow", "Principal": "*", "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:*:111122223333:queue1", "Condition" : { "IpAddress" : { "aws:SourceIp":"192.0.2.0/24" }, "NotIpAddress" : { "aws:SourceIp":"192.0.2.188/32" Using policies 659 Amazon Simple Queue Service Developer Guide } } }, { "Sid":"Queue1_AnonymousAccess_AllActions_IPLimit_Deny", "Effect": "Deny", "Principal": "*", "Action": "sqs:*", "Resource": "arn:aws:sqs:*:111122223333:queue1", "Condition" : { "IpAddress" : { "aws:SourceIp":"12.148.72.0/23" } } }] } Using custom policies with the Amazon SQS Access Policy Language To grant basic permissions (such as SendMessage or ReceiveMessage) based only on an AWS account ID, you don’t need to write a custom policy. Instead, use the Amazon SQS AddPermission action. To allow or deny access based on specific conditions, such as request time or the requester's IP address, you must create a custom Amazon SQS policy and upload it using the SetQueueAttributes action. Topics • Amazon SQS access control architecture • Amazon SQS access control process workflow • Amazon SQS Access Policy Language key concepts • Amazon SQS Access Policy Language evaluation logic • Relationships between explicit and default denials in the Amazon SQS Access Policy Language • Limitations of Amazon SQS custom policies • Custom Amazon SQS Access Policy Language examples Amazon SQS access control architecture The following diagram describes the access control for your Amazon SQS resources. Using policies 660 Amazon Simple Queue Service Developer Guide You, the resource owner. Your resources contained within the AWS service (for example, Amazon SQS queues). Your policies. It is a good practice to have one policy per resource. The AWS service provides an API you use to upload and manage your policies. 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. Using policies 661 Amazon Simple Queue Service Developer Guide Amazon SQS access control process workflow The following diagram describes the general workflow of access control with the Amazon SQS access policy language. You write an Amazon SQS policy for your queue. You upload your policy to AWS. The AWS service provides an API that you use to upload your policies. For example, you use the Amazon SQS SetQueueAttributes action to upload a policy for a particular Amazon SQS queue. Someone sends a request to use your Amazon SQS queue. Amazon SQS examines all available Amazon SQS policies and determines which ones are applicable. Amazon SQS evaluates the policies and determines whether the requester is allowed to use your queue. Based on the policy evaluation result, Amazon SQS either returns an Access denied error to the requester or continues to process the request. Using policies 662 Amazon Simple Queue Service Developer Guide Amazon SQS Access Policy Language key concepts To write your own policies, you must be familiar with JSON and a number of key concepts. Allow The result of a Statement that has Effect set to allow. Action The activity that the Principal has permission to perform, typically a request to AWS. Default-deny The result of a Statement that has no Allow or Explicit-deny settings. Condition Any restriction or detail about a Permission. Typical conditions are related to date and time and IP addresses. Effect The result that you want the Statement of a Policy to return at evaluation time. You specify the deny or allow value when you write the policy statement. There can be three possible results at policy evaluation time: Default-deny, Allow, and Explicit-deny. Explicit-deny The result of a Statement that has Effect set to deny. Evaluation The process that Amazon SQS uses to determine whether an incoming request should be denied or allowed based on a Policy. Issuer The user who writes a Policy to grant permissions to a resource. The issuer, by definition is always the resource owner. AWS doesn't permit Amazon SQS users to create policies for resources they don't own. Key The specific characteristic that is the basis for access restriction. Using policies 663 Amazon Simple Queue Service Permission Developer Guide The concept of allowing or disallowing access to a resource using a Condition and a Key. Policy The document that acts as a container for one or more statements. Amazon SQS uses the policy to determine whether to grant access to a user for a resource. Principal The user who receives Permission in the Policy. Resource The object that the Principal requests access to. Statement The formal description of a single permission, written in the access policy language as part of a broader Policy document. Requester The user who sends a request for access to a Resource. Amazon SQS Access Policy Language evaluation
sqs-dg-176
sqs-dg.pdf
176
allowing or disallowing access to a resource using a Condition and a Key. Policy The document that acts as a container for one or more statements. Amazon SQS uses the policy to determine whether to grant access to a user for a resource. Principal The user who receives Permission in the Policy. Resource The object that the Principal requests access to. Statement The formal description of a single permission, written in the access policy language as part of a broader Policy document. Requester The user who sends a request for access to a Resource. Amazon SQS Access Policy Language evaluation logic At evaluation time, Amazon SQS determines whether a request from someone other than the resource owner 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-deny. Using policies 664 Amazon Simple Queue Service Developer Guide • An Explicit-deny overrides any allow. • The order in which the policies are evaluated isn't important. The following diagram describes in detail how Amazon SQS evaluates decisions about access permissions. The decision starts with a default-deny. The enforcement code evaluates all the policies that are applicable to the request (based on the Using policies 665 Amazon Simple Queue Service Developer Guide resource, principal, action, and conditions). The order in which the enforcement code evaluates the policies isn't important. The enforcement code looks for an explicit-deny instruction that can apply to the request. If it finds even one, the enforcement code returns a decision of deny and the process finishes. If no explicit-deny instruction is found, the enforcement code looks for any allow instructions that can apply to the request. If it finds even one, the enforcement code returns a decision of allow and the process finishes (the service continues to process the request). If no allow instruction is found, then the final decision is deny (because there is no explicit-deny or allow, this is considered a default-deny). Relationships between explicit and default denials in the Amazon SQS Access Policy Language If an Amazon SQS policy doesn't directly apply to a request, the request results in a Default-deny. For example, if a user requests permission to use Amazon SQS but the only policy that applies to the user can use DynamoDB, the requests results in a default-deny. If a condition in a statement isn't met, the request results in a default-deny. If all conditions in a statement are met, the request results in either an Allow or an Explicit-deny based on the value of the Effect element of the policy. Policies don't specify what to do if a condition isn't met, so the default result in this case is a default-deny. For example, you want to prevent requests that come from Antarctica. You write Policy A1 that allows a request only if it doesn't come from Antarctica. The following diagram illustrates the Amazon SQS policy. If a user sends a request from the U.S., the condition is met (the request isn't from Antarctica), and the request results in an allow. However, if a user sends a request from Antarctica, the condition Using policies 666 Amazon Simple Queue Service Developer Guide isn't met and the request defaults to a default-deny. You can change the result to an explicit- deny by writing Policy A2 that explicitly denies a request if it comes from Antarctica. The following diagram illustrates the policy. If a user sends a request from Antarctica, the condition is met and the request results in an explicit-deny. The distinction between a default-deny and an explicit-deny is important because an allow can overwrite the former but not the latter. For example, Policy B allows requests if they arrive on June 1, 2010. The following diagram compares combining this policy with Policy A1 and Policy A2. Using policies 667 Amazon Simple Queue Service Developer Guide In Scenario 1, Policy A1 results in a default-deny and Policy B results in an allow because the policy 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 allowed. In Scenario 2, Policy B2 results in an explicit-deny and Policy B results in an allow. The explicit- deny from Policy A2 overrides the allow from Policy B, and the request is denied. Using policies 668 Amazon Simple Queue Service Developer Guide Limitations of Amazon SQS custom policies Cross-account access Cross-account permissions don't apply to the following actions: • AddPermission • CancelMessageMoveTask • CreateQueue • DeleteQueue • ListMessageMoveTask • ListQueues • ListQueueTags • RemovePermission • SetQueueAttributes • StartMessageMoveTask • TagQueue • UntagQueue Condition keys Currently, Amazon SQS supports only a limited subset of the condition keys available in IAM. For more information,
sqs-dg-177
sqs-dg.pdf
177
2, Policy B2 results in an explicit-deny and Policy B results in an allow. The explicit- deny from Policy A2 overrides the allow from Policy B, and the request is denied. Using policies 668 Amazon Simple Queue Service Developer Guide Limitations of Amazon SQS custom policies Cross-account access Cross-account permissions don't apply to the following actions: • AddPermission • CancelMessageMoveTask • CreateQueue • DeleteQueue • ListMessageMoveTask • ListQueues • ListQueueTags • RemovePermission • SetQueueAttributes • StartMessageMoveTask • TagQueue • UntagQueue Condition keys Currently, Amazon SQS supports only a limited subset of the condition keys available in IAM. For more information, see Amazon SQS API permissions: Actions and resource reference. Custom Amazon SQS Access Policy Language examples The following are examples of typical Amazon SQS access policies. Example 1: Give permission to one account The following example Amazon SQS policy gives AWS account 111122223333 permission to send to and receive from queue2 owned by AWS account 444455556666. { "Version": "2012-10-17", Using policies 669 Developer Guide Amazon Simple Queue Service "Id": "UseCase1", "Statement" : [{ "Sid": "1", "Effect": "Allow", "Principal": { "AWS": [ "111122223333" ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:444455556666:queue2" }] } Example 2: Give permission to one or more accounts The following example Amazon SQS policy gives one or more AWS accounts access to queues owned by your account for a specific time period. It is necessary to write this policy and to upload it to Amazon SQS using the SetQueueAttributes action because the AddPermission action doesn't permit specifying a time restriction when granting access to a queue. { "Version": "2012-10-17", "Id": "UseCase2", "Statement" : [{ "Sid": "1", "Effect": "Allow", "Principal": { "AWS": [ "111122223333", "444455556666" ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:444455556666:queue2", "Condition": { "DateLessThan": { Using policies 670 Amazon Simple Queue Service Developer Guide "AWS:CurrentTime": "2009-06-30T12:00Z" } } }] } Example 3: Give permission to requests from Amazon EC2 instances The following example Amazon SQS policy gives access to requests that come from Amazon EC2 instances. This example builds on the "Example 2: Give permission to one or more accounts" example: it restricts access to before June 30, 2009 at 12 noon (UTC), it restricts access to the IP range 203.0.113.0/24. It is necessary to write this policy and to upload it to Amazon SQS using the SetQueueAttributes action because the AddPermission action doesn't permit specifying an IP address restriction when granting access to a queue. { "Version": "2012-10-17", "Id": "UseCase3", "Statement" : [{ "Sid": "1", "Effect": "Allow", "Principal": { "AWS": [ "111122223333" ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:444455556666:queue2", "Condition": { "DateLessThan": { "AWS:CurrentTime": "2009-06-30T12:00Z" }, "IpAddress": { "AWS:SourceIp": "203.0.113.0/24" } } }] } Using policies 671 Amazon Simple Queue Service Developer Guide Example 4: Deny access to a specific account The following example Amazon SQS policy denies a specific AWS account access to your queue. This example builds on the "Example 1: Give permission to one account" example: it denies access to the specified AWS account. It is necessary to write this policy and to upload it to Amazon SQS using the SetQueueAttributes action because the AddPermission action doesn't permit deny access to a queue (it allows only granting access to a queue). { "Version": "2012-10-17", "Id": "UseCase4", "Statement" : [{ "Sid": "1", "Effect": "Deny", "Principal": { "AWS": [ "111122223333" ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:444455556666:queue2" }] } Example 5: Deny access if it isn't from a VPC endpoint The following example Amazon SQS policy restricts access to queue1: 111122223333 can perform the SendMessage and ReceiveMessage actions only from the VPC endpoint ID vpce-1a2b3c4d (specified using the aws:sourceVpce condition). For more information, see Amazon Virtual Private Cloud endpoints for Amazon SQS. Note • The aws:sourceVpce condition doesn't require an ARN for the VPC endpoint resource, only the VPC endpoint ID. • You can modify the following example to restrict all actions to a specific VPC endpoint by denying all Amazon SQS actions (sqs:*) in the second statement. However, such a Using policies 672 Amazon Simple Queue Service Developer Guide policy statement would stipulate that all actions (including administrative actions needed to modify queue permissions) must be made through the specific VPC endpoint defined in the policy, potentially preventing the user from modifying queue permissions in the future. { "Version": "2012-10-17", "Id": "UseCase5", "Statement": [{ "Sid": "1", "Effect": "Allow", "Principal": { "AWS": [ "111122223333" ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:111122223333:queue1" }, { "Sid": "2", "Effect": "Deny", "Principal": "*", "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:111122223333:queue1", "Condition": { "StringNotEquals": { "aws:sourceVpce": "vpce-1a2b3c4d" } } } ] } Using policies 673 Amazon Simple Queue Service Developer Guide Using temporary security credentials with Amazon SQS In addition to creating users with their own security credentials, IAM also allows you to grant temporary security credentials to any user, allowing
sqs-dg-178
sqs-dg.pdf
178
preventing the user from modifying queue permissions in the future. { "Version": "2012-10-17", "Id": "UseCase5", "Statement": [{ "Sid": "1", "Effect": "Allow", "Principal": { "AWS": [ "111122223333" ] }, "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:111122223333:queue1" }, { "Sid": "2", "Effect": "Deny", "Principal": "*", "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage" ], "Resource": "arn:aws:sqs:us-east-2:111122223333:queue1", "Condition": { "StringNotEquals": { "aws:sourceVpce": "vpce-1a2b3c4d" } } } ] } Using policies 673 Amazon Simple Queue Service Developer Guide Using temporary security credentials with Amazon SQS In addition to creating users with their own security credentials, IAM also allows you to grant temporary security credentials to any user, allowing the user to access your AWS services and resources. You can manage users who have AWS accounts. You can also manage users for your system who don't have AWS accounts (federated users). In addition, applications that you create to access your AWS resources can also be considered to be "users." You can use these temporary security credentials to make requests to Amazon SQS. The API libraries compute the necessary signature value using those credentials to authenticate your request. If you send requests using expired credentials, Amazon SQS denies the request. Note You can't set a policy based on temporary credentials. Prerequisites 1. Use IAM to create temporary security credentials: • Security token • Access Key ID • Secret Access Key 2. Prepare your string to sign with the temporary Access Key ID and the security token. 3. Use the temporary Secret Access Key instead of your own Secret Access Key to sign your Query API request. Note When you submit the signed Query API request, use the temporary Access Key ID instead of your own Access Key ID and to include the security token. For more information about IAM support for temporary security credentials, see Granting Temporary Access to Your AWS Resources in the IAM User Guide. Using policies 674 Amazon Simple Queue Service Developer Guide To call an Amazon SQS Query API action using temporary security credentials 1. Request a temporary security token using AWS Identity and Access Management. For more information, see Creating Temporary Security Credentials to Enable Access for IAM Users in the IAM User Guide. IAM returns a security token, an Access Key ID, and a Secret Access Key. 2. Prepare your query using the temporary Access Key ID instead of your own Access Key ID and include the security token. Sign your request using the temporary Secret Access Key instead of your own. 3. Submit your signed query string with the temporary Access Key ID and the security token. The following example demonstrates how to use temporary security credentials to authenticate an Amazon SQS request. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Signing AWS API Requests in the Amazon Web Services General Reference. https://sqs.us-east-2.amazonaws.com/ ?Action=CreateQueue &DefaultVisibilityTimeout=40 &QueueName=MyQueue &Attribute.1.Name=VisibilityTimeout &Attribute.1.Value=40 &Expires=2020-12-18T22%3A52%3A43PST &SecurityToken=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY &AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE &Version=2012-11-05 &AUTHPARAMS The following example uses temporary security credentials to send two messages using the SendMessageBatch action. https://sqs.us-east-2.amazonaws.com/ ?Action=SendMessageBatch &SendMessageBatchRequestEntry.1.Id=test_msg_001 &SendMessageBatchRequestEntry.1.MessageBody=test%20message%20body%201 &SendMessageBatchRequestEntry.2.Id=test_msg_002 &SendMessageBatchRequestEntry.2.MessageBody=test%20message%20body%202 &SendMessageBatchRequestEntry.2.DelaySeconds=60 &Expires=2020-12-18T22%3A52%3A43PST Using policies 675 Amazon Simple Queue Service Developer Guide &SecurityToken=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY &AWSAccessKeyId=AKIAI44QH8DHBEXAMPLE &Version=2012-11-05 &AUTHPARAMS Access management for encrypted Amazon SQS queues with least privilege policies You can use Amazon SQS to exchange sensitive data between applications by using server-side encryption (SSE) integrated with AWS Key Management Service (KMS). With the integration of Amazon SQS and AWS KMS, you can centrally manage the keys that protect Amazon SQS, as well as the keys that protect your other AWS resources. Multiple AWS services can act as event sources that send events to Amazon SQS. To enable an event source to access the encrypted Amazon SQS queue, you need to configure the queue with a customer-managed AWS KMS key. Then, use the key policy to allow the service to use the required AWS KMS API methods. The service also requires permissions to authenticate access to enable the queue to send events. You can achieve this by using an Amazon SQS policy, which is a resource- based policy that you can use to control access to the Amazon SQS queue and its data. The following sections provide information on how to control access to your encrypted Amazon SQS queue through the Amazon SQS policy and the AWS KMS key policy. The policies in this guide will help you achieve least privilege. This guide also describes how resource-based policies address the confused-deputy problem by using the aws:SourceArn, aws:SourceAccount, and aws:PrincipalOrgID global IAM condition context keys. Topics • Overview • Least privilege key policy for Amazon SQS • Amazon SQS policy statements for the dead-letter queue • Prevent the cross-service confused deputy problem • Use IAM Access Analyzer to review cross-account access Overview In this topic, we will walk you through a common use case to illustrate how you can build the key policy and the
sqs-dg-179
sqs-dg.pdf
179
and the AWS KMS key policy. The policies in this guide will help you achieve least privilege. This guide also describes how resource-based policies address the confused-deputy problem by using the aws:SourceArn, aws:SourceAccount, and aws:PrincipalOrgID global IAM condition context keys. Topics • Overview • Least privilege key policy for Amazon SQS • Amazon SQS policy statements for the dead-letter queue • Prevent the cross-service confused deputy problem • Use IAM Access Analyzer to review cross-account access Overview In this topic, we will walk you through a common use case to illustrate how you can build the key policy and the Amazon SQS queue policy. This use case is shown in the following image. Using policies 676 Amazon Simple Queue Service Developer Guide In this example, the message producer is an Amazon Simple Notification Service (SNS) topic, which is configured to fanout messages to your encrypted Amazon SQS queue. The message consumer is a compute service, such as an AWS Lambda function, an Amazon Elastic Compute Cloud (EC2) instance, or an AWS Fargate container. Your Amazon SQS queue is then configured to send failed messages to a Dead-letter Queue (DLQ). This is useful for debugging your application or messaging system because DLQs let you isolate unconsumed messages to determine why their processing didn't succeed. In the solution defined in this topic, a compute service such as a Lambda function is used to process messages stored in the Amazon SQS queue. If the message consumer is located in a virtual private cloud (VPC), the DenyReceivingIfNotThroughVPCE policy statement included in this guide lets you restrict message reception to that specific VPC. Note This guide contains only the required IAM permissions in the form of policy statements. To construct the policy, you need to add the statements to your Amazon SQS policy or your AWS KMS key policy. This guide doesn't provide instructions on how to create the Amazon SQS queue or the AWS KMS key. For instructions on how to create these resources, see Creating an Amazon SQS queue and Creating keys. The Amazon SQS policy defined in this guide doesn’t support redriving messages directly to the same or a different Amazon SQS queue. Using policies 677 Amazon Simple Queue Service Developer Guide Least privilege key policy for Amazon SQS In this section, we describe the required least privilege permissions in AWS KMS for the customer- managed key that you use to encrypt your Amazon SQS queue. With these permissions, you can limit access to only the intended entities while implementing least privilege. The key policy must consist of the following policy statements, which we describe in detail below: • Grant administrator permissions to the AWS KMS key • Grant read-only access to the key metadata • Grant Amazon SNS KMS permissions to Amazon SNS to publish messages to the queue • Allow consumers to decrypt messages from the queue Grant administrator permissions to the AWS KMS key To create an AWS KMS key, you need to provide AWS KMS administrator permissions to the IAM role that you use to deploy the AWS KMS key. These administrator permissions are defined in the following AllowKeyAdminPermissions policy statement. When you add this statement to your AWS KMS key policy, make sure to replace <admin-role ARN> with the Amazon Resource Name (ARN) of the IAM role used to deploy the AWS KMS key, manage the AWS KMS key, or both. This can be the IAM role of your deployment pipeline, or the administrator role for your organization in your AWS Organizations. { "Sid": "AllowKeyAdminPermissions", "Effect": "Allow", "Principal": { "AWS": [ "<admin-role ARN>" ] }, "Action": [ "kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*", "kms:Put*", "kms:Update*", "kms:Revoke*", "kms:Disable*", "kms:Get*", Using policies 678 Amazon Simple Queue Service Developer Guide "kms:Delete*", "kms:TagResource", "kms:UntagResource", "kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion" ], "Resource": "*" } Note In an AWS KMS key policy, the value of the Resource element needs to be *, which means "this AWS KMS key". The asterisk (*) identifies the AWS KMS key to which the key policy is attached. Grant read-only access to the key metadata To grant other IAM roles read-only access to your key metadata, add the AllowReadAccessToKeyMetaData statement to your key policy. For example, the following statement lets you list all of the AWS KMS keys in your account for auditing purposes. This statement grants the AWS root user read-only access to the key metadata. Therefore, any IAM principal in the account can have access to the key metadata when their identity-based policies have the permissions listed in the following statement: kms:Describe*, kms:Get*, and kms:List*. Make sure to replace <account-ID> with your own information. { "Sid": "AllowReadAcesssToKeyMetaData", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::<accountID>:root" ] }, "Action": [ "kms:Describe*", "kms:Get*", "kms:List*" ], "Resource": "*" Using policies 679 Amazon Simple Queue Service } Developer Guide Grant Amazon SNS KMS permissions to Amazon
sqs-dg-180
sqs-dg.pdf
180
of the AWS KMS keys in your account for auditing purposes. This statement grants the AWS root user read-only access to the key metadata. Therefore, any IAM principal in the account can have access to the key metadata when their identity-based policies have the permissions listed in the following statement: kms:Describe*, kms:Get*, and kms:List*. Make sure to replace <account-ID> with your own information. { "Sid": "AllowReadAcesssToKeyMetaData", "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::<accountID>:root" ] }, "Action": [ "kms:Describe*", "kms:Get*", "kms:List*" ], "Resource": "*" Using policies 679 Amazon Simple Queue Service } Developer Guide Grant Amazon SNS KMS permissions to Amazon SNS to publish messages to the queue To allow your Amazon SNS topic to publish messages to your encrypted Amazon SQS queue, add the AllowSNSToSendToSQS policy statement to your key policy. This statement grants Amazon SNS permissions to use the AWS KMS key to publish to your Amazon SQS queue. Make sure to replace <account-ID> with your own information. Note The Condition in the statement limits access to only the Amazon SNS service in the same AWS account. { "Sid": "AllowSNSToSendToSQS", "Effect": "Allow", "Principal": { "Service": [ "sns.amazonaws.com" ] }, "Action": [ "kms:Decrypt", "kms:GenerateDataKey" ], "Resource": "*", "Condition": { "StringEquals": { "aws:SourceAccount": "<account-id>" } } } Allow consumers to decrypt messages from the queue The following AllowConsumersToReceiveFromTheQueue statement grants the Amazon SQS message consumer the required permissions to decrypt messages received from the encrypted Amazon SQS queue. When you attach the policy statement, replace <consumer's runtime role ARN> with the IAM runtime role ARN of the message consumer. Using policies 680 Amazon Simple Queue Service Developer Guide { "Sid": "AllowConsumersToReceiveFromTheQueue", "Effect": "Allow", "Principal": { "AWS": [ "<consumer's execution role ARN>" ] }, "Action": [ "kms:Decrypt" ], "Resource": "*" } Least privilege Amazon SQS policy This section walks you through the least privilege Amazon SQS queue policies for the use case covered by this guide (for example, Amazon SNS to Amazon SQS). The defined policy is designed to prevent unintended access by using a mix of both Deny and Allow statements. The Allow statements grant access to the intended entity or entities. The Deny statements prevent other unintended entities from accessing the Amazon SQS queue, while excluding the intended entity within the policy condition. The Amazon SQS policy includes the following statements, which we describe in detail below: • Restrict Amazon SQS management permissions • Restrict Amazon SQS queue actions from the specified organization • Grant Amazon SQS permissions to consumers • Enforce encryption in transit • Restrict message transmission to a specific Amazon SNS topic • (Optional) Restrict message reception to a specific VPC endpoint Restrict Amazon SQS management permissions The following RestrictAdminQueueActions policy statement restricts the Amazon SQS management permissions to only the IAM role or roles that you use to deploy the queue, manage the queue, or both. Make sure to replace the <placeholder values> with your own information. Specify the ARN of the IAM role used to deploy the Amazon SQS queue, as well as the ARNs of any administrator roles that should have Amazon SQS management permissions. Using policies 681 Amazon Simple Queue Service Developer Guide { "Sid": "RestrictAdminQueueActions", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": [ "sqs:AddPermission", "sqs:DeleteQueue", "sqs:RemovePermission", "sqs:SetQueueAttributes" ], "Resource": "<SQS Queue ARN>", "Condition": { "StringNotLike": { "aws:PrincipalARN": [ "arn:aws:iam::<account-id>:role/<deployment-role-name>", "<admin-role ARN>" ] } } } Restrict Amazon SQS queue actions from the specified organization To help protect your Amazon SQS resources from external access (access by an entity outside of your AWS organization), use the following statement. This statement limits Amazon SQS queue access to the organization that you specify in the Condition. Make sure to replace <SQS queue ARN> with the ARN of the IAM role used to deploy the Amazon SQS queue; and the <org-id>, with your organization ID. { "Sid": "DenyQueueActionsOutsideOrg", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": [ "sqs:AddPermission", "sqs:ChangeMessageVisibility", "sqs:DeleteQueue", "sqs:RemovePermission", Using policies 682 Amazon Simple Queue Service Developer Guide "sqs:SetQueueAttributes", "sqs:ReceiveMessage" ], "Resource": "<SQS queue ARN>", "Condition": { "StringNotEquals": { "aws:PrincipalOrgID": [ "<org-id>" ] } } } Grant Amazon SQS permissions to consumers To receive messages from the Amazon SQS queue, you need to provide the message consumer with the necessary permissions. The following policy statement grants the consumer, which you specify, the required permissions to consume messages from the Amazon SQS queue. When adding the statement to your Amazon SQS policy, make sure to replace <consumer's IAM runtime role ARN> with the ARN of the IAM runtime role used by the consumer; and <SQS queue ARN>, with the ARN of the IAM role used to deploy the Amazon SQS queue. { "Sid": "AllowConsumersToReceiveFromTheQueue", "Effect": "Allow", "Principal": { "AWS": "<consumer's IAM execution role ARN>" }, "Action": [ "sqs:ChangeMessageVisibility", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "sqs:ReceiveMessage" ], "Resource": "<SQS queue ARN>" } To prevent other entities from receiving messages
sqs-dg-181
sqs-dg.pdf
181
policy statement grants the consumer, which you specify, the required permissions to consume messages from the Amazon SQS queue. When adding the statement to your Amazon SQS policy, make sure to replace <consumer's IAM runtime role ARN> with the ARN of the IAM runtime role used by the consumer; and <SQS queue ARN>, with the ARN of the IAM role used to deploy the Amazon SQS queue. { "Sid": "AllowConsumersToReceiveFromTheQueue", "Effect": "Allow", "Principal": { "AWS": "<consumer's IAM execution role ARN>" }, "Action": [ "sqs:ChangeMessageVisibility", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "sqs:ReceiveMessage" ], "Resource": "<SQS queue ARN>" } To prevent other entities from receiving messages from the Amazon SQS queue, add the DenyOtherConsumersFromReceiving statement to the Amazon SQS queue policy. This statement restricts message consumption to the consumer that you specify—allowing no other Using policies 683 Amazon Simple Queue Service Developer Guide consumers to have access, even when their identity-permissions would grant them access. Make sure to replace <SQS queue ARN> and <consumer’s runtime role ARN> with your own information. { "Sid": "DenyOtherConsumersFromReceiving", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": [ "sqs:ChangeMessageVisibility", "sqs:DeleteMessage", "sqs:ReceiveMessage" ], "Resource": "<SQS queue ARN>", "Condition": { "StringNotLike": { "aws:PrincipalARN": "<consumer's execution role ARN>" } } } Enforce encryption in transit The following DenyUnsecureTransport policy statement enforces the consumers and producers to use secure channels (TLS connections) to send and receive messages from the Amazon SQS queue. Make sure to replace <SQS queue ARN> with the ARN of the IAM role used to deploy the Amazon SQS queue. { "Sid": "DenyUnsecureTransport", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": [ "sqs:ReceiveMessage", "sqs:SendMessage" ], "Resource": "<SQS queue ARN>", Using policies 684 Amazon Simple Queue Service "Condition": { "Bool": { "aws:SecureTransport": "false" } } } Developer Guide Restrict message transmission to a specific Amazon SNS topic The following AllowSNSToSendToTheQueue policy statement allows the specified Amazon SNS topic to send messages to the Amazon SQS queue. Make sure to replace <SQS queue ARN> with the ARN of the IAM role used to deploy the Amazon SQS queue; and <SNS topic ARN>, with the Amazon SNS topic ARN. { "Sid": "AllowSNSToSendToTheQueue", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "<SQS queue ARN>", "Condition": { "ArnLike": { "aws:SourceArn": "<SNS topic ARN>" } } } The following DenyAllProducersExceptSNSFromSending policy statement prevents other producers from sending messages to the queue. Replace <SQS queue ARN> and <SNS topic ARN> with your own information. { "Sid": "DenyAllProducersExceptSNSFromSending", "Effect": "Deny", "Principal": { "AWS": "*" }, Using policies 685 Amazon Simple Queue Service Developer Guide "Action": "sqs:SendMessage", "Resource": "<SQS queue ARN>", "Condition": { "ArnNotLike": { "aws:SourceArn": "<SNS topic ARN>" } } } (Optional) Restrict message reception to a specific VPC endpoint To restrict the receipt of messages to only a specific VPC endpoint, add the following policy statement to your Amazon SQS queue policy. This statement prevents a message consumer from receiving messages from the queue unless the messages are from the desired VPC endpoint. Replace <SQS queue ARN> with the ARN of the IAM role used to deploy the Amazon SQS queue; and <vpce_id> with the ID of the VPC endpoint. { "Sid": "DenyReceivingIfNotThroughVPCE", "Effect": "Deny", "Principal": "*", "Action": [ "sqs:ReceiveMessage" ], "Resource": "<SQS queue ARN>", "Condition": { "StringNotEquals": { "aws:sourceVpce": "<vpce id>" } } } Amazon SQS policy statements for the dead-letter queue Add the following policy statements, identified by their statement ID, to your DLQ access policy: • RestrictAdminQueueActions • DenyQueueActionsOutsideOrg • AllowConsumersToReceiveFromTheQueue Using policies 686 Amazon Simple Queue Service Developer Guide • DenyOtherConsumersFromReceiving • DenyUnsecureTransport In addition to adding the preceding policy statements to your DLQ access policy, you should also add a statement to restrict message transmission to Amazon SQS queues, as described in the following section. Restrict message transmission to Amazon SQS queues To restrict access to only Amazon SQS queues from the same account, add the following DenyAnyProducersExceptSQS policy statement to the DLQ queue policy. This statement doesn't limit message transmission to a specific queue because you need to deploy the DLQ before you create the main queue, so you won't know the Amazon SQS ARN when you create the DLQ. If you need to limit access to only one Amazon SQS queue, modify the aws:SourceArn in the Condition with the ARN of your Amazon SQS source queue when you know it. { "Sid": "DenyAnyProducersExceptSQS", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "sqs:SendMessage", "Resource": "<SQS DLQ ARN>", "Condition": { "ArnNotLike": { "aws:SourceArn": "arn:aws:sqs:<region>:<account-id>:*" } } } Important The Amazon SQS queue policies defined in this guide don't restrict the sqs:PurgeQueue action to a certain IAM role or roles. The sqs:PurgeQueue action enables you to delete all messages in the Amazon SQS queue. You can also use this action to make changes to the message format without replacing the Amazon SQS queue. When debugging an application, you can clear the Amazon SQS
sqs-dg-182
sqs-dg.pdf
182
of your Amazon SQS source queue when you know it. { "Sid": "DenyAnyProducersExceptSQS", "Effect": "Deny", "Principal": { "AWS": "*" }, "Action": "sqs:SendMessage", "Resource": "<SQS DLQ ARN>", "Condition": { "ArnNotLike": { "aws:SourceArn": "arn:aws:sqs:<region>:<account-id>:*" } } } Important The Amazon SQS queue policies defined in this guide don't restrict the sqs:PurgeQueue action to a certain IAM role or roles. The sqs:PurgeQueue action enables you to delete all messages in the Amazon SQS queue. You can also use this action to make changes to the message format without replacing the Amazon SQS queue. When debugging an application, you can clear the Amazon SQS queue to remove potentially erroneous messages. When testing the application, you can drive a high message volume through the Using policies 687 Amazon Simple Queue Service Developer Guide Amazon SQS queue and then purge the queue to start fresh before entering production. The reason for not restricting this action to a certain role is that this role might not be known when deploying the Amazon SQS queue. You will need to add this permission to the role’s identity-based policy to be able to purge the queue. Prevent the cross-service confused deputy problem The confused deputy problem is a security issue where an entity that doesn't have permission to perform an action can coerce a more privileged entity to perform the action. To prevent this, AWS provides tools that help you protect your account if you provide third parties (known as cross- account) or other AWS services (known as cross-service) access to resources in your account. The policy statements in this section can help you prevent the cross-service confused deputy problem. Cross-service impersonation can occur when one service (the calling service) calls another service (the called service). The calling service can be manipulated to use its permissions to act on another customer's resources in a way it shouldn’t otherwise have permission to access. To help protect against this issue, the resource-based policies defined in this post use the aws:SourceArn, aws:SourceAccount, and aws:PrincipalOrgID global IAM condition context keys. This limits the permissions that a service has to a specific resource, a specific account, or a specific organization in AWS Organizations. Use IAM Access Analyzer to review cross-account access You can use AWS IAM Access Analyzer to review your Amazon SQS queue policies and AWS KMS key policies and alert you when an Amazon SQS queue or a AWS KMS key grants access to an external entity. IAM Access Analyzer helps identify resources in your organization and accounts that are shared with an entity outside the zone of trust. This zone of trust can be an AWS account or the organization within AWS Organizations that you specify when you enable IAM Access Analyzer. IAM Access Analyzer identifies resources shared with external principals by using logic-based reasoning to analyze the resource-based policies in your AWS environment. For each instance of a resource shared outside of your zone of trust, Access Analyzer generates a finding. Findings include information about the access and the external principal granted to it. Review the findings to determine whether the access is intended and safe, or whether the access is unintended and a security risk. For any unintended access, review the affected policy and fix it. Refer to this blog post for more information on how AWS IAM Access Analyzer identifies unintended access to your AWS resources. Using policies 688 Amazon Simple Queue Service Developer Guide For more information on AWS IAM Access Analyzer, see the AWS IAM Access Analyzer documentation. Amazon SQS API permissions: Actions and resource reference When you set up Access control and write permissions policies that you can attach to an IAM identity, you can use the following table as a reference. The list includes each Amazon Simple Queue Service action, the corresponding actions for which you can grant permissions to perform the action, and the AWS resource for which you can grant the permissions. Specify the actions in the policy's Action field, and the resource value in the policy's Resource field. To specify an action, use the sqs: prefix followed by the action name (for example, sqs:CreateQueue). Currently, Amazon SQS supports the global condition context keys available in IAM. Amazon Simple Queue Service API and required permissions for actions AddPermission Action(s): sqs:AddPermission Resource: arn:aws:sqs:region:account_id:queue_name ChangeMessageVisibility Action(s): sqs:ChangeMessageVisibility Resource: arn:aws:sqs:region:account_id:queue_name ChangeMessageVisibilityBatch Action(s): sqs:ChangeMessageVisibilityBatch Resource: arn:aws:sqs:region:account_id:queue_name CreateQueue Action(s): sqs:CreateQueue Resource: arn:aws:sqs:region:account_id:queue_name DeleteMessage Action(s): sqs:DeleteMessage Resource: arn:aws:sqs:region:account_id:queue_name Using policies 689 Amazon Simple Queue Service DeleteMessageBatch Developer Guide Action(s): sqs:DeleteMessageBatch Resource: arn:aws:sqs:region:account_id:queue_name DeleteQueue Action(s): sqs:DeleteQueue Resource: arn:aws:sqs:region:account_id:queue_name GetQueueAttributes Action(s): sqs:GetQueueAttributes Resource: arn:aws:sqs:region:account_id:queue_name GetQueueUrl Action(s): sqs:GetQueueUrl Resource: arn:aws:sqs:region:account_id:queue_name ListDeadLetterSourceQueues Action(s): sqs:ListDeadLetterSourceQueues Resource: arn:aws:sqs:region:account_id:queue_name ListQueues Action(s): sqs:ListQueues Resource: arn:aws:sqs:region:account_id:queue_name ListQueueTags Action(s): sqs:ListQueueTags Resource: arn:aws:sqs:region:account_id:queue_name PurgeQueue Action(s): sqs:PurgeQueue Resource: arn:aws:sqs:region:account_id:queue_name ReceiveMessage Action(s): sqs:ReceiveMessage Using policies 690 Amazon Simple Queue Service Developer Guide Resource: arn:aws:sqs:region:account_id:queue_name RemovePermission Action(s): sqs:RemovePermission Resource: arn:aws:sqs:region:account_id:queue_name SendMessage and SendMessageBatch
sqs-dg-183
sqs-dg.pdf
183
required permissions for actions AddPermission Action(s): sqs:AddPermission Resource: arn:aws:sqs:region:account_id:queue_name ChangeMessageVisibility Action(s): sqs:ChangeMessageVisibility Resource: arn:aws:sqs:region:account_id:queue_name ChangeMessageVisibilityBatch Action(s): sqs:ChangeMessageVisibilityBatch Resource: arn:aws:sqs:region:account_id:queue_name CreateQueue Action(s): sqs:CreateQueue Resource: arn:aws:sqs:region:account_id:queue_name DeleteMessage Action(s): sqs:DeleteMessage Resource: arn:aws:sqs:region:account_id:queue_name Using policies 689 Amazon Simple Queue Service DeleteMessageBatch Developer Guide Action(s): sqs:DeleteMessageBatch Resource: arn:aws:sqs:region:account_id:queue_name DeleteQueue Action(s): sqs:DeleteQueue Resource: arn:aws:sqs:region:account_id:queue_name GetQueueAttributes Action(s): sqs:GetQueueAttributes Resource: arn:aws:sqs:region:account_id:queue_name GetQueueUrl Action(s): sqs:GetQueueUrl Resource: arn:aws:sqs:region:account_id:queue_name ListDeadLetterSourceQueues Action(s): sqs:ListDeadLetterSourceQueues Resource: arn:aws:sqs:region:account_id:queue_name ListQueues Action(s): sqs:ListQueues Resource: arn:aws:sqs:region:account_id:queue_name ListQueueTags Action(s): sqs:ListQueueTags Resource: arn:aws:sqs:region:account_id:queue_name PurgeQueue Action(s): sqs:PurgeQueue Resource: arn:aws:sqs:region:account_id:queue_name ReceiveMessage Action(s): sqs:ReceiveMessage Using policies 690 Amazon Simple Queue Service Developer Guide Resource: arn:aws:sqs:region:account_id:queue_name RemovePermission Action(s): sqs:RemovePermission Resource: arn:aws:sqs:region:account_id:queue_name SendMessage and SendMessageBatch Action(s): sqs:SendMessage Resource: arn:aws:sqs:region:account_id:queue_name SetQueueAttributes Action(s): sqs:SetQueueAttributes Resource: arn:aws:sqs:region:account_id:queue_name TagQueue Action(s): sqs:TagQueue Resource: arn:aws:sqs:region:account_id:queue_name UntagQueue Action(s): sqs:UntagQueue Resource: arn:aws:sqs:region:account_id:queue_name Logging and monitoring in Amazon SQS Amazon Simple Queue Service 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 Amazon SQS as events. The calls captured include calls from the Amazon SQS console and code calls to the Amazon SQS API operations. Using the information collected by CloudTrail, you can determine the request that was made to Amazon SQS, 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. Logging and monitoring 691 Amazon Simple Queue Service Developer Guide • 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. 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. Amazon CloudWatch Alarms Monitor a single metric over a time period you specify, and take one or more actions based on the metric's value relative to a defined threshold over several periods. For example, you can configure a CloudWatch alarm to send a notification to an Amazon SNS topic or trigger an action to send a message to an Amazon SQS queue. CloudWatch alarms don't perform actions simply because they are in a specific state; the state must change and remain in that state for a defined number of periods. For more information, see Creating CloudWatch alarms for Amazon SQS metrics and Creating alarms for dead-letter queues using Amazon CloudWatch. Amazon CloudWatch Logs Monitor, store, and access log files related to Amazon SQS by configuring your applications or Lambda functions that process messages to send logs to CloudWatch Logs. You can use these logs to analyze message processing, debug issues, and monitor the performance of your Amazon SQS workflows. For more information, see Logging Amazon Simple Queue Service API calls using AWS CloudTrail. Amazon CloudWatch Events Use Amazon CloudWatch Events to detect changes or specific events in your AWS environment and route them to an Amazon SQS queue. This allows you to capture event data, trigger workflows, or store events for processing later. Logging and monitoring 692 Amazon Simple Queue Service Developer Guide For more information, see Automating notifications from AWS services to Amazon SQS using Amazon EventBridge in this guide and EventBridge is the evolution of Amazon CloudWatch Events in the Amazon EventBridge User Guide. AWS CloudTrail Logs CloudTrail captures a detailed record of actions performed on Amazon SQS by users, roles, or AWS services. These logs let you track API calls, such as SendMessage, ReceiveMessage, or DeleteQueue, and provide key details such as who made the request, when it occurred, and the originating IP address. For more information, see Logging Amazon Simple Queue Service API calls using AWS CloudTrail. AWS Trusted Advisor Trusted Advisor uses best practices developed from serving AWS customers to help optimize your Amazon SQS usage. It reviews your Amazon SQS queues and provides actionable recommendations to enhance security, improve message processing reliability, and reduce costs. For example, it may suggest enabling dead-letter queues or to improve your queue access policies to ensure secure operations. For more information, see AWS Trusted Advisor in the Support User Guide. CloudTrail trails A trail enables CloudTrail to deliver log files to an Amazon S3 bucket. All trails created
sqs-dg-184
sqs-dg.pdf
184
see Logging Amazon Simple Queue Service API calls using AWS CloudTrail. AWS Trusted Advisor Trusted Advisor uses best practices developed from serving AWS customers to help optimize your Amazon SQS usage. It reviews your Amazon SQS queues and provides actionable recommendations to enhance security, improve message processing reliability, and reduce costs. For example, it may suggest enabling dead-letter queues or to improve your queue access policies to ensure secure operations. For more information, see AWS Trusted Advisor in the Support User Guide. 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 Logging and monitoring 693 Amazon Simple Queue Service Developer Guide 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. Logging Amazon Simple Queue Service API calls using AWS CloudTrail CloudTrail allows you to log and monitor Amazon SQS operations using two event types: data events and management events. This makes it easy to track and audit Amazon SQS activity in your account. Amazon SQS data events in CloudTrail Data events provide information about the resource operations performed on or in a resource (for example, sending messages to an Amazon SQS 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 Amazon SQS 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. To log Amazon SQS data events with CloudTrail, you must use advanced event selectors to configure the specific Amazon SQS resources or actions you want to log. Include the resource type AWS::SQS::Queue to capture queue-related actions. You can refine your logging preferences even further with using filters like eventName (such as SendMessage events). For more information, see AdvancedEventSelector in the CloudTrail API Reference. Logging API calls 694 Amazon Simple Queue Service Developer Guide Data event type (console) resources.type value Data APIs logged to CloudTrail Amazon SQS queue AWS::SQS::Queue • ChangeMessageVisibility • ChangeMessageVisib ilityBatch • DeleteMessage • DeleteMessageBatch • GetQueueAttributes • GetQueueUrl • ListDeadLetterSour ceQueues • ListQueues • ListQueueTags • ReceiveMessage • SendMessage • SendMessageBatch Use advanced event selectors to filter fields and log only important events. For more information about these fields, see AdvancedFieldSelector in the AWS CloudTrail API Reference. Amazon SQS 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. Amazon SQS logs the following control plane operations to CloudTrail as management events. • AddPermission • CancelMessageMoveTask • CreateQueue • DeleteQueue • ListMessageMoveTasks Logging API calls 695 Developer Guide Amazon Simple Queue Service • PurgeQueue • RemovePermission • SetQueueAttributes •
sqs-dg-185
sqs-dg.pdf
185
event selectors to filter fields and log only important events. For more information about these fields, see AdvancedFieldSelector in the AWS CloudTrail API Reference. Amazon SQS 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. Amazon SQS logs the following control plane operations to CloudTrail as management events. • AddPermission • CancelMessageMoveTask • CreateQueue • DeleteQueue • ListMessageMoveTasks Logging API calls 695 Developer Guide Amazon Simple Queue Service • PurgeQueue • RemovePermission • SetQueueAttributes • StartMessageMoveTask • TagQueue • UntagQueue Amazon SQS event example 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 SendMessage operation. { "eventVersion": "1.09", "userIdentity": { "type": "AssumedRole", "principalId": "EXAMPLE_PRINCIPAL_ID", "arn": "arn:aws:sts::123456789012:assumed-role/RoleToBeAssumed/SessionName", "accountId": "123456789012", "accessKeyId": "ACCESS_KEY_ID", "sessionContext": { "sessionIssuer": { "type": "Role", "principalId": "AKIAI44QH8DHBEXAMPLE", "arn": "arn:aws:sts::123456789012:assumed-role/RoleToBeAssumed", "accountId": "123456789012", "userName": "RoleToBeAssumed" }, "attributes": { "creationDate": "2023-11-07T22:13:06Z", "mfaAuthenticated": "false" } } }, "eventTime": "2023-11-07T23:59:11Z", "eventSource": "sqs.amazonaws.com", Logging API calls 696 Amazon Simple Queue Service Developer Guide "eventName": "SendMessage", "awsRegion": "ap-southeast-4", "sourceIPAddress": "10.0.118.80", "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": { "queueUrl": "https://sqs.ap-southeast-4.amazonaws.com/123456789012/MyQueue", "messageBody": "HIDDEN_DUE_TO_SECURITY_REASONS", "messageDeduplicationId": "MsgDedupIdSdk1ae1958f2-bbe8-4442-83e7-4916e3b035aa", "messageGroupId": "MsgGroupIdSdk16" }, "responseElements": { "mD5OfMessageBody": "9a4e3f7a614d9dd9f8722092dbda17a2", "mD5OfMessageSystemAttributes": "f88f0587f951b7f5551f18ae699c3a9d", "messageId": "93bb6e2d-1090-416c-81b0-31eb1faa8cd8", "sequenceNumber": "18881790870905840128" }, "requestID": "c4584600-fe8a-5aa3-a5ba-1bc42f055fae", "eventID": "98c735d8-70e0-4644-9432-b6ced4d791b1", "readOnly": false, "resources": [ { "accountId": "123456789012", "type": "AWS::SQS::Queue", "ARN": "arn:aws:sqs:ap-southeast-4:123456789012:MyQueue" } ], "eventType": "AwsApiCall", "managementEvent": false, "recipientAccountId": "123456789012", "eventCategory": "Data", "tlsDetails": { "tlsVersion": "TLSv1.2", "cipherSuite": "ECDHE-RSA-AES128-GCM-SHA256", "clientProvidedHostHeader": "sqs.ap-southeast-4.amazonaws.com" } Note The ListQueues operation is a unique case because it doesn’t act on a specific resource. As a result, the ARN field doesn’t include a queue name and uses a wildcard (*) instead. Logging API calls 697 Amazon Simple Queue Service Developer Guide For information about CloudTrail record contents, see CloudTrail record contents in the AWS CloudTrail User Guide. Monitoring Amazon SQS queues using CloudWatch Amazon SQS and Amazon CloudWatch are integrated so you can use CloudWatch to view and analyze metrics for your Amazon SQS queues. You can view and analyze your queues' metrics from the Amazon SQS console, the CloudWatch console, using the AWS CLI, or using the CloudWatch API. You can also set CloudWatch alarms for Amazon SQS metrics. CloudWatch metrics for your Amazon SQS queues are automatically collected and pushed to CloudWatch at one-minute intervals. These metrics are gathered on all queues that meet the CloudWatch guidelines for being active. CloudWatch considers a queue to be active for up to six hours if it contains any messages, or if any action accesses it. When an Amazon SQS queue is inactive for more than six hours, the Amazon SQS service is considered asleep and stops delivering metrics to the CloudWatch service. Missing data, or data representing zero, can't be visualized in the CloudWatch metrics for Amazon SQS for the time period that your Amazon SQS queue was inactive. Note • An Amazon SQS queue can be activated when the user calling an API against the queue is not authorized, and the request fails. • The Amazon SQS console performs a GetQueueAttributes API call when the queue’s page is opened. The GetQueueAttributes API request activates the queue. • A delay of up to 15 minutes occurs in CloudWatch metrics when a queue is activated from an inactive state. • There is no charge for the Amazon SQS metrics reported in CloudWatch. They're provided as part of the Amazon SQS service. • CloudWatch metrics are supported for both standard and FIFO queues. Accessing CloudWatch metrics for Amazon SQS Amazon SQS and Amazon CloudWatch are integrated so you can use CloudWatch to view and analyze metrics for your Amazon SQS queues. You can view and analyze your queues' metrics from Monitoring queues 698 Amazon Simple Queue Service Developer Guide the Amazon SQS console, the CloudWatch console, using the AWS CLI, or using the CloudWatch API. You can also set CloudWatch alarms for Amazon SQS metrics. Using the Amazon SQS console Use the Amazon SQS console to access and analyze metrics for up to 10 Amazon SQS queues. 1. 2. Sign in to the Amazon SQS console. In the list of queues, choose (check) the boxes for the queues that you want to access metrics for. You can show metrics for up to 10 queues. 3. Choose the Monitoring tab. Various graphs are displayed in the SQS metrics section. 4. To understand what a particular graph represents, hover over 5. 6. 7. next to the desired graph, or see Available CloudWatch metrics for
sqs-dg-186
sqs-dg.pdf
186
Amazon SQS metrics. Using the Amazon SQS console Use the Amazon SQS console to access and analyze metrics for up to 10 Amazon SQS queues. 1. 2. Sign in to the Amazon SQS console. In the list of queues, choose (check) the boxes for the queues that you want to access metrics for. You can show metrics for up to 10 queues. 3. Choose the Monitoring tab. Various graphs are displayed in the SQS metrics section. 4. To understand what a particular graph represents, hover over 5. 6. 7. next to the desired graph, or see Available CloudWatch metrics for Amazon SQS. To change the time range for all of the graphs at the same time, for Time Range, choose the desired time range (for example, Last Hour). To view additional statistics for an individual graph, choose the graph. In the CloudWatch Monitoring Details dialog box, select a Statistic, (for example, Sum). For a list of supported statistics, see Available CloudWatch metrics for Amazon SQS. 8. To change the time range and time interval that an individual graph displays (for example, to show a time range of the last 24 hours instead of the last 5 minutes, or to show a time period of every hour instead of every 5 minutes), with the graph's dialog box still displayed, for Time Range, choose the desired time range (for example, Last 24 Hours). For Period, choose the desired time period within the specified time range (for example, 1 Hour). When you're finished looking at the graph, choose Close. 9. (Optional) To work with additional CloudWatch features, on the Monitoring tab, choose View all CloudWatch metrics, and then follow the instructions in the Using the Amazon CloudWatch console procedure. Using the Amazon CloudWatch console Use the CloudWatch console to access and analyze Amazon SQS metrics. 1. Sign in to the CloudWatch console. Monitoring queues 699 Amazon Simple Queue Service Developer Guide 2. On the navigation panel, choose Metrics. 3. Select the SQS metric namespace. 4. Select the Queue Metrics metric dimension. 5. You can now examine your Amazon SQS metrics: • To sort the metrics, use the column heading. • To graph a metric, select the check box next to the metric. • To filter by metric, choose the metric name and then choose Add to search. Monitoring queues 700 Amazon Simple Queue Service Developer Guide For more information and additional options, see Graph Metrics and Using Amazon CloudWatch Dashboards in the Amazon CloudWatch User Guide. Using the AWS Command Line Interface To access Amazon SQS metrics using the AWS CLI, run the get-metric-statistics command. For more information, see Get Statistics for a Metric in the Amazon CloudWatch User Guide. Using the CloudWatch API To access Amazon SQS metrics using the CloudWatch API, use the GetMetricStatistics action. For more information, see Get Statistics for a Metric in the Amazon CloudWatch User Guide. Creating CloudWatch alarms for Amazon SQS metrics CloudWatch allows you trigger alarms when a metric reaches a specified threshold. For example, you can create an alarm for the NumberOfMessagesSent metric. For example, if more than 100 messages are sent to the MyQueue queue in 1 hour, an email notification is sent out. For more information, see Creating Amazon CloudWatch Alarms in the Amazon CloudWatch User Guide. Monitoring queues 701 Amazon Simple Queue Service Developer Guide 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 Create Alarm. 3. 4. In the Select Metric section of the Create Alarm dialog box, choose Browse Metrics, SQS. For SQS > Queue Metrics, choose the QueueName and Metric Name for which to set an alarm, and then choose Next. For a list of available metrics, see Available CloudWatch metrics for Amazon SQS. In the following example, the selection is for an alarm for the NumberOfMessagesSent metric for the MyQueue queue. The alarm triggers when the number of sent messages exceeds 100. 5. In the Define Alarm section of the Create Alarm dialog box, do the following: a. Under Alarm Threshold, type the Name and Description for the alarm. b. c. Set is to > 100. Set for to 1 out of 1 datapoints. d. Under Alarm preview, set Period to 1 Hour. e. f. Set Statistic to Standard, Sum. Under Actions, set Whenever this alarm to State is ALARM. If you want CloudWatch to send a notification when the alarm is triggered, select an existing Amazon SNS topic or choose New list and enter email addresses separated by commas. Note If you create a new Amazon SNS topic, the email addresses must be verified before they receive any notifications. If the alarm state changes before the email addresses are verified, the notifications aren't delivered. 6. Choose Create Alarm. The alarm is created. Monitoring
sqs-dg-187
sqs-dg.pdf
187
d. Under Alarm preview, set Period to 1 Hour. e. f. Set Statistic to Standard, Sum. Under Actions, set Whenever this alarm to State is ALARM. If you want CloudWatch to send a notification when the alarm is triggered, select an existing Amazon SNS topic or choose New list and enter email addresses separated by commas. Note If you create a new Amazon SNS topic, the email addresses must be verified before they receive any notifications. If the alarm state changes before the email addresses are verified, the notifications aren't delivered. 6. Choose Create Alarm. The alarm is created. Monitoring queues 702 Amazon Simple Queue Service Developer Guide Available CloudWatch metrics for Amazon SQS Amazon SQS sends the following metrics to CloudWatch. Note For some metrics, the result is approximate because of the distributed architecture of Amazon SQS. In most cases, the count should be close to the actual number of messages in the queue. Amazon SQS metrics Amazon SQS automatically publishes operational metrics to Amazon CloudWatch under the AWS/SQS namespace. These metrics help you monitor queue health and performance. Due to SQS’s distributed nature, many values are approximate, but accurate enough for most operational decisions. Note • All metrics emit non-negative values only when the queue is active. • Some metrics (such as SentMessageSize) are not emitted until at least one message is sent. Metric Description Units Seconds Approxima teAgeOfOl destMessa ge The age of the oldest unprocessed message in the queue. Reporting behavior Reported if the queue contains at least one active message. Key notes • For standard queues, if a message is received three or more times and not deleted, SQS moves it to the back of the queue. The metric then reflects the age of the next message that hasn’t exceeded the receive threshold. This reordering Monitoring queues 703 Amazon Simple Queue Service Developer Guide Metric Description Units Reporting behavior Key notes occurs even when a redrive policy is in place. • Poison-pill messages (those repeatedly received but never deleted) are excluded from this metric until successfully processed. • When a message is moved to a DLQ after exceeding the maxReceiveCount , the age resets. In that case, the DLQ’s metric reflects the time the message was moved—not when it was originally sent. • FIFO queues don't reorder messages to preserve order. A failed message blocks its message group until it's deleted or expires. If a DLQ is configured, the message is sent there after the receive threshold is met. Monitoring queues 704 Amazon Simple Queue Service Developer Guide Metric Description Units Approxima teNumberO For FIFO only. The fGroupsWi number of thInfligh message Count tMessages groups with one or more in-flight messages. Reporting behavior Reported if the FIFO queue is active. Approxima teNumberO The number of messages fMessages in the queue Delayed that are Count delayed and not immediately available for retrieval. Reported if delayed messages exist in the queue. Key notes • A message is considered in-flight after it’s received from the queue by a consumer but not yet deleted or expired. • This metric helps you troubleshoot and optimize FIFO queue throughput. High values usually indicate strong concurrency. • If the queue has a large backlog and this value remains low, consider scaling consumers or increasing the number of active message groups. • For throughput and in- flight limits, see Amazon SQS quotas. • Applies to queues configure d with a default delay and to individual messages sent with a DelaySeconds parameter. • Delayed messages remain hidden from consumers until their delay period expires, which can affect perceived queue backlog or throughput. Monitoring queues 705 Amazon Simple Queue Service Developer Guide Metric Description Units Count Approxima teNumberO fMessages NotVisibl e The number of in-flight messages that have been received but not yet deleted or expired. Reporting behavior Reported if in-flight messages exist. Key notes • Messages enter the in- flight state after being sent to a consumer via the ReceiveMessage API. • These messages are temporarily hidden from other consumers during the visibility timeout window. • Use this metric to track message processing delays or stuck consumers. Approxima teNumberO The number of messages fMessages currently Count Reported if the queue is • Reflects the current processing backlog in the active. queue. Visible available for retrieval and processing. • There's no hard limit on how many messages can accumulate, but they are subject to the queue’s configured retention period. • A consistently high value may indicate under-pro visioned consumers or stuck processing logic. Monitoring queues 706 Amazon Simple Queue Service Developer Guide Metric Description Units NumberOfE mptyRecei ves ¹ Count The number of ReceiveMe ssage API calls that returned no messages. NumberOfD eduplicat edSentMes sages Count For FIFO only. The number of sent messages that were deduplica ted and not added to the queue. Reporting
sqs-dg-188
sqs-dg.pdf
188
current processing backlog in the active. queue. Visible available for retrieval and processing. • There's no hard limit on how many messages can accumulate, but they are subject to the queue’s configured retention period. • A consistently high value may indicate under-pro visioned consumers or stuck processing logic. Monitoring queues 706 Amazon Simple Queue Service Developer Guide Metric Description Units NumberOfE mptyRecei ves ¹ Count The number of ReceiveMe ssage API calls that returned no messages. NumberOfD eduplicat edSentMes sages Count For FIFO only. The number of sent messages that were deduplica ted and not added to the queue. Reporting behavior Reported during receive Key notes • This metric can help identify inefficiencies in polling behavior or operations. underutilized consumer instances. • High values may occur when the queue is empty, the consumer uses short polling, or messages are being processed faster than they are produced. • This isn't a precise indicator of queue state. It reflects service-side behavior and may include retries. Reported if duplicate MessageDe duplicati onId values or content are detected. • SQS deduplicates messages based on the MessageDe duplicationId content-based hashing (if or enabled). • A high value may indicate that a producer is repeatedl y sending the same message within the 5- minute deduplication window. • Use this metric to troublesh oot redundant producer logic or confirm that deduplication is functioning as intended. Monitoring queues 707 Amazon Simple Queue Service Developer Guide Metric Description Units Reporting behavior Key notes NumberOfM essagesDe leted ¹ Count The number of messages successfully deleted from the queue. Reported for each delete • This metric counts all successful delete operation request s—even if the same with a valid message is deleted more receipt handle. than once. • Common reasons for higher-than-expected values include: • Multiple deletes of the same message using different receipt handles, after visibility timeout expires and the message is received again. • Duplicate deletes using the same receipt handle, which still return a success status and increment the metric. • Use this metric to track message processing success, but don't treat it as an exact count of unique deleted messages. Monitoring queues 708 Amazon Simple Queue Service Developer Guide Metric Description Units NumberOfM essagesRe ceived ¹ Count The number of messages returned by the ReceiveMe ssage API. Reporting behavior Reported during receive Key notes • This includes all messages returned to consumers, including those that are operations. later returned to the queue due to visibility timeout expiration. • A single message can be received multiple times if it isn’t deleted, which can cause this metric to exceed the number of messages sent. • Use this to track consumer activity, but don't treat it as a count of unique messages processed. Monitoring queues 709 Amazon Simple Queue Service Developer Guide Metric Description Units NumberOfM essagesSe nt ¹ Count The number of messages successfully added to a queue. Reporting behavior Reported for each successful manual send. Key notes • Manual calls to SendMessa ge or SendMessa geBatch are counted, including those targeting a DLQ directly. • Messages that are automatically moved to a DLQ after exceeding the maxReceiveCount are not included in this metric. • As a result, NumberOfM essagesSent may be lower than NumberOfM essagesReceived — especially if redrive policies are moving many messages to DLQs behind the scenes. SentMessa geSize ¹ Bytes The size of messages successfully sent to the queue. Not emitted until at least • This metric will not appear in the CloudWatch console one message until the queue receives its is sent. first message. • Use this metric to track the size of each message in bytes. This is useful for analyzing payload trends or estimating throughput cost. • The maximum message size for SQS is 256 KB. Monitoring queues 710 Amazon Simple Queue Service Developer Guide ¹ These metrics reflect system-level activity and may include retries, duplicates, or delayed messages. Don’t use raw counts to estimate real-time queue state without factoring in message lifecycle behavior. Dead-letter queues (DLQs) and CloudWatch metrics When working with DLQs, it's important to understand how Amazon SQS metrics behave: • NumberOfMessagesSent – This metric behaves differently for DLQs: • Manual Sending – Messages manually sent to a DLQ are captured by this metric. • Automatic Redrive – Messages automatically moved to a DLQ due to processing failures are not captured by this metric. As a result, the NumberOfMessagesSent and NumberOfMessagesReceived metrics may show discrepancies for DLQs. • Recommended Metric for DLQs – To monitor the state of a DLQ, use the ApproximateNumberOfMessagesVisible metric. This metric indicates the number of messages currently available for processing in the DLQ. Dimensions for Amazon SQS metrics Amazon SQS metrics in CloudWatch use a single dimension: QueueName. All metric data is grouped and filtered by the name of the queue. Monitoring tips Monitor
sqs-dg-189
sqs-dg.pdf
189
are captured by this metric. • Automatic Redrive – Messages automatically moved to a DLQ due to processing failures are not captured by this metric. As a result, the NumberOfMessagesSent and NumberOfMessagesReceived metrics may show discrepancies for DLQs. • Recommended Metric for DLQs – To monitor the state of a DLQ, use the ApproximateNumberOfMessagesVisible metric. This metric indicates the number of messages currently available for processing in the DLQ. Dimensions for Amazon SQS metrics Amazon SQS metrics in CloudWatch use a single dimension: QueueName. All metric data is grouped and filtered by the name of the queue. Monitoring tips Monitor SQS effectively using key metrics and CloudWatch alarms to detect queue backlogs, optimize performance, and stay within service limits. • Set CloudWatch alarms based on ApproximateNumberOfMessagesVisible to catch backlog growth. • Monitor NumberOfEmptyReceives to tune poll frequency and reduce API cost. • Use ApproximateNumberOfGroupsWithInflightMessages in FIFO queues to diagnose throughput limits. • Review SQS quotas to understand metric thresholds and service limits. Monitoring queues 711 Amazon Simple Queue Service Developer Guide Compliance validation for Amazon SQS 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 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. Compliance validation 712 Amazon Simple Queue Service Developer Guide • 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 SQS The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between zones without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure. In addition to the AWS global infrastructure, Amazon SQS offers distributed queues. Distributed queues There are three main parts in a distributed messaging system: the components of your distributed system, your queue (distributed on Amazon SQS servers), and the messages in the queue. In the following scenario, your system has several producers (components that send messages to the queue) and consumers (components that receive messages from the queue). The queue (which holds messages A through E) redundantly stores the messages across multiple Amazon SQS servers. Resilience 713 Amazon Simple Queue Service Developer Guide Infrastructure security in Amazon SQS As a managed service, Amazon SQS is protected by the AWS global network security procedures described in the Amazon Web Services: Overview of Security Processes whitepaper. You use AWS published API actions to access Amazon SQS 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
sqs-dg-190
sqs-dg.pdf
190
from the queue). The queue (which holds messages A through E) redundantly stores the messages across multiple Amazon SQS servers. Resilience 713 Amazon Simple Queue Service Developer Guide Infrastructure security in Amazon SQS As a managed service, Amazon SQS is protected by the AWS global network security procedures described in the Amazon Web Services: Overview of Security Processes whitepaper. You use AWS published API actions to access Amazon SQS 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 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 SQS supports resource- based access policies, which can include restrictions based on the source IP address. You can also use Amazon SQS policies to control access from specific Amazon VPC endpoints or specific VPCs. This effectively isolates network access to a given Amazon SQS queue from only the specific VPC within the AWS network. For more information, see Example 5: Deny access if it isn't from a VPC endpoint. Amazon SQS security best practices AWS provides many security features for Amazon SQS, which you should review in the context of your own security policy. The following are preventative security best practices for Amazon SQS. Note The specific implementation guidance provided is for common use cases and implementations. We suggest that you view these best practices in the context of your specific use case, architecture, and threat model. Make sure that queues aren't publicly accessible Unless you explicitly require anyone on the internet to be able to read or write to your Amazon SQS queue, you should make sure that your queue isn't publicly accessible (accessible by everyone in the world or by any authenticated AWS user). Infrastructure security 714 Amazon Simple Queue Service Developer Guide • 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 queues the permissions are for, and specific API actions that you want to allow for these queues. Implementing least privilege is important to reducing security risks and reducing the 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 this using a combination of security policies. Amazon SQS uses the producer-consumer model, requiring three types of user account access: • Administrators – Access to creating, modifying, and deleting queues. Administrators also control queue policies. • Producers – Access to sending messages to queues. • Consumers – Access to receiving and deleting messages from queues. For more information, see the following sections: • Identity and access management in Amazon SQS • Amazon SQS API permissions: Actions and resource reference • Using custom policies with the Amazon SQS Access Policy Language Use IAM roles for applications and AWS services which require Amazon SQS access For applications or AWS services such as Amazon EC2 to access Amazon SQS queues, 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 SQS. When you use a role, you don't have to distribute long-term credentials (such as a username, password, and access keys) to an EC2 instance or AWS service such as AWS Implement least-privilege access 715 Amazon Simple Queue Service Developer Guide 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 SQS 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. As long as you authenticate your request and have access permissions, there is no difference between accessing encrypted and unencrypted queues. For more information, see Encryption at rest in Amazon SQS and Amazon SQS Key management. Enforce encryption of data in
sqs-dg-191
sqs-dg.pdf
191
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 SQS 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. As long as you authenticate your request and have access permissions, there is no difference between accessing encrypted and unencrypted queues. For more information, see Encryption at rest in Amazon SQS and Amazon SQS Key management. Enforce encryption of data in transit Without HTTPS (TLS), a network-based attacker can eavesdrop on network traffic or manipulate it, using an attack such as man-in-the-middle. Allow only encrypted connections over HTTPS (TLS) using the aws:SecureTransport condition in the queue policy to force requests to use SSL. Consider using VPC endpoints to access Amazon SQS If you have queues that you must be able to interact with but which must absolutely not be exposed to the internet, use VPC endpoints to queue access to only the hosts within a particular VPC. You can use queue policies to control access to queues from specific Amazon VPC endpoints or from specific VPCs. Amazon SQS 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 queue using a queue policy. For more information, see Amazon Virtual Private Cloud endpoints for Amazon SQS and Creating an Amazon VPC endpoint policy for Amazon SQS. Implement server-side encryption 716 Amazon Simple Queue Service Developer Guide Related Amazon SQS resources The following table lists related resources that you might find useful as you work with this service. Resource Description Amazon Simple Queue Service API Reference Descriptions of actions, parameters, and data types and a list of errors that the service returns. Amazon SQS in the AWS CLI Command Reference Descriptions of the AWS CLI commands that you can use to work with queues. Regions and Endpoints Information about Amazon SQS regions and endpoints Product Page Discussion Forum AWS Premium Support Information The primary web page for information about Amazon SQS. A community-based forum for developers to discuss technical questions related to Amazon SQS. The primary web page for information about AWS Premium Support, a one-on-one, fast-response support channel to help you build and run applications on AWS infrastructure services. 717 Amazon Simple Queue Service Developer Guide Documentation history The following table describes the important changes to the Amazon Simple Queue Service Developer Guide since Jan 2019. For notifications about updates to this documentation, subscribe to the RSS feed. 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 SQS now supports dual-stack (IPv4 and IPv6) April 17, 2025 endpoints, allowing queues to be accessed via both IP protocols. CloudTrail integration for all Amazon SQS APIs CloudTrail integration added for all Amazon SQS APIs. January 10, 2025 SQSUnlockQueuePolicy November 15, 2024 Amazon SQS added a new AWS-managed policy called SQSUnlockQueuePolicy to unlock a queue and remove a misconfigured queue policy that denies all principals from accessing an Amazon SQS queue. AWSkms:Decrypt Amazon SQS no longer July 24, 2024 requires the kms:Decry pt permission for the SendMessage API. Customers now only need the 718 Amazon Simple Queue Service Developer Guide kms:GenerateDataKey permission on the KMS key used to encrypt the queue, but still need kms:Decrypt permission to call ReceiveMe ssage . FIFO metrics update Support for NumberOfD July 3, 2024 eduplicatedSentMes sages and Approxima teNumberOfGroupsWi thInflightMessages added to Amazon SQS FIFO metrics. ListQueueTags action supported in the AmazonSQS The AmazonSQSReadOnlyA ccess managed policy May 2, 2024 ReadOnlyAccess managed policy supports ListQueueTags to retrieve all tags associated with a specified Amazon SQS queue. AWSJSON protocol Make API requests using AWS JSON protocol. July 27, 2023 New section describing AWS managed policies for Amazon Amazon SQS added a new action that allows you to list June 7, 2023 SQS and updates to these the most recent message policies Dead-letter queue redrive using APIs movement tasks (up to 10) under a specific source queue. This action is associated with the ListMessageMoveTas ks API operation. Configure dead-letter queue redrives using Amazon SQS APIs. June 7, 2023 719 Amazon Simple Queue Service ABAC for Amazon SQS Developer Guide November 10, 2022 Attribute-based access control (ABAC) using queue tags for
sqs-dg-192
sqs-dg.pdf
192
Make API requests using AWS JSON protocol. July 27, 2023 New section describing AWS managed policies for Amazon Amazon SQS added a new action that allows you to list June 7, 2023 SQS and updates to these the most recent message policies Dead-letter queue redrive using APIs movement tasks (up to 10) under a specific source queue. This action is associated with the ListMessageMoveTas ks API operation. Configure dead-letter queue redrives using Amazon SQS APIs. June 7, 2023 719 Amazon Simple Queue Service ABAC for Amazon SQS Developer Guide November 10, 2022 Attribute-based access control (ABAC) using queue tags for flexible and scalable access permissions. FIFO high throughput limit increases Increased default quotas for FIFO high throughput October 20, 2022 mode in commercial Regions, plus FIFO high throughput document optimization. Default server-side encryptio n (SSE) is available Server-side encryption (SSE) using SQS-owned encryption September 26, 2022 (SSE-SQS) by default. Amazon SQS confused deputy protection support is Confused deputy protectio n allows you to specify new December 29, 2021 available Managed SSE is available Dead-letter queue redrive is available headers in their requests, which are checked against conditions in the KMS policy when using Amazon SQS managed SSE. Amazon SQS managed SSE (SSE-SQS) is managed server-side encryption that uses Amazon SQS-owned encryption keys to protect sensitive data sent over message queues. Amazon SQS supports dead- letter queue redrive for standard queues. November 23, 2021 November 10, 2021 720 Amazon Simple Queue Service Developer Guide High throughput for messages in FIFO queues is High throughput for Amazon SQS FIFO queues provides a May 27, 2021 available higher number of transacti ons per second (TPS) for messages in FIFO queues. For information on throughput quotas, see Quotas related to messages. High throughput for messages in FIFO queues is High throughput for Amazon SQS FIFO queues is in preview December 17, 2020 available in preview release release and is subject to change. This feature provides a higher number of transacti ons per second (TPS) for messages in FIFO queues. For information on throughput quotas, see Quotas related to messages. New Amazon SQS console design To simplify development and production workflows, the July 8, 2020 Amazon SQS console has a new user experience. Amazon SQS supports pagination for listQueues and You can specify the maximum number of results to return June 22, 2020 listDeadLetterSourceQueues from a listQueues or listDeadL etterSourceQueues request. Amazon SQS supports 1- minute Amazon CloudWatc h metrics in all AWS Regions, except the AWS GovCloud (US) Regions The one-minute CloudWatc h metric for Amazon SQS is available in all Regions, except the AWS GovCloud (US) Regions. January 9, 2020 721 Amazon Simple Queue Service Developer Guide Amazon SQS supports 1- minute CloudWatch metrics The one-minute CloudWatc h metric for Amazon SQS is November 25, 2019 currently available only in the following Regions: US East (Ohio), Europe (Ireland), Europe (Stockholm), and Asia Pacific (Tokyo). AWS Lambda triggers for Amazon SQS FIFO queues are You can configure messages arriving in a FIFO queue as a available Lambda function trigger. November 25, 2019 Server-side encryption (SSE) for Amazon SQS is available in the China Regions SSE for Amazon SQS is available in the China Regions. November 13, 2019 FIFO queues are available in the Middle East (Bahrain) FIFO queues are available in the Middle East (Bahrain) October 10, 2019 Region Region. Amazon Virtual Private Cloud (Amazon VPC) endpoints for You can send messages to your Amazon SQS queues Amazon SQS are available in from Amazon VPC in the AWS the AWS GovCloud (US-East) GovCloud (US-East) and AWS and AWS GovCloud (US-West) GovCloud (US-West) Regions. Regions September 5, 2019 722 Amazon Simple Queue Service Developer Guide Amazon SQS allows troublesh ooting of queues using AWS You can troubleshoot messages passing through X-Ray using message system Amazon SQS queues August 28, 2019 attributes You can tag Amazon SQS queues upon creation using X-Ray. This release adds the MessageSy stemAttribute parameter (which lets you request send X-Ray trace headers through Amazon SQS) to the SendMessage and SendMessageBatch API operations, the AWSTraceH eader attribute to the ReceiveMessage API operation, and the MessageSystemAttri buteValue data type. You can use a single Amazon SQS API call, AWS SDK function, or AWS Command Line Interface (AWS CLI) command to simultaneously create a queue and specify its tags. In addition, Amazon SQS supports the aws:TagKe ys and aws:RequestTag AWS Identity and Access Management (IAM) keys. August 22, 2019 723 Amazon Simple Queue Service Developer Guide The temporary queue client for Amazon SQS is now Temporary queues help you save development time and July 25, 2019 available deployment costs when using common message patterns such as request-response. You can use the Temporary Queue Client to create high-throughput, cost-effe ctive, application-managed temporary queues. SSE for Amazon SQS is available in the AWS Server-side encryption (SSE)
sqs-dg-193
sqs-dg.pdf
193
Command Line Interface (AWS CLI) command to simultaneously create a queue and specify its tags. In addition, Amazon SQS supports the aws:TagKe ys and aws:RequestTag AWS Identity and Access Management (IAM) keys. August 22, 2019 723 Amazon Simple Queue Service Developer Guide The temporary queue client for Amazon SQS is now Temporary queues help you save development time and July 25, 2019 available deployment costs when using common message patterns such as request-response. You can use the Temporary Queue Client to create high-throughput, cost-effe ctive, application-managed temporary queues. SSE for Amazon SQS is available in the AWS Server-side encryption (SSE) for Amazon SQS is available June 20, 2019 GovCloud (US-East) Region in the AWS GovCloud (US- East) Region. FIFO queues are available in the Asia Pacific (Hong FIFO queues are available in the Asia Pacific (Hong May 15, 2019 Kong), China (Beijing), AWS Kong), China (Beijing), AWS GovCloud (US-East), and AWS GovCloud (US-East), and AWS GovCloud (US-West) Regions GovCloud (US-West) Regions. Amazon VPC endpoint policies are available for You can create Amazon VPC endpoint policies for Amazon April 4, 2019 Amazon SQS SQS. FIFO queues are available in the Europe (Stockholm) and China (Ningxia) Regions FIFO queues are available in the Europe (Stockholm) and China (Ningxia) Regions. March 14, 2019 724 Amazon Simple Queue Service Developer Guide FIFO queues are available in all Regions where Amazon FIFO queues are available in the US East (Ohio), US East SQS is available (N. Virginia), US West (N. February 7, 2019 California), US West (Oregon), Asia Pacific (Mumbai), Asia Pacific (Seoul), Asia Pacific (Singapore), Asia Pacific (Sydney), Asia Pacific (Tokyo), Canada (Central), Europe (Frankfurt), Europe (Ireland) , Europe (London), Europe (Paris), and South America (São Paulo) Regions. 725
ssm-sap-001
ssm-sap.pdf
1
User Guide AWS Systems Manager for SAP Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. AWS Systems Manager for SAP User Guide AWS Systems Manager for SAP: 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 Systems Manager for SAP Table of Contents User Guide What is AWS Systems Manager for SAP? ....................................................................................... 1 Features .......................................................................................................................................................... 1 Supported Regions ....................................................................................................................................... 1 Related services ............................................................................................................................................ 2 Pricing ............................................................................................................................................................. 2 Setting up ........................................................................................................................................ 3 Sign up for AWS ........................................................................................................................................... 3 Create an IAM user ....................................................................................................................................... 3 Get started ....................................................................................................................................... 5 Attach permissions for Amazon EC2 ........................................................................................................ 5 Amazon EC2 tag ........................................................................................................................................... 5 Register credentials in AWS Secrets Manager ........................................................................................ 6 Verify SSM Agent ......................................................................................................................................... 7 Verify setup .................................................................................................................................................... 8 Backup and restore – optional ................................................................................................................... 8 Set up permissions for backup and restore ....................................................................................... 9 Install AWS Backint Agent .................................................................................................................. 10 Tutorials ......................................................................................................................................... 11 AWS CLI ........................................................................................................................................................ 11 Register SAP HANA database ............................................................................................................. 11 Register SAP ABAP application .......................................................................................................... 19 Start SAP application ........................................................................................................................... 24 Stop SAP application ........................................................................................................................... 28 Refresh SAP application ...................................................................................................................... 32 Deregister SAP application ................................................................................................................. 34 AWS Management Console ...................................................................................................................... 35 Register SAP HANA database ............................................................................................................. 35 Register SAP ABAP application .......................................................................................................... 38 Start SAP application ........................................................................................................................... 41 Stop SAP application ........................................................................................................................... 41 Supported versions ........................................................................................................................ 43 Operating systems ..................................................................................................................................... 43 Databases ..................................................................................................................................................... 43 SAP applications ......................................................................................................................................... 44 iii AWS Systems Manager for SAP User Guide Security .......................................................................................................................................... 45 AWS managed policies .............................................................................................................................. 45 AWSSystemsManagerForSAPFullAccess ............................................................................................ 46 AWSSystemsManagerForSAPReadOnlyAccess ................................................................................. 47 Policy updates ....................................................................................................................................... 48 Using service linked roles ......................................................................................................................... 51 Service-linked role permissions for Systems Manager for SAP ................................................... 51 Creating a service-linked role for Systems Manager for SAP ...................................................... 61 Editing a service-linked role for Systems Manager for SAP ......................................................... 61 Deleting a service-linked role for Systems Manager for SAP ...................................................... 61 Supported Regions for Systems Manager for SAP service-linked roles ..................................... 62 Monitoring ...................................................................................................................................... 63 Monitoring AWS Systems Manager for SAP events using EventBridge ........................................... 63 Monitor events using EventBridge .................................................................................................... 63 Example ................................................................................................................................................... 66 AWS Systems Manager for SAP metrics with Amazon CloudWatch ................................................ 66 Log API calls using CloudTrail ................................................................................................................. 67 Quotas ............................................................................................................................................ 69 Troubleshooting ............................................................................................................................. 70 Database registration failure ................................................................................................................... 70 InvalidInstanceIdException ....................................................................................................................... 71 AccessDeniedException ............................................................................................................................. 71 ResourceNotFoundException .................................................................................................................... 72 Invalid control character ........................................................................................................................... 72 Expecting ',' delimiter ................................................................................................................................ 73 Maximum limit of resources .................................................................................................................... 73 Unauthorized user ...................................................................................................................................... 73 REFRESH_FAILED; Database connection mismatch ............................................................................. 74 Unsupported setup .................................................................................................................................... 74 Input parameter errors ............................................................................................................................. 74 Application status: FAILED ....................................................................................................................... 75 StartApplication AccessDeniedException .............................................................................................. 75 StartApplication ConflictException ......................................................................................................... 76 StartApplication ValidationException .................................................................................................... 76 StopApplication AccessDeniedException ............................................................................................... 76 StopApplication ConflictException ......................................................................................................... 77 iv AWS Systems Manager for SAP User Guide StopApplication ValidationException ..................................................................................................... 77 Unsupported sslenforce setup ........................................................................................................... 78 Document history .......................................................................................................................... 79 v AWS Systems Manager for SAP User Guide What is AWS Systems Manager for SAP? AWS Systems Manager for SAP is an automation capability to manage and operate your SAP applications on AWS. It provides a seamless integration between AWS services and SAP applications running on AWS. Systems Manager for SAP is available to use with AWS APIs. For more information, see Systems Manager for SAP API Reference Guide. With Systems Manager for SAP, you can backup and restore SAP HANA databases on Amazon EC2 with AWS Backup. For more information, see Get Started. Topics • Features • Supported Regions • Related services • Pricing Features AWS Systems Manager for SAP provides the following features for your SAP workloads running on Amazon EC2. • Register and discover SAP applications • List discovered SAP applications • List configurations of discovered SAP applications • Integration with AWS Backup – using https://console.aws.amazon.com/backup, enable automatic backup and restore operations of SAP HANA databases. Supported Regions AWS Systems Manager for SAP is available in all commercial AWS Regions. For more information, see Systems Manager for SAP endpoints and quotas. Features 1 AWS Systems Manager for SAP User Guide Note Supported services by AWS Region contains the currently supported Regions where SAP HANA database backups on Amazon EC2 instances are available. Related services The following services are related to AWS Systems Manager for SAP on AWS. • AWS Backup • SAP HANA on AWS • AWS Backint Agent for SAP HANA Pricing AWS Systems Manager for SAP is available to you at no additional cost. You only pay for the AWS resources that you provision to manage and
ssm-sap-002
ssm-sap.pdf
2
Regions. For more information, see Systems Manager for SAP endpoints and quotas. Features 1 AWS Systems Manager for SAP User Guide Note Supported services by AWS Region contains the currently supported Regions where SAP HANA database backups on Amazon EC2 instances are available. Related services The following services are related to AWS Systems Manager for SAP on AWS. • AWS Backup • SAP HANA on AWS • AWS Backint Agent for SAP HANA Pricing AWS Systems Manager for SAP is available to you at no additional cost. You only pay for the AWS resources that you provision to manage and operate your SAP environments. Related services 2 AWS Systems Manager for SAP User Guide Setting up Systems Manager for SAP If you are new to AWS, begin with the following topics. When you sign up for AWS, your AWS account is automatically signed up for all services in AWS, including Systems Manager for SAP. Topics • Sign up for AWS • Create an IAM user Sign up for AWS 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. Create an IAM user To create an administrator user, choose one of the following options. Sign up for AWS 3 AWS Systems Manager for SAP User Guide To By You can also Choose one way to manage your administr ator In IAM Identity Use short-term credentials to access Following the instructions in Getting started in the Configure programmatic access by Configuring the Center AWS. AWS IAM Identity Center AWS CLI to use AWS IAM (Recommen ded) This aligns with the security best practices User Guide. Identity Center in the AWS Command Line Interface User Guide. . For information about best practices , see Security best practices in IAM in the IAM User Guide. In IAM (Not Use long-term credentials to access Following the instructions in Create an IAM user for Configure programmatic access by Manage access keys AWS. emergency access in the for IAM users in the IAM User recommend ed) IAM User Guide. Guide. Create an IAM user 4 AWS Systems Manager for SAP User Guide Get started with AWS Systems Manager for SAP To get started with using AWS Systems Manager for SAP, ensure that you complete the following prerequisites for setup. You must run these steps on all Amazon EC2 instances in your setup. Prerequisites • Attach Systems Manager for SAP permissions to Amazon EC2 instance running SAP HANA database • Amazon EC2 tag • Register SAP HANA database credentials in AWS Secrets Manager • Verify AWS Systems Manager Agent (SSM Agent) is running • Verify setup before registering your SAP HANA database • Backup and restore – optional Attach Systems Manager for SAP permissions to Amazon EC2 instance running SAP HANA database AWS Systems Manager for SAP communicates with the Amazon EC2 instance where your SAP HANA database running via policies. Attach the following IAM policies to the IAM role used by your Amazon EC2 instance. • AmazonSSMManagedInstanceCore – this Amazon managed policy allows an instance to use Systems Manager service core functionality. For more information, see About policies for a Systems Manager instance profile. • AWSSystemsManagerForSAPFullAccess – this Amazon managed policy grants full access to AWS Systems Manager for SAP. For more information, see AWS managed policy: AWSSystemsManagerForSAPFullAccess. Amazon EC2 tag SSMForSAPManaged – add this tag on your Amazon EC2 instance to enable AWS Systems Manager for SAP to access your Amazon EC2 instance. Attach permissions for Amazon EC2 5 AWS Systems Manager for SAP User Guide Key Value SSMForSAPManaged True Register SAP HANA database credentials in AWS Secrets Manager You must create a secret with the username and password of a database. A separate secret is required for each one of your databases running on an Amazon EC2 instance. The following special characters are not allowed in a SAP HANA password: • angle brackets (<>) • backslashes (/) • double quotes (") • pipelines (|) • question marks (?) • semicolons (;) Use the following steps to register your SAP HANA database credentials in AWS Secrets Manager. 1. Sign in to https://console.aws.amazon.com/secretsmanager/. 2. On the AWS Secrets Manager page, select Store a new secret. 3. For Secret type, select Other type of secret and create the following key value pairs. Key username
ssm-sap-003
ssm-sap.pdf
3
A separate secret is required for each one of your databases running on an Amazon EC2 instance. The following special characters are not allowed in a SAP HANA password: • angle brackets (<>) • backslashes (/) • double quotes (") • pipelines (|) • question marks (?) • semicolons (;) Use the following steps to register your SAP HANA database credentials in AWS Secrets Manager. 1. Sign in to https://console.aws.amazon.com/secretsmanager/. 2. On the AWS Secrets Manager page, select Store a new secret. 3. For Secret type, select Other type of secret and create the following key value pairs. Key username password Value example_SAP_HANA_db_username example_SAP_HANA_db_password 4. 5. Select Next and enter a Secret name. Note this Secret name for use while following the steps in the section called “Register SAP HANA database”. In the Resource permissions container, choose Edit permissions, and paste the following policy with your Amazon Resource Name for the Amazon EC2 instance role. Register credentials in AWS Secrets Manager 6 AWS Systems Manager for SAP User Guide { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::AccountId:role/EC2RoleToAccessSecrets" ] }, "Action": "secretsmanager:GetSecretValue", "Resource": "*" } ] } This policy enables the IAM role used by your Amazon EC2 instance access to this secret. For more details, see Attach a permissions policy to an AWS Secrets Manager secret. Note You must attach this policy to each secret that you create for your SAP HANA database credentials. 6. Select Next and then, select Store. Verify AWS Systems Manager Agent (SSM Agent) is running Use the following command to verify the status of the SSM Agent on your instance. sudo systemctl status amazon-ssm-agent Your output should display active (running) as seen here. amazon-ssm-agent.service - amazon-ssm-agent Loaded: loaded (/usr/lib/systemd/system/amazon-ssm-agent.service; enabled; vendor preset: disabled) Active: active (running) since Tue 2022-02-15 18:56:26 UTC; 12s ago ^^^^^^^^^^^^^^^^^^^^^^^^ You should expect to see "active (running)". Verify SSM Agent 7 AWS Systems Manager for SAP User Guide Main PID: 16061 (amazon-ssm-agen) Tasks: 36 CGroup: /system.slice/amazon-ssm-agent.service ##16061 /usr/sbin/amazon-ssm-agent ##16069 /usr/sbin/ssm-agent-worker AWS Systems Manager Agent (SSM Agent) is pre-installed in several Amazon Machine Images (AMIs) provided by AWS. For more information, see Working with SSM Agent. Verify setup before registering your SAP HANA database • Ensure that you are running SAP HANA 2.x. • Ensure that your Amazon EC2 instance has /run mount point mounted on tmpfs. Use the df | grep tmpfs command for verification. • Ensure that your Amazon EC2 instance has Python 3.5 or higher version installed. • Ensure that the hdbcli Python library is installed in the /opt/aws/ssm-sap/ directory on your Amazon EC2 instance, if the revision of your SAP HANA 2.0 server is below 056.00. • Ensure that the boto3 version is higher than 1.7.0 if boto3 is installed. To register your database, see Register your SAP HANA database with AWS Systems Manager for SAP. Backup and restore – optional After registering your database, you can optionally choose to complete the prerequisites required to backup and restore your database. You must run these steps on all Amazon EC2 instances in your setup. Topics • Set up required permissions for Amazon EC2 instance for backup and restore of SAP HANA database • Install AWS Backint Agent for SAP HANA with AWS Systems Manager Agent (SSM Agent) on your SAP application server Verify setup 8 AWS Systems Manager for SAP User Guide Set up required permissions for Amazon EC2 instance for backup and restore of SAP HANA database To backup and restore your SAP HANA databases running on Amazon EC2 instance, attach the following IAM policies to the IAM role used by your Amazon EC2 instance. • AWSBackupDataTransferAccess – this Amazon managed policy must be attached to the IAM role of Amazon EC2 instance where AWS Backint Agent for SAP HANA is located. AWS Backint Agent uses this IAM role to transfer data for backup and restore. For more information about the policy, see Managed policies for AWS Backup. • AWSBackupRestoreAccessForSAPHANA – this Amazon managed policy enables access to restore your SAP HANA database using AWS Backup. • If you are going to use AWS Backup console for the restore process, attach this policy to the IAM role using the console. • If you are going to use AWS API for the restore process, attach this policy to the IAM role performing the API call. • Follow the recommended best practice of granting least privilege necessary for each role by attaching the AWSBackupRestoreAccessForSAPHANA policy only to the SAP HANA resource owner. • AWSBackupServiceRolePolicyForBackup – this Amazon managed policy must be attached to the role that will passed to StartBackupJob or DefaultRole. For more information, see Service-linked role permissions for AWS Backup. The policy must contain the following trust relation. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "backup.amazonaws.com" }, "Action": "sts:AssumeRole"
ssm-sap-004
ssm-sap.pdf
4
are going to use AWS API for the restore process, attach this policy to the IAM role performing the API call. • Follow the recommended best practice of granting least privilege necessary for each role by attaching the AWSBackupRestoreAccessForSAPHANA policy only to the SAP HANA resource owner. • AWSBackupServiceRolePolicyForBackup – this Amazon managed policy must be attached to the role that will passed to StartBackupJob or DefaultRole. For more information, see Service-linked role permissions for AWS Backup. The policy must contain the following trust relation. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "backup.amazonaws.com" }, "Action": "sts:AssumeRole" } ] } Set up permissions for backup and restore 9 AWS Systems Manager for SAP User Guide Install AWS Backint Agent for SAP HANA with AWS Systems Manager Agent (SSM Agent) on your SAP application server Follow along the steps described in AWS Backint Agent for SAP HANA documentation. For more information, see Install and configure AWS Backint Agent for SAP HANA. Install AWS Backint Agent 10 AWS Systems Manager for SAP User Guide Tutorials for AWS Systems Manager for SAP You can manage your SAP deployments with Systems Manager for SAP using AWS CLI or AWS Management Console. This section provides tutorials to perform these tasks. See the following topics for detailed tutorials. Topics • AWS CLI • AWS Management Console AWS CLI Using AWS CLI, you can register SAP HANA or SAP ABAP applications, start, stop, refresh, and deregister SAP applications with Systems Manager for SAP. Topics • Register your SAP HANA databases with Systems Manager for SAP • Register your SAP ABAP application with AWS Systems Manager for SAP • Start SAP application • Stop SAP application • Refresh SAP application • Deregister SAP application Register your SAP HANA databases with Systems Manager for SAP You can register a single node or a high availability setup with multiple nodes for SAP HANA database with Systems Manager for SAP. Ensure that you have completed the setup perquisites described in Get started with Systems Manager for SAP. Follow along these steps to register your database. Steps • Step 1: Create a JSON for credentials • Step 2: Register database AWS CLI 11 AWS Systems Manager for SAP User Guide • Step 3: Check registration status • Step 4: Verify registration • Step 5: View component summary • Backup your database – optional Step 1: Create a JSON for credentials Create a JSON file to store the credentials you created in the section called “Register credentials in AWS Secrets Manager”. [{ "DatabaseName": "<YOUR_SID>/<YOUR_DATABASE_NAME>", "CredentialType": "ADMIN", "SecretId": "<YOUR_SECRET_NAME>" }, { "DatabaseName": "<YOUR_SID>/<ANOTHER_ONE_OF_YOUR_DATABASE_NAME>", "CredentialType": "ADMIN", "SecretId": "<YOUR_SECRET_NAME>" }] • Enter a unique name for the JSON file. For example, SsmForSapRegistrationCredentials.json. • For DatabaseName, ensure that you enter both, the system ID and the database name. • For SecretId, use the Secret name created in Step 4 of the section called “Register credentials in AWS Secrets Manager”. The following is an example JSON file. [{ "DatabaseName": "HDB/SYSTEMDB", "CredentialType": "ADMIN", "SecretId": "HANABackup" }, { "DatabaseName": "HDB/HDB", "CredentialType": "ADMIN", "SecretId": "HANABackup" }] Register SAP HANA database 12 AWS Systems Manager for SAP Step 2: Register database User Guide Register your SAP HANA databases using the following command. Make sure to use the correct SAP HANA database instance number and SAP HANA database name (SID). These are different than the SAP instance number and SAP System Identifier. // Command template aws ssm-sap register-application \ --application-id <myApplication> \ --application-type HANA \ --instances <YOUR_EC2_INSTANCE_ID> \ --sap-instance-number <YOUR_HANA_DATABASE_SYSTEM_NUMBER> \ --sid <YOUR_HANA_DATABASE_SID> \ --region us-east-1 \ --credentials file://<PATH_TO_YOUR_CREDENTIALS_JSON_FILE> // Example command with sample values aws ssm-sap register-application \ --application-id <myApplication> \ --application-type HANA \ --instances i-0123456789abcdefg \ --sap-instance-number 00 \ --sid HDB \ --region us-east-1 \ --credentials file://SsmForSapRegistrationCredentials.json // Example JSON response{ "Application": { "Id": "myApplication", "Type": "HANA", "Arn": "<APPLICATION_ARN>", "Status": "REGISTERING", "Components": [], "LastUpdated": "2022-08-19T10:58:48.521000-07:00" }, "OperationId": "6bd44104-d63c-449d-8007-6c1b471e3e5e" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Take note of this operation ID. You'll need it in the next step. } Register SAP HANA database 13 AWS Systems Manager for SAP User Guide In the preceding example, the instance number is 00 and SID is HDB. This can be verified with / usr/sap/<SID>/HDB<instance number>. For example, the path will be /usr/sap/HDB/ HDB00. Note To register a high availability SAP HANA database, you can input either the primary or the secondary instance ID with the --instances parameter. For example, for a high availability SAP HANA database residing on primary node i-0123456789abcdefg and secondary node i-9876543210abcdefg, you can specify database registration in any one of the following ways. • --instances i-0123456789abcdefg • --instances i-9876543210abcdefg Step 3: Check registration status The registration may take approximately five minutes to complete. Use the following command to check the status of the registration. Replace <Your_Operation_ID> with the OperationID from the previous step. aws ssm-sap get-operation \ --operation-id <YOUR_OPERATION_ID> \ --region us-east-1
ssm-sap-005
ssm-sap.pdf
5
a high availability SAP HANA database, you can input either the primary or the secondary instance ID with the --instances parameter. For example, for a high availability SAP HANA database residing on primary node i-0123456789abcdefg and secondary node i-9876543210abcdefg, you can specify database registration in any one of the following ways. • --instances i-0123456789abcdefg • --instances i-9876543210abcdefg Step 3: Check registration status The registration may take approximately five minutes to complete. Use the following command to check the status of the registration. Replace <Your_Operation_ID> with the OperationID from the previous step. aws ssm-sap get-operation \ --operation-id <YOUR_OPERATION_ID> \ --region us-east-1 Step 4: Verify registration Verify the registration with GetApplication API. You can also view the details of registered databases with ListDatabases and GetDatabase API. // Command template aws ssm-sap get-application \ --application-id <myApplication> \ --region us-east-1 // Example to get the summary of an application aws ssm-sap get-application \ --application-id <myApplication> \ Register SAP HANA database 14 AWS Systems Manager for SAP --region us-east-1 // Example output { "Application": { "Id": "myApplication", "Type": "HANA", User Guide "Arn": "arn:aws:ssm-sap:us-east-1:123456789123:HANA/myApplication", "AppRegistryArn": "arn:aws:servicecatalog:us-east-1:123456789123:/applications/ myApplication", "Status": "ACTIVATED", "DiscoveryStatus": "SUCCESS", "Components": [ "HDB-HDB00" ^^^^^^^^^^^ // Take note of this component ID. You'll need it in the next step. ], "LastUpdated": "2023-07-06T13:25:35.702000-07:00" }, "Tags": {} } Step 5: View component summary Get the component summary with GetComponent API. // Command template aws ssm-sap get-component \ --application-id <myApplication> \ --component-id <YOUR_COMPONENT_ID_FROM_LAST_STEP> --region us-east-1 Systems Manager for SAP provides two types of components for an SAP HANA application – parent and child. • HANA – there is only one parent component representing the logical database. • HANA_NODE – there are multiple child components representing database host entities. See the following table for examples of single node and high availability SAP HANA database setup with Systems Manager for SAP. Register SAP HANA database 15 AWS Systems Manager for SAP Single node User Guide GetComponent API output for parent component { "Component": { "ComponentId": "HDB-HDB00", "ChildComponents": [ "HDB-HDB00-sapci" ], "ApplicationId": "myApplication", "ComponentType": "HANA", "Status": "RUNNING", "Databases": [ "SYSTEMDB", "HDB" ], "Hosts": [ { "HostName": "sapci", "HostIp": "172.31.31.70", "EC2InstanceId": "i-0123456789abcdefg", "InstanceId": "i-0123456789abcdefg", "HostRole": "LEADER", "OsVersion": "SUSE Linux Enterprise Server 15 SP4" } ], "PrimaryHost": "i-0123456789abcdefg", "LastUpdated": "2023-07-19T11:06:36.114000-07:00", "Arn": "arn:aws:ssm-sap:us-east-1:123456789123:HANA/myApplication/COMPONENT/ HDB-HDB00" }, "Tags": {} } GetComponent API output for child component { "Component": { "ComponentId": "HDB-HDB00-sapci", "ParentComponent": "HDB-HDB00", "ApplicationId": "myApplication", "ComponentType": "HANA_NODE", "Status": "RUNNING", "SapHostname": "sapci.local", Register SAP HANA database 16 AWS Systems Manager for SAP User Guide "SapKernelVersion": "753, patch 1010, changelist 2124070", "HdbVersion": "", "Resilience": { "HsrTier": "", "HsrReplicationMode": "NONE", "HsrOperationMode": "NONE" }, "AssociatedHost": { "Hostname": "sapci", "Ec2InstanceId": "i-04823df91c0934025", "OsVersion": "SUSE Linux Enterprise Server 15 SP4" }, "LastUpdated": "2023-07-19T11:06:36.101000-07:00", "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:HANA/myApplication/COMPONENT/ HDB-HDB00-sapci" }, "Tags": {} } High availability GetComponent API output for parent component { “Component”: { “ComponentId”: “HDB-HDB00”, “ChildComponents”: [ “HDB-HDB00-sapsecdb”, “HDB-HDB00-sappridb” ], “ApplicationId”: “myApplication”, “ComponentType”: “HANA”, “Status”: “RUNNING”, “Databases”: [ “SYSTEMDB”, “HDB” ], "LastUpdated": "2023-06-28T22:57:24.053000-07:00", “Arn”: “arn:aws:ssm-sap:us-east-1:123456789123:HANA/myApplication/COMPONENT/HDB- HDB00" }, “Tags”: {} } Register SAP HANA database 17 AWS Systems Manager for SAP User Guide GetComponent API output for child component (primary) { "Component": { "ComponentId": "HDB-HDB00-sappridb", "ParentComponent": "HDB-HDB00", "ApplicationId": "myApplication", "ComponentType": "HANA_NODE", "Status": "RUNNING", "SapHostname": "sappridb.local", "SapKernelVersion": "753, patch 1010, changelist 2124070", "HdbVersion": "2.00.065.00.1665753120", "Resilience": { "HsrTier": "1", "HsrReplicationMode": "PRIMARY", "HsrOperationMode": "PRIMARY", "ClusterStatus": "ONLINE" }, "AssociatedHost": { "Hostname": "sappridb", "Ec2InstanceId": "i-0123456789abcdefg", "OsVersion": "SUSE Linux Enterprise Server 15 SP4" }, "LastUpdated": "2023-07-19T10:20:26.888000-07:00", "Arn": "arn:aws:ssm-sap:us-east-1:123456789123:HANA/myApplication/COMPONENT/ HDB-HDB00-sappridb" }, "Tags": {} } GetComponent API output for child component (secondary) { "Component": { "ComponentId": "HDB-HDB00-sapsecdb", "ParentComponent": "HDB-HDB00", "ApplicationId": "myApplication", "ComponentType": "HANA_NODE", "Status": "RUNNING", "SapHostname": "sapsecdb.local", "SapKernelVersion": "753, patch 1010, changelist 2124070", "HdbVersion": "2.00.065.00.1665753120", "Resilience": { "HsrTier": "2", "HsrReplicationMode": "SYNC", Register SAP HANA database 18 AWS Systems Manager for SAP User Guide "HsrOperationMode": "LOGREPLAY", "ClusterStatus": "ONLINE" }, "AssociatedHost": { "Hostname": "sapsecdb", "Ec2InstanceId": "i-0123456789abcdefg", "OsVersion": "SUSE Linux Enterprise Server 15 SP4" }, "LastUpdated": "2023-07-19T10:20:26.639000-07:00", "Arn": "arn:aws:ssm-sap:us-east-1:123456789123:HANA/myApplication/COMPONENT/ HDB-HDB00-sapsecdb" }, "Tags": {} } Backup your database – optional Now the registration is complete, and you can begin data protection operations, including backup and restore of your SAP HANA databases. For more details, see AWS Backup documentation. Register your SAP ABAP application with AWS Systems Manager for SAP You can register a single node setup for SAP ABAP application with Systems Manager for SAP. Ensure that you have completed the setup perquisites described in Get started with Systems Manager for SAP. Follow along these steps to register your SAP ABAP application. Steps • Step 1: Register database • Step 2: Register application • Step 3: Check registration status • Step 4: Verify registration • Step 5: View component summary Step 1: Register database Register your SAP HANA database before registering your SAP ABAP application. For more information, see the section called “Register SAP HANA database”. Register SAP ABAP application 19 AWS Systems Manager for SAP User Guide Note the ApplicationId of your registration. Step 2: Register application 1.
ssm-sap-006
ssm-sap.pdf
6
completed the setup perquisites described in Get started with Systems Manager for SAP. Follow along these steps to register your SAP ABAP application. Steps • Step 1: Register database • Step 2: Register application • Step 3: Check registration status • Step 4: Verify registration • Step 5: View component summary Step 1: Register database Register your SAP HANA database before registering your SAP ABAP application. For more information, see the section called “Register SAP HANA database”. Register SAP ABAP application 19 AWS Systems Manager for SAP User Guide Note the ApplicationId of your registration. Step 2: Register application 1. Use the ApplicationId noted in the previous step in the next command. 2. Use the following command to find the Amazon Resource Name (ARN) of the database. % aws ssm-sap list-databases --application-id <mySAPHANAApplication> { "Databases": [ { "ApplicationId": "SAP_HANA_APPLICATION", "ComponentId": "HDB-HDB00", "DatabaseId": "SYSTEMDB", "DatabaseType": "SYSTEM", "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:HANA/ SAP_HANA_APPLICATION/DB/SYSTEMDB", "Tags": {} }, { "ApplicationId": "SAP_HANA_APPLICATION", "ComponentId": "HDB-HDB00", "DatabaseId": "HDB", "DatabaseType": "TENANT", ------> "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:HANA/ SAP_HANA_APPLICATION/DB/HDB", "Tags": {} } ] } 3. Note the database-arn from the preceding step to register your SAP ABAP application with the following command. // Command template aws ssm-sap register-application \ --application-id <myApplication> \ --application-type SAP_ABAP \ --instances <YOUR_EC2_INSTANCE_ID> \ --sid <YOUR_HANA_SID> \ --region us-east-1 --database-arn <SAP HANA DATABASE ARN FROM REGISTERED APPLICATION> Register SAP ABAP application 20 AWS Systems Manager for SAP User Guide // Example command with sample values aws ssm-sap register-application —application-id "mySAPABAPApplication" \ —application-type SAP_ABAP \ —instances i-0307b3e5fbdc4bda1 \ —sid ECD \ —region us-east-1 \ —database-arn "arn:aws:ssm-sap:us-east-1:123456789101:HANA/ SAP_HANA_APPLICATION/DB/HDB" // Example JSON response { "Application": { "Id": "mySAPABAPApplication", "Type": "SAP_ABAP", "Arn": "<APPLICATION_ARN>", "Status": "REGISTERING", "Components": [], "LastUpdated": "2022-08-19T10:58:48.521000-07:00" }, "OperationId": "6bd44104-d63c-449d-8007-6c1b471e3e5e" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Take note of this operation ID. You'll need it in the next step. } Step 3: Check registration status The registration may take a few minutes to complete. Use the following command to check the status of your registration. Use the OperationId generated when registering your SAP ABAP application in the preceding step. aws ssm-sap get-operation \ --operation-id <YOUR_OPERATION_ID> \ --region us-east-1 Step 4: Verify registration Verify the registration with GetApplication API. You can also view the details of registered databases with ListDatabases and GetDatabase API. // Command template Register SAP ABAP application 21 AWS Systems Manager for SAP User Guide aws ssm-sap get-application \ --application-id <myApplication> \ --region us-east-1 // Example to get the summary of an application aws ssm-sap get-application \ --application-id mySAPABAPApplication \ --region us-east-1 { "Application": { "Id": "mySAPABAPApplication", "Type": "SAP_ABAP", "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:SAP_ABAP/mySAPABAPApplication", "AppRegistryArn": "arn:aws:servicecatalog:us-east-1:123456789101:/ applications/0efeiejngum6atpd8ww2xklo", "Status": "ACTIVATED", "DiscoveryStatus": "SUCCESS", "Components": [ "ECD-ABAP" ^^^^^^^^^^^ // Take note of this component ID. You'll need it in the next step. ], "LastUpdated": "2023-10-04T22:16:59.106000-07:00" }, "Tags": {} } Step 5: View component summary Get the component summary with GetComponent API. // Command template aws ssm-sap get-component \ --application-id <myApplication> \ --component-id <YOUR_COMPONENT_ID_FROM_LAST_STEP> --region us-east-1 //GetComponent API output for parent component % aws ssm-sap get-component --component-id ECD-ABAP \ --application-id mySAPABAPApplication \ --region us-east-1 { "Component": { Register SAP ABAP application 22 AWS Systems Manager for SAP User Guide "ComponentId": "ECD-ABAP", "Sid": "ECD", "ChildComponents": [ "ECD-ASCS10-sapci", "ECD-D12-sapci" ], "ApplicationId": "mySAPABAPApplication", "ComponentType": "ABAP", "Status": "RUNNING", "DatabaseConnection": { "DatabaseConnectionMethod": "DIRECT", "DatabaseArn": "arn:aws:ssm-sap:us-east-1:123456789101:HANA/ SAP_HANA_APPLICATION/DB/HDB", "ConnectionIp": "172.31.19.240" }, "LastUpdated": "2023-10-04T22:16:59.089000-07:00", "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:SAP_ABAP/mySAPABAPApplication/ COMPONENT/ECD-ABAP" }, "Tags": {} } //GetComponent API output for child component % aws ssm-sap get-component \ --component-id ECD-ASCS10-sapci --application-id mySAPABAPApplication \ --region us-east-1 { "Component": { "ComponentId": "ECD-ASCS10-sapci", "Sid": "ECD", "SystemNumber": "10", "ParentComponent": "ECD-ABAP", "ApplicationId": "mySAPABAPApplication", "ComponentType": "ASCS", "Status": "RUNNING", "SapFeature": "MESSAGESERVER|ENQUE", "SapHostname": "sapci", "SapKernelVersion": "785, patch 200, changelist 2150416", "Resilience": { "EnqueueReplication": false }, "AssociatedHost": { "Hostname": "sapci", "Ec2InstanceId": "i-0307b3e5fbdc4bda1", Register SAP ABAP application 23 AWS Systems Manager for SAP User Guide "IpAddresses": [ { "IpAddress": "172.31.19.240", "Primary": true, "AllocationType": "VPC_SUBNET" } ], "OsVersion": "SUSE Linux Enterprise Server 15 SP4" }, "LastUpdated": "2023-10-04T22:16:58.915000-07:00", "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:SAP_ABAP/mySAPABAPApplication/ COMPONENT/ECD-ASCS10-sapci" }, "Tags": {} } Start SAP application You can perform a start operation on a single node or HA (high availability) SAP HANA application or on a single node setup of an SAP ABAP application which is registered with AWS Systems Manager for SAP. When starting an SAP HANA application, the Amazon EC2 instance(s) on which the SAP HANA application will run is started first (if it is not already running), before the application is started. When starting a single node setup of an SAP ABAP application, the HANA database and/or the Amazon EC2 instance on which the SAP ABAP application will run is started first (if it is not already running). Before you initiate a start operation, complete the setup prerequisites described in Get started with AWS Systems Manager for SAP and register your SAP application, if you have not already done so. You can start Systems Manager for SAP application using AWS CLI or AWS Management Console. The following procedure is for starting an SAP
ssm-sap-007
ssm-sap.pdf
7
is not already running), before the application is started. When starting a single node setup of an SAP ABAP application, the HANA database and/or the Amazon EC2 instance on which the SAP ABAP application will run is started first (if it is not already running). Before you initiate a start operation, complete the setup prerequisites described in Get started with AWS Systems Manager for SAP and register your SAP application, if you have not already done so. You can start Systems Manager for SAP application using AWS CLI or AWS Management Console. The following procedure is for starting an SAP application using AWS CLI. Steps • Step 1: Register SAP Application • Step 2: Start SAP Application • Step 3: Check Start Operation status • Step 4: Verify Start operation Start SAP application 24 AWS Systems Manager for SAP User Guide Step 1: Register SAP Application Register your SAP application, if you have not already done so. For more information, see Register SAP HANA database or Register SAP ABAP application. In your records, note the ApplicationId of your registration. Step 2: Start SAP Application You can use the following AWS CLI command to start your SAP application: aws ssm-sap start-application \ --application-id >ApplicationId< --region us-east-1 The parameter application-id is required. As the value, use the ApplicationID generated from registration in Step 1. // Command template aws ssm-sap start-application \ --application-id >myApplication< --region us-east-1 // Command example aws ssm-sap start-application --application-id myHANAApp --region us-east-1 // Return example { "OperationId": "a7h4j3k6-8463-836h-018h-7sh377h6hhd6" } Step 3: Check Start Operation status The start operation can take up to five minutes to complete. During that time, you can use the following command to check the status of the operation. Use the OperationId that was generated in Step 2. // Command template aws ssm-sap get-operation \ Start SAP application 25 AWS Systems Manager for SAP User Guide --operation-id <OPERATION_ID> --region us-east-1 Step 4: Verify Start operation Verify the start operation on the application through the event using the ListOperationEvents API. // Command template aws ssm-sap list-operation-events \ --operation-id <YOUR_OPERATION_ID> --region us-east-1 // Command example aws ssm-sap list-operation-events \ --operation-id b2bc3266-9369-4163-b935-6a586c80e76b { "OperationEvents": [ { "Description": "Start the SAP component ECD-ABAP", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:SAP_ABAP/ nwStartStop/COMPONENT/ECD-ABAP", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "COMPLETED", "StatusMessage": "", "Timestamp": "2024-01-03T04:49:59.846000+00:00" }, { "Description": "Start the SAP component ECD-ABAP", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:SAP_ABAP/ nwStartStop/COMPONENT/ECD-ABAP", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "IN_PROGRESS", "StatusMessage": "", "Timestamp": "2024-01-03T04:48:59.846000+00:00" }, { "Description": "Start the SAP component HDB-HDB00-sapci", "Resource": { Start SAP application 26 AWS Systems Manager for SAP User Guide "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:HANA/ hanaStartStop/COMPONENT/HDB-HDB00-sapci", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "COMPLETED", "StatusMessage": "", "Timestamp": "2024-01-03T04:47:59.846000+00:00" }, { "Description": "Start the SAP component HDB-HDB00-sapci", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:HANA/ hanaStartStop/COMPONENT/HDB-HDB00-sapci", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "IN_PROGRESS", "StatusMessage": "", "Timestamp": "2024-01-03T04:46:59.846000+00:00" }, { "Description": "Start the EC2 instance i-abcdefgh987654321", "Resource": { "ResourceArn": "arn:aws:ec2:us-east-1:111111111111:instance/i- abcdefgh987654321", "ResourceType": "AWS::EC2::Instance" }, "Status": "COMPLETED", "StatusMessage": "", "Timestamp": "2024-01-03T04:45:59.846000+00:00" }, { "Description": "Start the EC2 instance i-0e5ec51c3679d6231", "Resource": { "ResourceArn": "arn:aws:ec2:us-east-1:111111111111:instance/ i-0e5ec51c3679d6231", "ResourceType": "AWS::EC2::Instance" }, "Status": "IN_PROGRESS", "StatusMessage": "", "Timestamp": "2024-01-03T04:44:59.846000+00:00" } ] } Start SAP application 27 AWS Systems Manager for SAP Stop SAP application User Guide You can perform a stop operation on a single node or HA (high availability) SAP HANA application or on a single node setup of SAP ABAP application that has been registered with AWS Systems Manager for SAP. While performing the stop operation on an SAP HANA application, you can optionally also stop the Amazon EC2 instance(s) on which the SAP HANA application is running. While performing a stop operation on a single node setup of SAP ABAP application, you can optionally also stop the HANA database application and the Amazon EC2 instance on which the SAP ABAP application is running. Before you initiate a stop operation, complete the setup prerequisites described in Get started with AWS Systems Manager for SAP and register your SAP application, if you have not already done so. You can stop Systems Manager for SAP application using AWS CLI or AWS Management Console. The following procedure is for stopping an SAP application using AWS CLI. Steps • Step 1: Register SAP Application • Step 2: Stop SAP Application • Step 3: Check Stop Operation status • Step 4: Monitor and verify stop operation Step 1: Register SAP Application Register your SAP application, if you have not already done so. For more information, see Register SAP HANA database or Register SAP ABAP application. Step 2: Stop SAP Application You can use the following AWS CLI command to stop your SAP application: aws ssm-sap stop-application \ --application-id <myApplication> --stop-connected-entity <DBMS> --include-ec2-instance-shutdown The parameter application-id is required. As the value, use the ApplicationID generated from registration in Step 1. Stop SAP application 28 AWS Systems Manager for SAP User Guide The following parameters are optional: • Use the stop-connected-entity parameter with a value of
ssm-sap-008
ssm-sap.pdf
8
stop operation Step 1: Register SAP Application Register your SAP application, if you have not already done so. For more information, see Register SAP HANA database or Register SAP ABAP application. Step 2: Stop SAP Application You can use the following AWS CLI command to stop your SAP application: aws ssm-sap stop-application \ --application-id <myApplication> --stop-connected-entity <DBMS> --include-ec2-instance-shutdown The parameter application-id is required. As the value, use the ApplicationID generated from registration in Step 1. Stop SAP application 28 AWS Systems Manager for SAP User Guide The following parameters are optional: • Use the stop-connected-entity parameter with a value of DBMS (Database Management System) to also stop the corresponding database application when you stop a single node setup of an SAP ABAP application. • Use the Boolean parameter include-ec2-instance-shutdown to shut down the Amazon EC2 instance on which the SAP HANA or single node set up of an SAP ABAP application is running The following table displays examples of the stop operation on a single node SAP ABAP setup and an SAP HANA setup with AWS Systems Manager for SAP: SAP ABAP // Command template aws ssm-sap stop-application \ --application-id <myApplication> --stop-connected-entity DBMS --include-ec2-instance-shutdown --region us-east-1 // Command example aws ssm-sap stop-application --application-id myABAPApp --stop-connected-entity DBMS --include-ec2-instance-shutdown --region us-east-1 // Return example { "OperationId": "a7h4j3k6-8463-836h-018h-7sh377h6hhd6" } SAP HANA // Command template aws ssm-sap stop-application \ --application-id <myApplication> --include-ec2-instance-shutdown --region us-east-1 Stop SAP application 29 AWS Systems Manager for SAP User Guide // Command example aws ssm-sap stop-application --application-id myABAPApp --include-ec2-instance-shutdown --region us-east-1 // Return example { "OperationId": "j3h5j4k5-8323-192j-102n-18h7hhh27h27" } Step 3: Check Stop Operation status The stop operation can take up to five minutes to complete. During that time, you can use the following command to check the status of the operation. Use the OperationId that was generated in Step 2. // Command template aws ssm-sap get-operation \ --operation-id <OPERATION_ID> --region us-east-1 // Command example aws ssm-sap get-operation --operation-id b2bc3266-9369-4163-b935-6a586c80e76b --region us-east-1 Step 4: Monitor and verify stop operation Verify the stop operation on the application through the event using the ListOperationEvents API. // Command template aws ssm-sap list-operation-events \ --operation-id <OPERATION_ID> --region us-east-1 // Command example aws ssm-sap list-operation-events \ Stop SAP application 30 AWS Systems Manager for SAP User Guide --operation-id a1bc2345-6789-0123-d456-7e890f12g34h { "OperationEvents": [ { "Description": "Stop the EC2 instance i-abcdefgh987654321", "Resource": { "ResourceArn": "arn:aws:ec2:us-east-1:111111111111:instance/i- abcdefgh987654321", "ResourceType": "AWS::EC2::Instance" }, "Status": "COMPLETED", "StatusMessage": "", "Timestamp": "2024-01-03T04:49:59.846000+00:00" }, { "Description": "Stop the EC2 instance i-abcdefgh987654321", "Resource": { "ResourceArn": "arn:aws:ec2:us-east-1:111111111111:instance/i- abcdefgh987654321", "ResourceType": "AWS::EC2::Instance" }, "Status": "IN_PROGRESS", "StatusMessage": "", "Timestamp": "2024-01-03T04:48:59.846000+00:00" }, { "Description": "Stop the SAP component HDB-HDB00-sapci", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:HANA/ hanaStartStop/COMPONENT/HDB-HDB00-sapci", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "COMPLETED", "StatusMessage": "", "Timestamp": "2024-01-03T04:47:59.846000+00:00" }, { "Description": "Stop the SAP component HDB-HDB00-sapci", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:HANA/ hanaStartStop/COMPONENT/HDB-HDB00-sapci", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "IN_PROGRESS", Stop SAP application 31 AWS Systems Manager for SAP User Guide "StatusMessage": "", "Timestamp": "2024-01-03T04:46:59.846000+00:00" }, { "Description": "Stop the SAP component ECD-ABAP", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:SAP_ABAP/ nwStartStop/COMPONENT/ECD-ABAP", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "COMPLETED", "StatusMessage": "", "Timestamp": "2024-01-03T04:45:59.846000+00:00" }, { "Description": "Stop the SAP component ECD-ABAP", "Resource": { "ResourceArn": "arn:aws:ssm-sap:us-east-1:111111111111:SAP_ABAP/ nwStartStop/COMPONENT/ECD-ABAP", "ResourceType": "AWS::SystemsManagerSAP::Component" }, "Status": "IN_PROGRESS", "StatusMessage": "", "Timestamp": "2024-01-03T04:44:59.846000+00:00" } ] } Refresh SAP application The following steps will guide you through a refresh of your SAP HANA application or of your single node setup of SAP ABAP application. This refresh updates the application metadata in the AWS Systems Manager for SAP. Before you refresh an application, complete the setup prerequisites described in Get started with AWS Systems Manager for SAP and register your SAP application if you have not already done so. Step 1: Register SAP Application Register your SAP application, if you have not already done so. For more information, see Register SAP HANA database or Register SAP ABAP application. In your records, note the ApplicationId of your registration. Refresh SAP application 32 AWS Systems Manager for SAP User Guide Step 2: Refresh SAP Application You can use the following AWS CLI command to refresh your SAP application: aws ssm-sap start-application-refresh \ --application-id <ApplicationId> --region us-east-1 The parameter application-id is required. As the value, use the ApplicationID generated from registration in Step 1. Step 3: Check Refresh Operation status The refresh operation can take up to five minutes to complete. During that time, you can use the following command to check the status of the operation. Use the OperationId generated in Step 2. // Command template aws ssm-sap get-operation \ --operation-id <OPERATION_ID> --region us-east-1 Step 4: Verify application status Use the command get-application (GetApplication API) to verify the application status. You can also view the details of registered databases with ListDatabases and GetDatabase API. // Command template aws ssm-sap get-application \ --application-id <myApplication> --region us-east-1 // Example to get the summary of an application aws ssm-sap get-application \ --application-id mySAPABAPApplication --region us-east-1 // Response example { "Application": {
ssm-sap-009
ssm-sap.pdf
9
to complete. During that time, you can use the following command to check the status of the operation. Use the OperationId generated in Step 2. // Command template aws ssm-sap get-operation \ --operation-id <OPERATION_ID> --region us-east-1 Step 4: Verify application status Use the command get-application (GetApplication API) to verify the application status. You can also view the details of registered databases with ListDatabases and GetDatabase API. // Command template aws ssm-sap get-application \ --application-id <myApplication> --region us-east-1 // Example to get the summary of an application aws ssm-sap get-application \ --application-id mySAPABAPApplication --region us-east-1 // Response example { "Application": { "Id": "mySAPABAPApplication", Refresh SAP application 33 AWS Systems Manager for SAP "Type": "SAP_ABAP", User Guide "Arn": "arn:aws:ssm-sap:us-east-1:123456789101:SAP_ABAP/mySAPABAPApplication", "AppRegistryArn": "arn:aws:servicecatalog:us-east-1:123456789101:/ applications/0efeiejngum6atpd8ww2xklo", "Status": "ACTIVATED", "DiscoveryStatus": "SUCCESS", "Components": [ "ECD-ABAP" ^^^^^^^^^^^ // Note the ComponentID; it will be necessary if you choose to call GetComponent after this operation. ], "LastUpdated": "2023-10-04T22:16:59.106000-07:00" }, "Tags": {} } Deregister SAP application The following steps will guide you through deregistration your SAP HANA application or of your single node setup of SAP ABAP application registered with Systems Manager for SAP. If a database has not been previously registered with AWS Systems Manager, the deregistration process will result in a ValidationException. Step 1: Get ApplicationId of your SAP application // Command template aws ssm-sap list-applications \ --region us-east-1 In your records, note the ApplicationId of your registration. Step 2: Deregister SAP application You can use the AWS CLI command deregister-application (API DeregisterApplication) to deregister your SAP application. // Command template aws ssm-sap deregister-application \ --application-id <ApplicationId> --region us-east-1 Deregister SAP application 34 AWS Systems Manager for SAP User Guide The parameter application-id is required. As the value, use the ApplicationID retrieved in Step 1. Step 3: Verify deregistration Run the command list-application (ListApplications API) to verify your application is not present. AWS Management Console Using AWS Management Console, you can register SAP HANA and SAP ABAP applications, and start or stop SAP applications with Systems Manager for SAP. Topics • Register SAP HANA database with AWS Systems Manager for SAP • Register SAP ABAP application with AWS Systems Manager for SAP • Start SAP application • Stop SAP application Register SAP HANA database with AWS Systems Manager for SAP Follow along these steps to register SAP HANA database as a Systems Manager for SAP application. 1. Go to https://console.aws.amazon.com/systems-manager/ > Application Management > 2. 3. 4. Application Manager. Select Create Application > Enterprise Workload. For Application type, select SAP HANA. In Application details, enter a name for the application you want to register with Application Manager. 5. In SAP HANA workload, provide details of your workload. a. Instance ID – This is the Amazon EC2 instance ID where your workload is currently running. Choose Browse instances, and select the instance ID for your primary SAP HANA workload. b. SAP System Identifier (SID) – This is the SAP System Identifier (sapsid) of your SAP HANA instance. AWS Management Console 35 AWS Systems Manager for SAP User Guide c. SAP system number – This is the system number of your SAP HANA instance. d. Credentials – These are the credentials of your database. Note If you do not see the credentials for the application you want to register in the Secret ID drop-down list, ensure that you have registered your credentials with AWS Secrets Manager. For more information, see Register SAP HANA database credentials in AWS Secrets Manager. Optional Select Add credentials to add credentials for five databases. 6. Optional In Application tags, you can add 100 tags associated to resources. 7. Select Create. Application tabs On registration completion, you can see your application in the list of applications. You can see the following tabs for each application. Overview For more information, see Viewing overview information about an application. Resources You can find the Topology of a Systems Manager for SAP application in the Resources tab. It provides the details of your application components. The child components are embedded under parent components. Select each component to view its details. For more information, see Viewing application resources. Instances For more information, see Working with your application instances. Compliance For more information, see Viewing compliance information. Register SAP HANA database 36 AWS Systems Manager for SAP Monitoring Note User Guide You must on-board your Systems Manager for SAP application with Amazon CloudWatch Application Insights to view monitoring details in this tab. Use the following steps to on-board your registered SAP HANA application with Application Insights. 1. Open https://console.aws.amazon.com/systems-manager/. 2. Go to Application Manager. 3. From the list of applications, find and select your SAP application. This opens your application details window. 4. Go to the Monitoring tab > Application Insights > Add an application. 5. You are now redirected to Amazon CloudWatch Application Insights console. 6. Follow the instructions described in Set
ssm-sap-010
ssm-sap.pdf
10
Systems Manager for SAP Monitoring Note User Guide You must on-board your Systems Manager for SAP application with Amazon CloudWatch Application Insights to view monitoring details in this tab. Use the following steps to on-board your registered SAP HANA application with Application Insights. 1. Open https://console.aws.amazon.com/systems-manager/. 2. Go to Application Manager. 3. From the list of applications, find and select your SAP application. This opens your application details window. 4. Go to the Monitoring tab > Application Insights > Add an application. 5. You are now redirected to Amazon CloudWatch Application Insights console. 6. Follow the instructions described in Set up your SAP HANA database for monitoring. Under Select an application or resource group, make sure to select the SAP HANA application registered with Systems Manager for SAP. Note You can create only one CloudWatch Application Insights application on a single- node SAP ABAP application. You can onboard either the SAP ABAP application or the connected SAP HANA application. 7. Once you have completed onboarding your registered SAP HANA application with Amazon CloudWatch Application Insights, you can view monitoring details in the Monitoring tab. For more information, see Viewing monitoring information. OpsItems For more information, see Viewing OpsItems for an application. Register SAP HANA database 37 AWS Systems Manager for SAP Logs User Guide For more information, see Viewing log groups and log data. Runbooks For more information, see Working with runbooks in Application Manager. Cost You must enable AWS Cost Explorer Service to view details in the Cost tab. For more information, see Enabling Cost Explorer. The cost of the single-node SAP ABAP application is an aggregate of the cost of SAP ABAP and SAP HANA applications on the same EC2 instance. Register SAP ABAP application with AWS Systems Manager for SAP Important You must register the SAP HANA database you want to connect to the SAP ABAP application before registering the SAP ABAP application. Follow along these steps to register SAP ABAP as a Systems Manager for SAP application. 1. Go to https://console.aws.amazon.com/systems-manager/ > Application Management > 2. 3. 4. Application Manager. Select Create Application > Enterprise Workload. For Application type, select SAP HANA. In Application details, enter a name for the application you want to register with Application Manager. 5. Provide the following details of your workload. a. Instance ID – This is the Amazon EC2 instance ID where your workload is currently running. Choose Browse instances, and select the instance ID for your primary SAP ABAP workload. b. SAP System Identifier (SID) – This is the SAP System Identifier (sapsid) of your SAP ABAP instance. Register SAP ABAP application 38 AWS Systems Manager for SAP User Guide c. SAP HANA database Amazon Resource Name (ARN) – This is the Amazon Resource Name (ARN) of the SAP HANA database you want to connect to your SAP ABAP application. • Select Browse databases to choose the database. • Select Register a new application to register an SAP HANA database to connect to the SAP ABAP application. You can refresh the database list on successful completion of the SAP HANA application. 6. Optional In Application tags, you can add 100 tags associated to resources. 7. Select Create. Application tabs On registration completion, you can see your application in the list of applications. You can see the following tabs for each application. Overview For more information, see Viewing overview information about an application. Resources You can find the Topology of a Systems Manager for SAP application in the Resources tab. It provides the details of your application components. The child components are embedded under parent components. Select each component to view its details. For more information, see Viewing application resources. Instances For more information, see Working with your application instances. Compliance For more information, see Viewing compliance information. Monitoring Note You must on-board your Systems Manager for SAP application with Amazon CloudWatch Application Insights to view monitoring details in this tab. Register SAP ABAP application 39 AWS Systems Manager for SAP User Guide Use the following steps to on-board your registered SAP HANA application with Application Insights. 1. Open https://console.aws.amazon.com/systems-manager/. 2. Go to Application Manager. 3. From the list of applications, find and select your SAP application. This opens your application details window. 4. Go to the Monitoring tab > Application Insights > Add an application. 5. You are now redirected to Amazon CloudWatch Application Insights console. 6. Follow the instructions described in Set up your SAP HANA database for monitoring. Under Select an application or resource group, make sure to select the SAP HANA application registered with Systems Manager for SAP. Note You can create only one CloudWatch Application Insights application on a single- node SAP ABAP application. You can onboard either the SAP ABAP application or the connected SAP HANA application. 7. Once you have completed onboarding your
ssm-sap-011
ssm-sap.pdf
11
application details window. 4. Go to the Monitoring tab > Application Insights > Add an application. 5. You are now redirected to Amazon CloudWatch Application Insights console. 6. Follow the instructions described in Set up your SAP HANA database for monitoring. Under Select an application or resource group, make sure to select the SAP HANA application registered with Systems Manager for SAP. Note You can create only one CloudWatch Application Insights application on a single- node SAP ABAP application. You can onboard either the SAP ABAP application or the connected SAP HANA application. 7. Once you have completed onboarding your registered SAP HANA application with Amazon CloudWatch Application Insights, you can view monitoring details in the Monitoring tab. For more information, see Viewing monitoring information. OpsItems For more information, see Viewing OpsItems for an application. Logs For more information, see Viewing log groups and log data. Runbooks For more information, see Working with runbooks in Application Manager. Cost You must enable AWS Cost Explorer Service to view details in the Cost tab. For more information, see Enabling Cost Explorer. Register SAP ABAP application 40 AWS Systems Manager for SAP User Guide The cost of the single-node SAP ABAP application is an aggregate of the cost of SAP ABAP and SAP HANA applications on the same EC2 instance. Start SAP application Follow along these steps to start Systems Manager for SAP application using AWS Management Console. 1. Go to https://console.aws.amazon.com/systems-manager/ > Application Management > Application Manager. 2. 3. 4. From the list of registered applications, choose the application you want to start. Select Actions > Start application. Select Start. You can monitor the task status using the operation ID provided in the flash banner or by selecting Actions > View operations. Stop SAP application Follow along these steps to stop Systems Manager for SAP application using AWS Management Console. 1. Go to https://console.aws.amazon.com/systems-manager/ > Application Management > Application Manager. 2. 3. From the list of registered applications, choose the application you want to stop. Select Actions > Stop application. a. When sttopping an SAP HANA application, you can also stop the associated EC2 instance where the SAP HANA application is running. b. When stopping an SAP ABAP application, you can also stop the connected SAP HANA application, and/or stop the associated EC2 instance where the SAP ABAP and SAP HANA applications are running. Start SAP application 41 AWS Systems Manager for SAP User Guide Note You can stop the EC2 instance only if you have selected the option to stop the connected SAP HANA application. 4. Select Stop. You can monitor the task status using the operation ID provided in the flash banner or by selecting Actions > View operations. Stop SAP application 42 AWS Systems Manager for SAP User Guide Supported versions for SAP deployments The following section provides information about the versions of operating systems, databases, and applications supported by AWS Systems Manager for SAP. Topics • Operating systems • Databases • SAP applications Operating systems The following table provides details of the operating systems supported by AWS Systems Manager for SAP. Operating system Versions Red Hat Enterprise Linux 9.2, 9.0, 8.6, 8.4, 8.2, 8.1, 7.9, and 7.7 SUSE Linux Enterprise Server for SAP Applicati ons 15, 15 SP1, 15 SP2, 15 SP3, 15 SP4, 15 SP5, 12 SP4, and 12 SP5 SUSE Linux Enterprise Server 15, 15 SP1, 15 SP2, 15 SP3, 15 SP4, 15 SP5, 12 SP4, and 12 SP5 Databases The following table provides details of the database versions supported by AWS Systems Manager for SAP. Database SAP HANA (single node) SAP HANA (high availability) Versions 2.0 2.0 Operating systems 43 AWS Systems Manager for SAP SAP applications User Guide The following table provides details of SAP applications supported by AWS Systems Manager for SAP. Applications SAP HANA (single-node) SAP HANA (high availability) Versions 2.0 2.0 SAP NetWeaver on SAP ABAP 750 and higher SAP applications 44 AWS Systems Manager for SAP User Guide Security in AWS Systems Manager for SAP Cloud security at AWS is the highest priority. As an AWS customer, you benefit from data centers and network architectures that are built to meet the requirements of the most security-sensitive organizations. Security is a shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third- party auditors regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To learn about the compliance programs that apply to AWS Systems Manager for SAP, see AWS Services in Scope by Compliance Program. • Security in the cloud
ssm-sap-012
ssm-sap.pdf
12
shared responsibility between AWS and you. The shared responsibility model describes this as security of the cloud and security in the cloud: • Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third- party auditors regularly test and verify the effectiveness of our security as part of the AWS Compliance Programs. To learn about the compliance programs that apply to AWS Systems Manager for SAP, see AWS Services in Scope by Compliance Program. • Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations. This documentation helps you understand how to apply the shared responsibility model when using Systems Manager for SAP. The following topics show you how to configure Systems Manager for SAP to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your Systems Manager for SAP resources. Topics • AWS managed policies for AWS Systems Manager for SAP • Using service linked roles for AWS Systems Manager for SAP AWS managed policies for AWS Systems Manager for SAP To add permissions to users, groups, and roles, it is easier to use AWS managed policies than to write policies yourself. It takes time and expertise to create IAM customer managed policies that provide your team with only the permissions they need. To get started quickly, you can use our AWS managed policies. These policies cover common use cases and are available in your AWS account. For more information about AWS managed policies, see AWS managed policies in the IAM User Guide. AWS managed policies 45 AWS Systems Manager for SAP User Guide AWS services maintain and update AWS managed policies. You can't change the permissions in AWS managed policies. Services occasionally add additional permissions to an AWS managed policy to support new features. This type of update affects all identities (users, groups, and roles) where the policy is attached. Services are most likely to update an AWS managed policy when a new feature is launched or when new operations become available. Services do not remove permissions from an AWS managed policy, so policy updates won't break your existing permissions. Additionally, AWS supports managed policies for job functions that span multiple services. For example, the ReadOnlyAccess AWS managed policy provides read-only access to all AWS services and resources. When a service launches a new feature, AWS adds read-only permissions for new operations and resources. For a list and descriptions of job function policies, see AWS managed policies for job functions in the IAM User Guide. AWS managed policy: AWSSystemsManagerForSAPFullAccess Attach the AWSSystemsManagerForSAPFullAccess policy to your IAM identities. The AWSSystemsManagerForSAPFullAccess policy grants full access to Systems Manager for SAP service. Permissions details This policy includes the following permissions. • ssm-sap – Allows principals full access to Systems Manager for SAP. • iam – Allows a service-linked role to be created, which is a requirement for using Systems Manager for SAP. • ec2 – Allows Systems Manager for SAP to start or stop an Amazon EC2 instance, if that instance is tagged with the key value pair SSMForSAPManaged=True. { "Version": "2012-10-17", "Statement": [ { "Sid": "AwsSsmForSapPermissions", "Effect": "Allow", "Action": [ "ssm-sap:*" ], AWSSystemsManagerForSAPFullAccess 46 AWS Systems Manager for SAP User Guide "Resource": "arn:*:ssm-sap:*:*:*" }, { "Sid": "AwsSsmForSapServiceRoleCreationPermission", "Effect": "Allow", "Action": [ "iam:CreateServiceLinkedRole" ], "Resource": [ "arn:aws:iam::*:role/aws-service-role/ssm-sap.amazonaws.com/ AWSServiceRoleForAWSSSMForSAP" ], "Condition": { "StringEquals": { "iam:AWSServiceName": "ssm-sap.amazonaws.com" } } }, { "Sid": "Ec2StartStopPermission", "Effect": "Allow", "Action": [ "ec2:StartInstances", "ec2:StopInstances" ], "Resource": "arn:aws:ec2:*:*:instance/*", "Condition": { "StringEqualsIgnoreCase": { "ec2:resourceTag/SSMForSAPManaged": "True" } } } ] } AWS managed policy: AWSSystemsManagerForSAPReadOnlyAccess Attach the AWSSystemsManagerForSAPReadOnlyAccess policy to your IAM identities. The AWSSystemsManagerForSAPReadOnlyAccess policy grants read only access to the Systems Manager for SAP service. Permissions details AWSSystemsManagerForSAPReadOnlyAccess 47 AWS Systems Manager for SAP User Guide This policy includes the following permissions. • ssm-sap – Allows principals read only access to Systems Manager for SAP. { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ssm-sap:get*", "ssm-sap:list*" ], "Resource": "arn:*:ssm-sap:*:*:*" } ] } Systems Manager for SAP updates to AWS managed policies View details about updates to AWS managed policies for Systems Manager for SAP since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Systems Manager for SAP Document history page. Change Description Date AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Updated policy for managing application tags on Amazon EBS volumes. September 05, 2024 AWSSSMForSAPServiceLinkedRolePolicy – Updated policy August 05, 2024 Added ec2:CreateTags , ec2:DeleteTags , resource-groups:Tag , and resource-groups:Cr eateGroup actions to the policy. Policy updates 48
ssm-sap-013
ssm-sap.pdf
13
"Resource": "arn:*:ssm-sap:*:*:*" } ] } Systems Manager for SAP updates to AWS managed policies View details about updates to AWS managed policies for Systems Manager for SAP since this service began tracking these changes. For automatic alerts about changes to this page, subscribe to the RSS feed on the Systems Manager for SAP Document history page. Change Description Date AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Updated policy for managing application tags on Amazon EBS volumes. September 05, 2024 AWSSSMForSAPServiceLinkedRolePolicy – Updated policy August 05, 2024 Added ec2:CreateTags , ec2:DeleteTags , resource-groups:Tag , and resource-groups:Cr eateGroup actions to the policy. Policy updates 48 AWS Systems Manager for SAP User Guide Change Description Date These permissions enable you to create and delete tags on EC2 instances and volumes. These permissions also enable you to create, tag, and delete Systems Manager for SAP resource groups. AWSSystemsManagerForSAPFullAccess – Updated policy Added ec2:Start Instances and July 10, 2024 ec2:StopInstances actions to the policy. These permissions enable you to start or stop an SAP application registered with Systems Manager for SAP. AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Added ec2:Start Instances and April 26, 2024 ec2:StopInstances actions to the policy. These permissions enable you to start or stop an SAP application registered with Systems Manager for SAP. AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Added AWS Resource Group actions to the policy. November 21, 2023 AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Added Systems Manager action to the policy. November 17, 2023 AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Added Amazon EC2 and Systems Manager actions to October 27, 2023 the policy. Policy updates 49 AWS Systems Manager for SAP User Guide Change Description Date AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Added AWS Service Catalog and AWS Resource Group July 25, 2023 actions to the policy. AWSSSMForSAPServiceLinkedRolePolicy – Updated policy Added the PutMetricData Amazon CloudWatch action January 05, 2023 AWSSystemsManagerForSAPFullAccess – Updated policy AWSSystemsManagerForSAPFullAccess – New policy made available at launch AWSSystemsManagerForSAPRead OnlyAccess – New policy made available at launch AWSSSMForSAPServiceLinkedRolePolicy – New policy made available at launch to the policy. Updated the "arn:aws: iam::*:role/aws-se rvice-role/ssm-sap .amazonaws.com/AWS ServiceRoleForAWSS SMForSAP" resource in policy. AWSSystemsManagerF orSAPFullAccess grants an IAM user account full access to Systems Manager for SAP service. AWSSystemsManagerF orSAPReadOnlyAccess grants an IAM user account read only access to Systems Manager for SAP service. The AWSSSMForSAPServic eLinkedRolePolicy service- linked role policy provides access to Systems Manager for SAP. November 18, 2022 November 15, 2022 November 15, 2022 November 15, 2022 Policy updates 50 AWS Systems Manager for SAP User Guide Change Description Date Systems Manager for SAP started tracking changes Systems Manager for SAP started tracking changes for November 15, 2022 its AWS managed policies. Using service linked roles for AWS Systems Manager for SAP AWS Systems Manager for SAP uses AWS Identity and Access Management (IAM) service-linked roles. A service-linked role is a unique type of IAM role that is linked directly to Systems Manager for SAP. Service-linked roles are predefined by Systems Manager for SAP and include all of the permissions that the service requires to call other AWS services, including Amazon EC2, Systems Manager, IAM, Amazon CloudWatch, Amazon EventBridge, AWS Resource Groups, and AWS Service Catalog. A service-linked role makes setting up Systems Manager for SAP easier because you don’t have to manually add the necessary permissions. Systems Manager for SAP defines the permissions of its service-linked roles, and unless you make changes to the configuration, only Systems Manager for SAP can assume its roles. Configurable permissions include the trust policy and the permissions policy. You can't attach the permissions policy to any other IAM entity. For information about other services that support service-linked roles, see AWS Services That Work with IAM and look for the services that have Yes in the Service-Linked Role column. Follow the Yes link to view the service-linked role documentation for that service, if applicable. Service-linked role permissions for Systems Manager for SAP Systems Manager for SAP uses the service-linked role named AWSServiceRoleForAWSSSMForSAP and associates it with the AWSSSMForSAPServiceLinkedRolePolicy IAM policy – Provides AWS Systems Manager for SAP the permissions required to manage and integrate SAP applications on AWS. The policy enables Systems Manager for SAP to perform actions specified in the policy. These actions are from the following AWS services – Amazon EC2, Systems Manager, IAM, Amazon CloudWatch, Amazon EventBridge, AWS Resource Groups, and AWS Service Catalog. Permissions details This policy includes the following permissions. Using service linked roles 51 AWS Systems Manager for SAP User Guide • cloudwatch – Allows publication of Systems Manager for SAP metric data to Amazon CloudWatch. • ec2 – Allows description, start and stop of instances, and creation, deletion, and description of tags on EC2 instances that are with SSMForSAPManaged:True. The permission also enables creation and deletion of tags on EBS volumes attached to the EC2 instances tagged with SSMForSAPManaged:True. • eventbridge – Allows Amazon EventBridge to create,
ssm-sap-014
ssm-sap.pdf
14
Manager, IAM, Amazon CloudWatch, Amazon EventBridge, AWS Resource Groups, and AWS Service Catalog. Permissions details This policy includes the following permissions. Using service linked roles 51 AWS Systems Manager for SAP User Guide • cloudwatch – Allows publication of Systems Manager for SAP metric data to Amazon CloudWatch. • ec2 – Allows description, start and stop of instances, and creation, deletion, and description of tags on EC2 instances that are with SSMForSAPManaged:True. The permission also enables creation and deletion of tags on EBS volumes attached to the EC2 instances tagged with SSMForSAPManaged:True. • eventbridge – Allows Amazon EventBridge to create, update, and delete rules, and add or remove targets to the rules. • iam – Allows creation of roles and instance profiles. • resource-groups – Allows AWS Resource Groups to create and delete groups. • servicecatalog – Allows AWS Service Catalog to create, update, and delete applications, and attribute groups. The permission also enables association/disassociation of attribute groups to applications. • ssm – Allows SSM to describe documents, run commands, and return command details. The AWSSSMForSAPServiceLinkedRolePolicy service-linked role trusts the following services to assume the role: • ssm-sap.amazonaws.com The following is the full policy. { "Version": "2012-10-17", "Statement": [ { "Sid": "DescribeInstanceActions", "Effect": "Allow", "Action": [ "ec2:DescribeInstances", "ssm:GetCommandInvocation", "ssm:DescribeInstanceInformation" ], "Resource": "*" }, { "Sid": "DescribeInstanceStatus", "Effect": "Allow", Service-linked role permissions for Systems Manager for SAP 52 AWS Systems Manager for SAP User Guide "Action": "ec2:DescribeInstanceStatus", "Resource": "*" }, { "Sid": "TargetRuleActions", "Effect": "Allow", "Action": [ "events:DeleteRule", "events:PutTargets", "events:DescribeRule", "events:PutRule", "events:RemoveTargets" ], "Resource": [ "arn:*:events:*:*:rule/SSMSAPManagedRule*", "arn:*:events:*:*:event-bus/default" ] }, { "Sid": "DocumentActions", "Effect": "Allow", "Action": [ "ssm:DescribeDocument", "ssm:SendCommand" ], "Resource": [ "arn:*:ssm:*:*:document/AWSSystemsManagerSAP-*", "arn:*:ssm:*:*:document/AWSSSMSAP*", "arn:*:ssm:*:*:document/AWSSAP*" ] }, { "Sid": "CustomerSendCommand", "Effect": "Allow", "Action": "ssm:SendCommand", "Resource": "arn:*:ec2:*:*:instance/*", "Condition": { "StringEqualsIgnoreCase": { "ssm:resourceTag/SSMForSAPManaged": "True" } } }, { "Sid": "InstanceTagActions", Service-linked role permissions for Systems Manager for SAP 53 AWS Systems Manager for SAP User Guide "Effect": "Allow", "Action": [ "ec2:CreateTags", "ec2:DeleteTags" ], "Resource": "arn:*:ec2:*:*:instance/*", "Condition": { "Null": { "aws:RequestTag/awsApplication": "false" }, "StringEqualsIgnoreCase": { "ec2:ResourceTag/SSMForSAPManaged": "True" } } }, { "Sid": "DescribeTag", "Effect": "Allow", "Action": "ec2:DescribeTags", "Resource": "*" }, { "Sid": "GetApplication", "Effect": "Allow", "Action": "servicecatalog:GetApplication", "Resource": "arn:*:servicecatalog:*:*:*" }, { "Sid": "UpdateOrDeleteApplication", "Effect": "Allow", "Action": [ "servicecatalog:DeleteApplication", "servicecatalog:UpdateApplication" ], "Resource": "arn:*:servicecatalog:*:*:*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPCreated": "True" } } }, { "Sid": "CreateApplication", "Effect": "Allow", Service-linked role permissions for Systems Manager for SAP 54 User Guide AWS Systems Manager for SAP "Action": [ "servicecatalog:TagResource", "servicecatalog:CreateApplication" ], "Resource": "arn:*:servicecatalog:*:*:*", "Condition": { "StringEquals": { "aws:RequestTag/SSMForSAPCreated": "True" } } }, { "Sid": "CreateServiceLinkedRole", "Effect": "Allow", "Action": "iam:CreateServiceLinkedRole", "Resource": "arn:aws:iam::*:role/aws-service-role/servicecatalog- appregistry.amazonaws.com/AWSServiceRoleForAWSServiceCatalogAppRegistry", "Condition": { "StringEquals": { "iam:AWSServiceName": "servicecatalog-appregistry.amazonaws.com" } } }, { "Sid": "PutMetricData", "Effect": "Allow", "Action": "cloudwatch:PutMetricData", "Resource": "*", "Condition": { "StringEquals": { "cloudwatch:namespace": [ "AWS/Usage", "AWS/SSMForSAP" ] } } }, { "Sid": "CreateAttributeGroup", "Effect": "Allow", "Action": "servicecatalog:CreateAttributeGroup", "Resource": "arn:*:servicecatalog:*:*:/attribute-groups/*", "Condition": { "StringEquals": { Service-linked role permissions for Systems Manager for SAP 55 AWS Systems Manager for SAP User Guide "aws:RequestTag/SSMForSAPCreated": "True" } } }, { "Sid": "GetAttributeGroup", "Effect": "Allow", "Action": "servicecatalog:GetAttributeGroup", "Resource": "arn:*:servicecatalog:*:*:/attribute-groups/*" }, { "Sid": "DeleteAttributeGroup", "Effect": "Allow", "Action": "servicecatalog:DeleteAttributeGroup", "Resource": "arn:*:servicecatalog:*:*:/attribute-groups/*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPCreated": "True" } } }, { "Sid": "AttributeGroupActions", "Effect": "Allow", "Action": [ "servicecatalog:AssociateAttributeGroup", "servicecatalog:DisassociateAttributeGroup" ], "Resource": "arn:*:servicecatalog:*:*:*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPCreated": "True" } } }, { "Sid": "ListAssociatedAttributeGroups", "Effect": "Allow", "Action": "servicecatalog:ListAssociatedAttributeGroups", "Resource": "arn:*:servicecatalog:*:*:*" }, { "Sid": "CreateGroup", "Effect": "Allow", Service-linked role permissions for Systems Manager for SAP 56 AWS Systems Manager for SAP "Action": [ "resource-groups:CreateGroup", "resource-groups:Tag" ], User Guide "Resource": "arn:*:resource-groups:*:*:group/SystemsManagerForSAP-*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPCreated": "True" }, "ForAllValues:StringEquals": { "aws:TagKeys": [ "SSMForSAPCreated" ] } } }, { "Sid": "GetGroup", "Effect": "Allow", "Action": "resource-groups:GetGroup", "Resource": "arn:*:resource-groups:*:*:group/SystemsManagerForSAP-*" }, { "Sid": "DeleteGroup", "Effect": "Allow", "Action": "resource-groups:DeleteGroup", "Resource": "arn:*:resource-groups:*:*:group/SystemsManagerForSAP-*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPCreated": "True" } } }, { "Sid": "CreateAppTagResourceGroup", "Effect": "Allow", "Action": [ "resource-groups:CreateGroup" ], "Resource": "arn:*:resource-groups:*:*:group/AWS_AppRegistry_AppTag_*", "Condition": { "StringEquals": { "aws:RequestTag/EnableAWSServiceCatalogAppRegistry": "true" } Service-linked role permissions for Systems Manager for SAP 57 AWS Systems Manager for SAP } }, { "Sid": "TagAppTagResourceGroup", "Effect": "Allow", "Action": [ "resource-groups:Tag" ], User Guide "Resource": "arn:*:resource-groups:*:*:group/AWS_AppRegistry_AppTag_*", "Condition": { "StringEquals": { "aws:ResourceTag/EnableAWSServiceCatalogAppRegistry": "true" } } }, { "Sid": "GetAppTagResourceGroupConfig", "Effect": "Allow", "Action": [ "resource-groups:GetGroupConfiguration" ], "Resource": [ "arn:*:resource-groups:*:*:group/AWS_AppRegistry_AppTag_*" ] }, { "Sid": "StartStopInstances", "Effect": "Allow", "Action": [ "ec2:StartInstances", "ec2:StopInstances" ], "Resource": "arn:*:ec2:*:*:instance/*", "Condition": { "StringEqualsIgnoreCase": { "ec2:resourceTag/SSMForSAPManaged": "True" } } }, { "Sid": "SsmSapResourceGroup", "Effect": "Allow", "Action": [ "resource-groups:Tag", Service-linked role permissions for Systems Manager for SAP 58 AWS Systems Manager for SAP User Guide "resource-groups:CreateGroup" ], "Resource": "arn:aws:resource-groups:*:*:group/SystemsManagerForSAP-*", "Condition": { "StringEquals": { "aws:RequestTag/SSMForSAPCreated": "True" }, "ArnLike": { "aws:RequestTag/awsApplication": "arn:aws:resource- groups:*:*:group/*/*" }, "ForAllValues:StringEquals": { "aws:TagKeys": [ "SSMForSAPCreated", "awsApplication" ] } } }, { "Sid": "ManageSsmSapTagsOnEc2Instances", "Effect": "Allow", "Action": [ "ec2:CreateTags", "ec2:DeleteTags" ], "Resource": "arn:aws:ec2:*:*:instance/*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPManaged": "True" }, "ForAllValues:StringLike": { "aws:TagKeys": [ "SystemsManagerForSAP-*" ] } } }, { "Sid": "ManageSsmSapTagsOnEbsVolumes", "Effect": "Allow", "Action": [ "ec2:CreateTags", "ec2:DeleteTags" Service-linked role permissions
ssm-sap-015
ssm-sap.pdf
15
"Condition": { "StringEqualsIgnoreCase": { "ec2:resourceTag/SSMForSAPManaged": "True" } } }, { "Sid": "SsmSapResourceGroup", "Effect": "Allow", "Action": [ "resource-groups:Tag", Service-linked role permissions for Systems Manager for SAP 58 AWS Systems Manager for SAP User Guide "resource-groups:CreateGroup" ], "Resource": "arn:aws:resource-groups:*:*:group/SystemsManagerForSAP-*", "Condition": { "StringEquals": { "aws:RequestTag/SSMForSAPCreated": "True" }, "ArnLike": { "aws:RequestTag/awsApplication": "arn:aws:resource- groups:*:*:group/*/*" }, "ForAllValues:StringEquals": { "aws:TagKeys": [ "SSMForSAPCreated", "awsApplication" ] } } }, { "Sid": "ManageSsmSapTagsOnEc2Instances", "Effect": "Allow", "Action": [ "ec2:CreateTags", "ec2:DeleteTags" ], "Resource": "arn:aws:ec2:*:*:instance/*", "Condition": { "StringEquals": { "aws:ResourceTag/SSMForSAPManaged": "True" }, "ForAllValues:StringLike": { "aws:TagKeys": [ "SystemsManagerForSAP-*" ] } } }, { "Sid": "ManageSsmSapTagsOnEbsVolumes", "Effect": "Allow", "Action": [ "ec2:CreateTags", "ec2:DeleteTags" Service-linked role permissions for Systems Manager for SAP 59 User Guide AWS Systems Manager for SAP ], "Resource": "arn:aws:ec2:*:*:volume/*", "Condition": { "ForAllValues:StringLike": { "aws:TagKeys": [ "SystemsManagerForSAP-*" ] } } }, { "Sid": "ManageAppTagsOnEbsVolumes", "Effect": "Allow", "Action": [ "ec2:CreateTags", "ec2:DeleteTags" ], "Resource": "arn:aws:ec2:*:*:volume/*", "Condition": { "ArnLike": { "aws:RequestTag/awsApplication": "arn:aws:resource- groups:*:*:group/*/*" }, "ForAllValues:StringEquals": { "aws:TagKeys": [ "awsApplication" ] } } } ] } To view the update history of this policy, see Systems Manager for SAP updates to AWS managed policies. You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. For more information, see Service-Linked Role Permissions in the IAM User Guide. Service-linked role permissions for Systems Manager for SAP 60 AWS Systems Manager for SAP User Guide Creating a service-linked role for Systems Manager for SAP AWS Systems Manager for SAP uses AWS Identity and Access Management (IAM) service-linked roles. A service-linked role is a unique type of IAM role that is linked directly to Systems Manager for SAP. Service-linked roles are predefined by Systems Manager for SAP and include all of the permissions that the service requires to call other AWS services on your behalf. A service-linked role makes setting up Systems Manager for SAP easier because you don’t have to manually add the necessary permissions. Systems Manager for SAP defines the permissions of its service-linked roles, and unless you make changes to the configuration, only Systems Manager for SAP can assume its roles. Configurable permissions include the trust policy and the permissions policy. You can't attach the permissions policy to any other IAM entity. If you delete this service-linked role, Systems Manager for SAP automatically creates this service- linked role for you when you resume using Systems Manager for SAP. Editing a service-linked role for Systems Manager for SAP Systems Manager for SAP does not allow you to edit the AWSServiceRoleForAWSSSMForSAP service-linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can edit the description of the role using the Systems Manager for SAP console, CLI, or API. Deleting a service-linked role for Systems Manager for SAP To manually delete the service-linked role using IAM Use the IAM console, the AWS CLI, or the AWS API to delete the AWSServiceRoleForAWSSSMForSAP service-linked role. For more information, see Deleting a Service-Linked Role in the IAM User Guide. When deleting Systems Manager for SAP resources used by the AWSServiceRoleForAWSSSMForSAP SLR, you cannot have any running assessments (tasks for generating recommendations). No background assessments can be running, either. If assessments are running, the SLR deletion fails in the IAM console. If the SLR deletion fails, you can retry the deletion after all background tasks have completed. You don’t need to clean up any created resources before you delete the SLR. Creating a service-linked role for Systems Manager for SAP 61 AWS Systems Manager for SAP User Guide Supported Regions for Systems Manager for SAP service-linked roles Systems Manager for SAP supports using service-linked roles in all of the regions where the service is available. For more information, see Service endpoints for Systems Manager for SAP. Supported Regions for Systems Manager for SAP service-linked roles 62 AWS Systems Manager for SAP User Guide Monitoring Systems Manager for SAP AWS Systems Manager for SAP works with other AWS tools to enable you to monitor SAP workloads. These tools include the following: • Use Amazon CloudWatch and Amazon EventBridge to monitor AWS Systems Manager for SAP processes. • You can use CloudWatch to track metrics, create alarms, and view dashboards. • You can use EventBridge to view and monitor AWS Systems Manager for SAP events. • Use AWS CloudTrail to monitor AWS Systems Manager for SAP API calls. Topics • Monitoring AWS Systems Manager for SAP events using EventBridge • AWS Systems Manager for SAP metrics with Amazon CloudWatch • Logging AWS Systems Manager for SAP API calls using CloudTrail Monitoring AWS Systems Manager for SAP events using EventBridge Topics • Monitor events using EventBridge • Example Monitor events using EventBridge You can track the following AWS Systems Manager for SAP-related events in EventBridge. Event type Status Event details
ssm-sap-016
ssm-sap.pdf
16
dashboards. • You can use EventBridge to view and monitor AWS Systems Manager for SAP events. • Use AWS CloudTrail to monitor AWS Systems Manager for SAP API calls. Topics • Monitoring AWS Systems Manager for SAP events using EventBridge • AWS Systems Manager for SAP metrics with Amazon CloudWatch • Logging AWS Systems Manager for SAP API calls using CloudTrail Monitoring AWS Systems Manager for SAP events using EventBridge Topics • Monitor events using EventBridge • Example Monitor events using EventBridge You can track the following AWS Systems Manager for SAP-related events in EventBridge. Event type Status Event details SSM for SAP Operation State Change InProgress , Success, Error operationId, type, applicati onId, resourceId, resourceT ype, status, statusMessage Monitoring AWS Systems Manager for SAP events using EventBridge 63 AWS Systems Manager for SAP User Guide Use these sample JSON payloads if you would like to use these events programmatically. Event state JSON payload SSM for SAP Operation: InProgress SSM for SAP Operation: Success { "version": "0", "id": "6b41eac1-3685-c064-12a3-f1 6b57f30114", "detail-type": "SSM for SAP Operation State Change", "source": "aws.ssm-sap", "account": "112233445566", "time": "2023-01-25T08:04:33Z", "region": "us-east-1", "resources": [], "detail": { "operationId": "dbfd5c7d -0f5a-4ad3-87bf-d04b65eba21e", "type": "REGISTER_APPLICAT ION", "applicationId": "HANA_TEST", "resourceId": "HDB", "resourceType": "APPLICAT ION", "status": "InProgress", "statusMessage": null } } { "version": "0", "id": "05595cb1-ceac-1fb0-9040-04 5ca7865146", "detail-type": "SSM for SAP Operation State Change", "source": "aws.ssm-sap", "account": "112233445566", "time": "2023-01-26T04:45:43Z", "region": "us-east-1", "resources": [], "detail": { Monitor events using EventBridge 64 AWS Systems Manager for SAP User Guide Event state JSON payload SSM for SAP Operation: Error "operationId": "e5de5599 -3b1e-4892-9201-835e71c6090a", "type": "REGISTER_APPLICAT ION", "applicationId": "HANA_TEST", "resourceId": "HDB", "resourceType": "APPLICAT ION", "status": "Success", "statusMessage": null } } { "version": "0", "id": "fb715f90-e80c-1c7f-f179-e6 646f4b97d9", "detail-type": "SSM for SAP Operation State Change", "source": "aws.ssm-sap", "account": "112233445566", "time": "2023-01-26T04:46:34Z", "region": "us-east-1", "resources": [], "detail": { "operationId": "77c8f0e6 -6987-4e2b-9517-c5a44388992a", "type": "UPDATE_CREDENTIALS", "applicationId": "HANA", "resourceId": "HDB", "resourceType": "APPLICAT ION", "status": "Error", "statusMessage": null } } Monitor events using EventBridge 65 AWS Systems Manager for SAP Example User Guide The following is an event pattern example of Operation State Change event from AWS Systems Manager for SAP using the RegisterApplication API. { "source": ["aws.ssm-sap"], "detail-type": ["SSM for SAP Operation State Change"], "detail": { "type": ["REGISTER_APPLICATION"] } } AWS Systems Manager for SAP metrics with Amazon CloudWatch You can view CloudTrail metrics for AWS Systems Manager for SAP via AWS Management Console or AWS CLI. AWS Management Console Metrics are grouped first by the service namespace, and then by the various dimension combination within each namespace. Use the following steps to view the metrics in AWS Management Console. 1. Open https://console.aws.amazon.com/cloudwatch/. 2. 3. In the left navigation pane, select Metrics. In namespace, select AWS/SSMForSAP. AWS Command Line Interface Use the following command to view the metrics via AWS CLI. aws cloudwatch list-metrics --namespace "AWS/SSMForSAP" The following are all the metrics available to you. Example 66 AWS Systems Manager for SAP User Guide Metric Dimensions OperationStarted OperationType Units Count OperationSucceeded OperationType Count Description An operation is started. An operation is succeeded. OperationFailed OperationType Count An operation is failed. Usage Metrics AWS Systems Manager for SAP provides resource usage metrics in the AWS/Usage namespace. For more information, see AWS usage metrics. Logging AWS Systems Manager for SAP API calls using CloudTrail AWS Systems Manager for SAP is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user, role, or an AWS service. CloudTrail captures API calls for AWS Systems Manager for SAP as events. The calls captured include calls from the AWS Management Console and code calls to the AWS Systems Manager for SAP API operations. Using the information collected by CloudTrail, you can determine the request that was made to AWS Systems Manager for SAP, 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. 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 Log API calls using CloudTrail 67 AWS Systems Manager for SAP User Guide 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
ssm-sap-017
ssm-sap.pdf
17
request was made by another AWS service. 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 Log API calls using CloudTrail 67 AWS Systems Manager for SAP User Guide 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. For information about CloudTrail record contents, see CloudTrail record contents in the AWS CloudTrail User Guide. Log API calls using CloudTrail 68 AWS Systems Manager for SAP User Guide Quotas for AWS Systems Manager for SAP Your AWS account has default quotas, formerly referred to as limits, for each AWS service. Unless otherwise noted, each quota is Region-specific. You can request increases for some quotas, and other quotas cannot be increased. To view a list of the quotas for Systems Manager for SAP, see Systems Manager for SAP service quotas. To view the quotas for Systems Manager for SAP, open the Service Quotas console. In the navigation pane, choose AWS services and select Systems Manager for SAP. To request a quota increase, see Requesting a Quota Increase in the Service Quotas User Guide. If the quota is not yet available in Service Quotas, use the limit increase form. 69 AWS Systems Manager for SAP User Guide Troubleshooting AWS Systems Manager for SAP Topics • Database registration failure • InvalidInstanceIdException • AccessDeniedException • ResourceNotFoundException • Invalid control character • Expecting ',' delimiter • Maximum limit of resources • Unauthorized user • REFRESH_FAILED; Database connection mismatch • Unsupported setup • Input parameter errors • Application status: FAILED • StartApplication AccessDeniedException • StartApplication ConflictException • StartApplication ValidationException • StopApplication AccessDeniedException • StopApplication ConflictException • StopApplication ValidationException • Unsupported sslenforce setup Database registration failure Problem – Registration of SAP HANA database on AWS Systems Manager for SAP fails with an error Resolution – Use the following steps to resolve this error. 1. Deregister the database with the following command. Database registration failure 70 AWS Systems Manager for SAP User Guide aws ssm-sap deregister-application \ --application-id <YOUR_APPLICATION_ID> \ --region us-east-1 <YOUR_APPLICATION_ID> must be the same as the one used during registration. 2. Re-register the database. aws ssm-sap register-application \ --application-id <YOUR_APPLICATION_ID> \ --region us-east-1 Problem – Application DiscoveryStatus: REGISTRATION_FAILED; StatusMessage: The database ARN specified in registration input does not match discovered database connection. Resolution – The specified --database-arn does not match the database connection discovered on the SAP_ABAP instance. De-register the failed SAP ABAP application registration, and re- register with the correct --database-arn. For more information, see Register your SAP ABAP
ssm-sap-018
ssm-sap.pdf
18
registration failure 70 AWS Systems Manager for SAP User Guide aws ssm-sap deregister-application \ --application-id <YOUR_APPLICATION_ID> \ --region us-east-1 <YOUR_APPLICATION_ID> must be the same as the one used during registration. 2. Re-register the database. aws ssm-sap register-application \ --application-id <YOUR_APPLICATION_ID> \ --region us-east-1 Problem – Application DiscoveryStatus: REGISTRATION_FAILED; StatusMessage: The database ARN specified in registration input does not match discovered database connection. Resolution – The specified --database-arn does not match the database connection discovered on the SAP_ABAP instance. De-register the failed SAP ABAP application registration, and re- register with the correct --database-arn. For more information, see Register your SAP ABAP application with Systems Manager for SAP. InvalidInstanceIdException Problem – Error executing SSM document - InvalidInstanceIdException Instances [[<EC2_INSTANCE_ID>]] not in a valid state for account <ACCOUNT_ID> (Service: Ssm, Status Code: 400, Request ID: <REQUEST_ID>) Resolution – Ensure that your Amazon EC2 instance is active, and that the SSM Agent has been installed. For more information, see Verify AWS Systems Manager (SSM Agent) is running. After verification, deregister, and then re-register your application. AccessDeniedException Problem – Discovered 1 SAP instances. {HDB: Unable to decrypt credentials <SECRET_NAME>: An error occurred (AccessDeniedException) when calling the GetSecretValue operation: User: arn:aws:sts::<ACCOUNT_ID>:assumed- role/<EC2_IAM_ROLE>/<INSTANCE_ID> is not authorized to perform: InvalidInstanceIdException 71 AWS Systems Manager for SAP User Guide secretsmanager:GetSecretValue on resource: <SECRET_NAME> because no identity-based policy allows the secretsmanager:GetSecretValue action}, {HDB: Failed to discover HANA database ports. Exception type: <class 'IndexError'>}, REGISTER_APPLICATION Resolution – Ensure that your Amazon EC2 instance is setup correctly. For more information, see Set up required permissions for Amazon EC2 instance running SAP HANA database. The IAM role attached to your Amazon EC2 instance must have the permission to perform secretsmanager:GetSecretValue action. After verification, deregister, and then re-register your application. ResourceNotFoundException Problem – ERROR Discovered 1 SAP instances. {HDB: Unable to decrypt credentials <SECRET_NAME>: An error occurred (ResourceNotFoundException) when calling the GetSecretValue operation: Secrets Manager can't find the specified secret.},{HDB: Failed to discover HANA database ports. Exception type: <class 'IndexError'>}, REGISTER_APPLICATION Resolution – Verify and ensure that you are using the correct SECRET_NAME. For more information, see Register SAP HANA database credentials in AWS Secrets Manager. After verification, deregister, and then re-register your application. Problem – An error occurred (ResourceNotFoundException) when calling the RegisterApplication operation: Resource cannot be found Resolution – The --database-arn provided in the registration input parameter does not exist. Ensure that the connected SAP HANA database has been registered as an application with Systems Manager for SAP. The database must be registered before registering the SAP ABAP application. For more information, see Register database. Invalid control character Problem – Invalid control character at: line 2 column 32 (char 34) Resolution – Ensure that the JSON file that contains your SAP HANA database credentials is formatted correctly as a JSON file. Some characters may be pasted incorrectly after copying them from this file. Edit the file to remove line spaces, double quotes, spaces, and tabs. Add the ResourceNotFoundException 72 AWS Systems Manager for SAP User Guide formatted file content to your machine, terminal, and in your file editor. Save the changes to the file and retry registering your database. Expecting ',' delimiter Problem – Expecting ',' delimiter: line 1 column 36 (char 35) Resolution- – Ensure that the JSON file that contains your SAP HANA database credentials is formatted correctly as a JSON file. Some characters may be pasted incorrectly after copying them from this file. Edit the file to remove line spaces, double quotes, spaces, and tabs. Add the formatted file content to your machine, terminal, and in your file editor. Save the changes to the file and retry registering your database. Maximum limit of resources Problem – The number of registered resources under your account <ACCOUNTID> has reached max limit Resolution – With AWS Systems Manager for SAP, you can register up to 10 applications per AWS account. You can add up to 20 SAP HANA databases on each application. For more information, see Quotas for Systems Manager for SAP. Unauthorized user Problem – Error executing SSM document - SsmException User: arn:aws:sts::<ACCOUNT_ID>:assumed-role/AWSServiceRoleForAWSSSMForSAP/ ssm-sap is not authorized to perform: ssm:SendCommand on resource: arn:aws:ec2:us-east-1:<ACCOUNT_ID>:instance/<INSTANCE_ID> because no identity-based policy allows the ssm:SendCommand action (Service: Ssm, Status Code: 400, Request ID: 25ec41f5-1fa8-4a1a-80ac-6b7e85088d74) Resolution – Ensure that your Amazon EC2 instance has the SSMForSAPManaged tag with the value True. For more information, see Set up required permissions for Amazon EC2 instance running SAP HANA database. Expecting ',' delimiter 73 AWS Systems Manager for SAP User Guide REFRESH_FAILED; Database connection mismatch Problem – Application DiscoveryStatus: REFRESH_FAILED; StatusMessage: The database ARN specified in registration input does not match discovered database connection. Resolution – The specified --database-arn does not match the database connection discovered on the SAP_ABAP instance. Use the UpdateApplicationSettings API to provide the correct -- database-arn of your SAP HANA database along with the --application-id of
ssm-sap-019
ssm-sap.pdf
19
Ensure that your Amazon EC2 instance has the SSMForSAPManaged tag with the value True. For more information, see Set up required permissions for Amazon EC2 instance running SAP HANA database. Expecting ',' delimiter 73 AWS Systems Manager for SAP User Guide REFRESH_FAILED; Database connection mismatch Problem – Application DiscoveryStatus: REFRESH_FAILED; StatusMessage: The database ARN specified in registration input does not match discovered database connection. Resolution – The specified --database-arn does not match the database connection discovered on the SAP_ABAP instance. Use the UpdateApplicationSettings API to provide the correct -- database-arn of your SAP HANA database along with the --application-id of the SAP ABAP application. aws ssm-sap update-application-settings --application-id --database-arn Unsupported setup Problem – SSM-SAP only supports single-node SAP_ABAP deployment. Resolution – Systems Manager for SAP currently only supports single-node SAP ABAP deployment registration. Your SAP ABAP application must be connected to a single-node SAP HANA instance that resides in the same Amazon EC2 instance. All components belonging to the SAP ABAP application (ASCS, dialog instances, etc.) must also reside on the same Amazon EC2 instance. Input parameter errors Problem – An error occurred (ValidationException) when calling the RegisterApplication operation: Credentials and/or instance number is not expected for SAP applications with type SAP_ABAP. Resolution – --credentials and --sap-instance-number are inapplicable parameters for registering Systems Manager application of type SAP_ABAP. Remove both the parameters from the RegisterApplication call. Problem – An error occurred (ValidationException) when calling the RegisterApplication operation: The SID and database ARN of ASCS or Application Server must be specified for SAP applications with type SAP_ABAP. Resolution – The SID and ARN of ASCS of the connected SAP HANA database are required input parameters for registering SAP ABAP application. Ensure that the connected SAP HANA database REFRESH_FAILED; Database connection mismatch 74 AWS Systems Manager for SAP User Guide has been registered as a Systems Manager application before registering SAP ABAP with Systems Manager for SAP. For more information, see Register your SAP ABAP application with Systems Manager for SAP. Application status: FAILED Problem – System configuration change detected. To continue using this application as a standalone, for operations like backup/restore through AWS Backup, deregister this application and register again. Resolution – Systems Manager for SAP does not support moving a highly available (2 nodes) application to a single node system. You must re-register your primary application with the same application ID to ensure that the primary database is associated with the application, and that backup continuity is maintained. Use the following steps. 1. De-register the database with the following command. aws ssm-sap deregister-application \ --application-id <YOUR_APPLICATION_ID> \ --region <REGION> Note Use the same APPLICATION_ID as the one used during registration. 2. Use the following command to re-register the database with the same APPLICATION_ID. aws ssm-sap register-application \ --application-id <YOUR_APPLICATION_ID> \ --region <REGION> StartApplication AccessDeniedException Problem – An error occurred (AccessDeniedException) when calling the StartApplication operation: User: arn:aws:sts::<account_id> :assumed-role/ <role_name> is not authorized to perform: ssm-sap:StartApplication on resource: arn:aws:ssm-sap:<region>: <account_id>:HANA/<hana_application_id> Application status: FAILED 75 AWS Systems Manager for SAP User Guide Possible cause – When the StartApplication operation is performed on an SAP ABAP application and the procedure includes starting its connected HANA application, you must have the necessary IAM permissions to run ssm-sap:StartApplication on the connected application. Without those permissions, the error message will occur. Resolution – Add the permission ssm-sap:StartApplication against the HANA application to the role of the user calling StartApplication. StartApplication ConflictException Problem – Start Application can not be run on an already running application. Run ssm-sap start-application-refresh --application-id <ApplicationId> to ensure that the ssm-sap status reflects the current application state. Possible cause – The application you attempted to start is already running. Resolution – Refresh SAP application to ensure the ssm-sap status reflects the current application state. StartApplication ValidationException Problem – An error occurred (ValidationException) when calling the StartApplication operation: Caller lacks permissions to start Amazon EC2 instances Possible cause – When the StartApplication operation includes starting the Amazon EC2 instances running the SAP application, you must have the necessary IAM permissions to run ec2:StartInstances on the corresponding Amazon EC2 instances. Without those permissions, the error message will occur. Resolution – Add the permission ec2:StartInstances permission against the Amazon EC2 hosts of the SAP application to the role of the user calling StartApplication. StopApplication AccessDeniedException Problem – An error occurred (AccessDeniedException) when calling the StopApplication operation: User: arn:aws:sts::<account_id>:assumed-role/ StartApplication ConflictException 76 AWS Systems Manager for SAP User Guide <role_name> is not authorized to perform: ssm-sap:StopApplication on resource:arn:aws:ssm-sap:<region>:<account_id>:HANA/<hana_application_id> Possible cause – When the StopApplication operation is performed on an SAP ABAP application and the procedure includes starting its connected HANA application, you must have the necessary IAM permissions to run ssm-sap:StopApplication on the connected application. Without those permissions, the error message will occur. Resolution – Add the permission ssm-sap:StopApplication against the HANA application to the role of
ssm-sap-020
ssm-sap.pdf
20
the role of the user calling StartApplication. StopApplication AccessDeniedException Problem – An error occurred (AccessDeniedException) when calling the StopApplication operation: User: arn:aws:sts::<account_id>:assumed-role/ StartApplication ConflictException 76 AWS Systems Manager for SAP User Guide <role_name> is not authorized to perform: ssm-sap:StopApplication on resource:arn:aws:ssm-sap:<region>:<account_id>:HANA/<hana_application_id> Possible cause – When the StopApplication operation is performed on an SAP ABAP application and the procedure includes starting its connected HANA application, you must have the necessary IAM permissions to run ssm-sap:StopApplication on the connected application. Without those permissions, the error message will occur. Resolution – Add the permission ssm-sap:StopApplication against the HANA application to the role of the user calling StopApplication. StopApplication ConflictException Problem – An error occurred (ConflictException) when calling the StopApplication operation: The specified component is already stopped. or An error occurred (ConflictException) when calling the StopApplication operation: The specified component is not in a state that can be started or stopped. Possible cause – If your application status or status of the components are stale, the StopApplication operation can result in these or similar ConflictExceptions. Resolution – 1. Refresh SAP application. 2. Then, retry Stop SAP application. Possible cause – If the SSMForSAPManaged:True tag has not been applied to the EC2 instance. Resolution – Apply the SSMForSAPManaged:True tag to the EC2 instance. StopApplication ValidationException Problem – An error occurred (ValidationException) when calling the StopApplication operation: Caller lacks permissions to stop Amazon EC2 instances Possible cause – When the StopApplication operation includes stopping the Amazon EC2 instances running the SAP application, you must have the necessary IAM permissions to run StopApplication ConflictException 77 AWS Systems Manager for SAP User Guide ec2:StopInstances on the corresponding EC2 instances. Without those permissions, the error message will occur. Resolution – Add the permission ec2:StopInstances permission against the Amazon EC2 hosts of the SAP application to the role of the user calling StopApplication. Unsupported sslenforce setup Problem – HANA error code: 4321. HANA error message: connection failed: only secure connections are allowed Resolution – Set sslenfore to flase in the global.ini file. Unsupported sslenforce setup 78 AWS Systems Manager for SAP User Guide Document history of Systems Manager for SAP User Guide The following table describes the documentation releases for Systems Manager for SAP. Change Description Date Policy update New feature New feature Policy update Policy update Support update Policy update New feature Updated AWSSSMFor SAPServiceLinkedRolePolicy. September 5, 2024 Start and stop Systems Manager for SAP applicati on using AWS Management Console. August 22, 2024 Register SAP ABAP applicati on with Systems Manager for August 22, 2024 SAP. Updated AWSSSMFor SAPServiceLinkedRolePolicy. August 5, 2024 Updated the AWSSystem sManagerForSAPFullAccess policy. Systems Manager for SAP now supports Red Hat Enterprise Linux versions 9.0 and 9.2. July 10, 2024 May 10, 2024 Updated AWSSSMFor SAPServiceLinkedRolePolicy. May 10, 2024 Users can now stop and start SAP HANA applications May 10, 2024 79 AWS Systems Manager for SAP User Guide New feature Policy update Policy update New content Policy update New feature Policy update New feature and single node SAP ABAP applications. AWS Backup support for SAP HANA high availability deployments. Updated the AWSSSMFor SAPServiceLinkedRolePolicy policy. Updated the AWSSSMFor SAPServiceLinkedRolePolicy policy. December 22, 2023 November 21, 2023 November 17, 2023 Added details for Application tabs to the tutorial. November 17, 2023 Updated the AWSSSMFor SAPServiceLinkedRolePolicy policy. October 31, 2023 Register SAP ABAP applicati on with Systems Manager for October 31, 2023 SAP. Updated the AWSSSMFor SAPServiceLinkedRolePolicy July 26, 2023 policy. Register SAP HANA database with Systems Manager for SAP in a high availability setup. July 26, 2023 Updates Updated the Get started section of the guide. March 9, 2023 80 AWS Systems Manager for SAP User Guide New content New content New content Initial release Policy update Policy update Public preview Added Supported Regions section to the guide. Added Supported versions section to the guide. February 22, 2023 February 21, 2023 Added Tutorials section to the guide. February 15, 2023 Initial release of AWS Systems Manager for SAP User Guide. January 30, 2023 Updated the AWSSSMFor SAPServiceLinkedRolePolicy policy. Updated the AWSSystem sManagerForSAPFullAccess policy. Public preview of AWS Systems Manager for SAP. January 5, 2023 November 18, 2022 November 15, 2022 81
ssmsap-api-001
ssmsap-api.pdf
1
API Reference Guide AWS Systems Manager for SAP API Version 2018-05-10 Copyright © 2025 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. AWS Systems Manager for SAP API Reference Guide AWS Systems Manager for SAP: API Reference 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 Systems Manager for SAP Table of Contents API Reference Guide Welcome ........................................................................................................................................... 1 Actions .............................................................................................................................................. 2 DeleteResourcePermission .......................................................................................................................... 3 Request Syntax ........................................................................................................................................ 3 URI Request Parameters ........................................................................................................................ 3 Request Body ........................................................................................................................................... 3 Response Syntax ...................................................................................................................................... 4 Response Elements ................................................................................................................................. 4 Errors .......................................................................................................................................................... 4 See Also ..................................................................................................................................................... 5 DeregisterApplication ................................................................................................................................... 6 Request Syntax ........................................................................................................................................ 6 URI Request Parameters ........................................................................................................................ 6 Request Body ........................................................................................................................................... 6 Response Syntax ...................................................................................................................................... 6 Response Elements ................................................................................................................................. 6 Errors .......................................................................................................................................................... 7 See Also ..................................................................................................................................................... 7 GetApplication ............................................................................................................................................... 8 Request Syntax ........................................................................................................................................ 8 URI Request Parameters ........................................................................................................................ 8 Request Body ........................................................................................................................................... 8 Response Syntax ...................................................................................................................................... 9 Response Elements ................................................................................................................................. 9 Errors ....................................................................................................................................................... 10 See Also .................................................................................................................................................. 10 GetComponent ............................................................................................................................................ 12 Request Syntax ...................................................................................................................................... 12 URI Request Parameters ...................................................................................................................... 12 Request Body ......................................................................................................................................... 12 Response Syntax ................................................................................................................................... 13 Response Elements ............................................................................................................................... 14 Errors ....................................................................................................................................................... 15 See Also .................................................................................................................................................. 15 API Version 2018-05-10 iii AWS Systems Manager for SAP API Reference Guide GetDatabase ................................................................................................................................................ 17 Request Syntax ...................................................................................................................................... 17 URI Request Parameters ...................................................................................................................... 17 Request Body ......................................................................................................................................... 17 Response Syntax ................................................................................................................................... 18 Response Elements ............................................................................................................................... 19 Errors ....................................................................................................................................................... 19 See Also .................................................................................................................................................. 20 GetOperation ............................................................................................................................................... 21 Request Syntax ...................................................................................................................................... 21 URI Request Parameters ...................................................................................................................... 21 Request Body ......................................................................................................................................... 21 Response Syntax ................................................................................................................................... 21 Response Elements ............................................................................................................................... 22 Errors ....................................................................................................................................................... 22 See Also .................................................................................................................................................. 23 GetResourcePermission ............................................................................................................................. 24 Request Syntax ...................................................................................................................................... 24 URI Request Parameters ...................................................................................................................... 24 Request Body ......................................................................................................................................... 24 Response Syntax ................................................................................................................................... 25 Response Elements ............................................................................................................................... 25 Errors ....................................................................................................................................................... 25 See Also .................................................................................................................................................. 26 ListApplications ........................................................................................................................................... 27 Request Syntax ...................................................................................................................................... 27 URI Request Parameters ...................................................................................................................... 27 Request Body ......................................................................................................................................... 27 Response Syntax ................................................................................................................................... 28 Response Elements ............................................................................................................................... 28 Errors ....................................................................................................................................................... 29 See Also .................................................................................................................................................. 29 ListComponents .......................................................................................................................................... 31 Request Syntax ...................................................................................................................................... 31 URI Request Parameters ...................................................................................................................... 31 Request Body ......................................................................................................................................... 31 API Version 2018-05-10 iv AWS Systems Manager for SAP API Reference Guide Response Syntax ................................................................................................................................... 32 Response Elements ............................................................................................................................... 32 Errors ....................................................................................................................................................... 33 See Also .................................................................................................................................................. 33 ListDatabases ............................................................................................................................................... 35 Request Syntax ...................................................................................................................................... 35 URI Request Parameters ...................................................................................................................... 35 Request Body ......................................................................................................................................... 35 Response Syntax ................................................................................................................................... 36 Response Elements ............................................................................................................................... 37 Errors ....................................................................................................................................................... 37 See Also .................................................................................................................................................. 38 ListOperationEvents ................................................................................................................................... 39 Request Syntax ...................................................................................................................................... 39 URI Request Parameters ...................................................................................................................... 39 Request Body ......................................................................................................................................... 39 Response Syntax ................................................................................................................................... 40 Response Elements ............................................................................................................................... 41 Errors ....................................................................................................................................................... 41 See Also .................................................................................................................................................. 42 ListOperations ............................................................................................................................................. 43 Request Syntax ...................................................................................................................................... 43 URI Request Parameters ...................................................................................................................... 43 Request Body ......................................................................................................................................... 43 Response Syntax ................................................................................................................................... 44 Response Elements ............................................................................................................................... 45 Errors ....................................................................................................................................................... 45 See Also .................................................................................................................................................. 46 ListTagsForResource ................................................................................................................................... 47 Request Syntax ...................................................................................................................................... 47 URI Request Parameters ...................................................................................................................... 47 Request Body ......................................................................................................................................... 47 Response Syntax ................................................................................................................................... 47 Response Elements ............................................................................................................................... 47 Errors ....................................................................................................................................................... 48 See Also .................................................................................................................................................. 48 API Version 2018-05-10 v AWS Systems Manager for SAP API Reference Guide PutResourcePermission ............................................................................................................................. 50 Request Syntax ...................................................................................................................................... 50 URI Request Parameters ...................................................................................................................... 50 Request Body ......................................................................................................................................... 50 Response Syntax ................................................................................................................................... 51 Response Elements ............................................................................................................................... 51 Errors ....................................................................................................................................................... 51 See Also .................................................................................................................................................. 52 RegisterApplication .................................................................................................................................... 53 Request Syntax ...................................................................................................................................... 53 URI Request Parameters ...................................................................................................................... 54 Request Body ......................................................................................................................................... 54 Response Syntax ................................................................................................................................... 56 Response Elements ............................................................................................................................... 56 Errors ....................................................................................................................................................... 57 See Also .................................................................................................................................................. 58 StartApplication .......................................................................................................................................... 59 Request Syntax ...................................................................................................................................... 59 URI Request Parameters ...................................................................................................................... 59 Request Body ......................................................................................................................................... 59 Response Syntax ................................................................................................................................... 59 Response Elements ............................................................................................................................... 60 Errors ....................................................................................................................................................... 60 See Also .................................................................................................................................................. 61 StartApplicationRefresh ............................................................................................................................ 62 Request Syntax ...................................................................................................................................... 62 URI Request Parameters ...................................................................................................................... 62 Request Body ......................................................................................................................................... 62 Response Syntax ................................................................................................................................... 62 Response Elements ............................................................................................................................... 63 Errors ....................................................................................................................................................... 63 See Also .................................................................................................................................................. 64 StopApplication .......................................................................................................................................... 65 Request Syntax ...................................................................................................................................... 65 URI Request Parameters ...................................................................................................................... 65 Request Body ......................................................................................................................................... 65 API Version 2018-05-10 vi AWS Systems Manager for SAP API Reference Guide Response Syntax ................................................................................................................................... 66 Response Elements ............................................................................................................................... 66 Errors ....................................................................................................................................................... 66 See Also .................................................................................................................................................. 67 TagResource ................................................................................................................................................. 68 Request Syntax ...................................................................................................................................... 68 URI Request Parameters ...................................................................................................................... 68 Request Body ......................................................................................................................................... 68 Response Syntax ................................................................................................................................... 69 Response Elements ............................................................................................................................... 69 Errors ....................................................................................................................................................... 69 See Also .................................................................................................................................................. 69 UntagResource ............................................................................................................................................ 71 Request Syntax ...................................................................................................................................... 71 URI Request Parameters ...................................................................................................................... 71 Request Body ......................................................................................................................................... 71 Response Syntax ................................................................................................................................... 71 Response Elements ............................................................................................................................... 71 Errors
ssmsap-api-002
ssmsap-api.pdf
2
64 StopApplication .......................................................................................................................................... 65 Request Syntax ...................................................................................................................................... 65 URI Request Parameters ...................................................................................................................... 65 Request Body ......................................................................................................................................... 65 API Version 2018-05-10 vi AWS Systems Manager for SAP API Reference Guide Response Syntax ................................................................................................................................... 66 Response Elements ............................................................................................................................... 66 Errors ....................................................................................................................................................... 66 See Also .................................................................................................................................................. 67 TagResource ................................................................................................................................................. 68 Request Syntax ...................................................................................................................................... 68 URI Request Parameters ...................................................................................................................... 68 Request Body ......................................................................................................................................... 68 Response Syntax ................................................................................................................................... 69 Response Elements ............................................................................................................................... 69 Errors ....................................................................................................................................................... 69 See Also .................................................................................................................................................. 69 UntagResource ............................................................................................................................................ 71 Request Syntax ...................................................................................................................................... 71 URI Request Parameters ...................................................................................................................... 71 Request Body ......................................................................................................................................... 71 Response Syntax ................................................................................................................................... 71 Response Elements ............................................................................................................................... 71 Errors ....................................................................................................................................................... 72 See Also .................................................................................................................................................. 72 UpdateApplicationSettings ....................................................................................................................... 73 Request Syntax ...................................................................................................................................... 73 URI Request Parameters ...................................................................................................................... 73 Request Body ......................................................................................................................................... 73 Response Syntax ................................................................................................................................... 75 Response Elements ............................................................................................................................... 75 Errors ....................................................................................................................................................... 75 See Also .................................................................................................................................................. 76 Data Types ..................................................................................................................................... 77 Application ................................................................................................................................................... 78 Contents .................................................................................................................................................. 78 See Also .................................................................................................................................................. 80 ApplicationCredential ................................................................................................................................ 81 Contents .................................................................................................................................................. 81 See Also .................................................................................................................................................. 81 ApplicationSummary ................................................................................................................................. 83 API Version 2018-05-10 vii AWS Systems Manager for SAP API Reference Guide Contents .................................................................................................................................................. 83 See Also .................................................................................................................................................. 84 AssociatedHost ............................................................................................................................................ 85 Contents .................................................................................................................................................. 85 See Also .................................................................................................................................................. 85 BackintConfig .............................................................................................................................................. 87 Contents .................................................................................................................................................. 87 See Also .................................................................................................................................................. 87 Component .................................................................................................................................................. 88 Contents .................................................................................................................................................. 88 See Also .................................................................................................................................................. 92 ComponentInfo ........................................................................................................................................... 93 Contents .................................................................................................................................................. 93 See Also .................................................................................................................................................. 94 ComponentSummary ................................................................................................................................. 95 Contents .................................................................................................................................................. 95 See Also .................................................................................................................................................. 96 Database ....................................................................................................................................................... 97 Contents .................................................................................................................................................. 97 See Also .................................................................................................................................................. 99 DatabaseConnection ................................................................................................................................ 100 Contents ............................................................................................................................................... 100 See Also ................................................................................................................................................ 100 DatabaseSummary ................................................................................................................................... 102 Contents ............................................................................................................................................... 102 See Also ................................................................................................................................................ 103 Filter ............................................................................................................................................................ 104 Contents ............................................................................................................................................... 104 See Also ................................................................................................................................................ 104 Host ............................................................................................................................................................. 106 Contents ............................................................................................................................................... 106 See Also ................................................................................................................................................ 107 IpAddressMember .................................................................................................................................... 108 Contents ............................................................................................................................................... 108 See Also ................................................................................................................................................ 108 Operation ................................................................................................................................................... 109 API Version 2018-05-10 viii AWS Systems Manager for SAP API Reference Guide Contents ............................................................................................................................................... 109 See Also ................................................................................................................................................ 111 OperationEvent ........................................................................................................................................ 112 Contents ............................................................................................................................................... 112 See Also ................................................................................................................................................ 113 Resilience ................................................................................................................................................... 114 Contents ............................................................................................................................................... 114 See Also ................................................................................................................................................ 115 Resource ..................................................................................................................................................... 116 Contents ............................................................................................................................................... 116 See Also ................................................................................................................................................ 116 Common Parameters ................................................................................................................... 117 Common Errors ............................................................................................................................ 120 API Version 2018-05-10 ix AWS Systems Manager for SAP API Reference Guide Welcome This API reference provides descriptions, syntax, and other details about each of the actions and data types for AWS Systems Manager for SAP. The topic for each action shows the API request parameters and responses. This document was last published on May 21, 2025. API Version 2018-05-10 1 AWS Systems Manager for SAP API Reference Guide Actions The following actions are supported: • DeleteResourcePermission • DeregisterApplication • GetApplication • GetComponent • GetDatabase • GetOperation • GetResourcePermission • ListApplications • ListComponents • ListDatabases • ListOperationEvents • ListOperations • ListTagsForResource • PutResourcePermission • RegisterApplication • StartApplication • StartApplicationRefresh • StopApplication • TagResource • UntagResource • UpdateApplicationSettings API Version 2018-05-10 2 AWS Systems Manager for SAP API Reference Guide DeleteResourcePermission Removes permissions associated with the target database. Request Syntax POST /delete-resource-permission HTTP/1.1 Content-type: application/json { "ActionType": "string", "ResourceArn": "string", "SourceResourceArn": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ActionType Delete or restore the permissions on the target database. Type: String Valid Values: RESTORE Required: No ResourceArn The Amazon Resource Name (ARN) of the resource. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes DeleteResourcePermission API Version 2018-05-10 3 AWS Systems Manager for SAP SourceResourceArn API Reference Guide The Amazon Resource Name (ARN) of the source resource. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Policy": "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. Policy The policy that removes permissions on the target database. Type: String Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 Response Syntax API Version 2018-05-10 4 AWS Systems Manager for SAP ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException API Reference Guide The input fails to satisfy the constraints specified by an AWS service. 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 2018-05-10 5 AWS Systems Manager for SAP API Reference Guide DeregisterApplication Deregister an SAP application with AWS Systems Manager for
ssmsap-api-003
ssmsap-api.pdf
3
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 2018-05-10 5 AWS Systems Manager for SAP API Reference Guide DeregisterApplication Deregister an SAP application with AWS Systems Manager for SAP. This action does not affect the existing setup of your SAP workloads on Amazon EC2. Request Syntax POST /deregister-application HTTP/1.1 Content-type: application/json { "ApplicationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ 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. DeregisterApplication API Version 2018-05-10 6 AWS Systems Manager for SAP Errors API Reference Guide For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 UnauthorizedException The request is not authorized. HTTP Status Code: 401 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 Errors API Version 2018-05-10 7 AWS Systems Manager for SAP GetApplication API Reference Guide Gets an application registered with AWS Systems Manager for SAP. It also returns the components of the application. Request Syntax POST /get-application HTTP/1.1 Content-type: application/json { "ApplicationArn": "string", "ApplicationId": "string", "AppRegistryArn": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationArn The Amazon Resource Name (ARN) of the application. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. GetApplication API Version 2018-05-10 8 API Reference Guide AWS Systems Manager for SAP Pattern: [\w\d\.-]+ Required: No AppRegistryArn The Amazon Resource Name (ARN) of the application registry. Type: String Pattern: arn:aws:servicecatalog:[a-z0-9:\/-]+ Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Application": { "AppRegistryArn": "string", "Arn": "string", "AssociatedApplicationArns": [ "string" ], "Components": [ "string" ], "DiscoveryStatus": "string", "Id": "string", "LastUpdated": number, "Status": "string", "StatusMessage": "string", "Type": "string" }, "Tags": { "string" : "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. Response Syntax API Version 2018-05-10 9 AWS Systems Manager for SAP Application API Reference Guide Returns all of the metadata of an application registered with AWS Systems Manager for SAP. Type: Application object Tags The tags of a registered application. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 Errors API Version 2018-05-10 10 AWS Systems Manager for SAP • 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 Guide See Also API Version 2018-05-10 11 AWS Systems Manager for SAP GetComponent API Reference Guide Gets the component of an application registered with AWS Systems Manager for SAP. Request Syntax POST /get-component HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "ComponentId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of
ssmsap-api-004
ssmsap-api.pdf
4
AWS SDK for Kotlin • AWS SDK for PHP V3 • AWS SDK for Python • AWS SDK for Ruby V3 API Reference Guide See Also API Version 2018-05-10 11 AWS Systems Manager for SAP GetComponent API Reference Guide Gets the component of an application registered with AWS Systems Manager for SAP. Request Syntax POST /get-component HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "ComponentId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes ComponentId The ID of the component. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. GetComponent API Version 2018-05-10 12 API Reference Guide AWS Systems Manager for SAP Pattern: [\w\d-]+ Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { "Component": { "ApplicationId": "string", "Arn": "string", "AssociatedHost": { "Ec2InstanceId": "string", "Hostname": "string", "IpAddresses": [ { "AllocationType": "string", "IpAddress": "string", "Primary": boolean } ], "OsVersion": "string" }, "ChildComponents": [ "string" ], "ComponentId": "string", "ComponentType": "string", "DatabaseConnection": { "ConnectionIp": "string", "DatabaseArn": "string", "DatabaseConnectionMethod": "string" }, "Databases": [ "string" ], "HdbVersion": "string", "Hosts": [ { "EC2InstanceId": "string", "HostIp": "string", "HostName": "string", "HostRole": "string", "InstanceId": "string", "OsVersion": "string" Response Syntax API Version 2018-05-10 13 API Reference Guide AWS Systems Manager for SAP } ], "LastUpdated": number, "ParentComponent": "string", "PrimaryHost": "string", "Resilience": { "ClusterStatus": "string", "EnqueueReplication": boolean, "HsrOperationMode": "string", "HsrReplicationMode": "string", "HsrTier": "string" }, "SapFeature": "string", "SapHostname": "string", "SapKernelVersion": "string", "Sid": "string", "Status": "string", "SystemNumber": "string" }, "Tags": { "string" : "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. Component The component of an application registered with AWS Systems Manager for SAP. Type: Component object Tags The tags of a component. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Response Elements API Version 2018-05-10 14 AWS Systems Manager for SAP API Reference Guide Value Length Constraints: Minimum length of 1. Maximum length of 256. Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 UnauthorizedException The request is not authorized. HTTP Status Code: 401 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 Errors API Version 2018-05-10 15 AWS Systems Manager for SAP API Reference Guide See Also API Version 2018-05-10 16 AWS Systems Manager for SAP GetDatabase API Reference Guide Gets the SAP HANA database of an application registered with AWS Systems Manager for SAP. Request Syntax POST /get-database HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "ComponentId": "string", "DatabaseArn": "string", "DatabaseId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No ComponentId The ID of the component. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. GetDatabase API Version 2018-05-10 17 AWS Systems Manager for SAP Pattern: [\w\d-]+ Required: No DatabaseArn The Amazon Resource Name (ARN) of the database. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No DatabaseId The ID of the database. Type: String Length Constraints: Minimum length of 1. Maximum length of 300. Pattern: .*[\w\d]+ Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Database": { "ApplicationId": "string", "Arn": "string", "ComponentId": "string", "ConnectedComponentArns": [ "string" ], "Credentials": [ { "CredentialType": "string", "DatabaseName": "string", "SecretId": "string" } ], Response Syntax API Reference Guide API Version 2018-05-10 18 AWS Systems Manager for SAP API Reference Guide "DatabaseId": "string", "DatabaseName": "string", "DatabaseType": "string", "LastUpdated": number, "PrimaryHost": "string", "SQLPort": number, "Status": "string" }, "Tags": { "string" : "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. Database The SAP HANA database of an application registered with AWS Systems Manager for SAP. Type: Database object Tags The tags of a database. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. Errors For information about the errors that are common to all actions,
ssmsap-api-005
ssmsap-api.pdf
5
"string", "DatabaseType": "string", "LastUpdated": number, "PrimaryHost": "string", "SQLPort": number, "Status": "string" }, "Tags": { "string" : "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. Database The SAP HANA database of an application registered with AWS Systems Manager for SAP. Type: Database object Tags The tags of a database. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. Response Elements API Version 2018-05-10 19 AWS Systems Manager for SAP HTTP Status Code: 500 ValidationException The input fails to satisfy the constraints specified by an AWS service. API Reference Guide 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 2018-05-10 20 AWS Systems Manager for SAP GetOperation Gets the details of an operation by specifying the operation ID. API Reference Guide Request Syntax POST /get-operation HTTP/1.1 Content-type: application/json { "OperationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. OperationId The ID of the operation. Type: String Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { "Operation": { "EndTime": number, GetOperation API Version 2018-05-10 21 AWS Systems Manager for SAP API Reference Guide "Id": "string", "LastUpdatedTime": number, "Properties": { "string" : "string" }, "ResourceArn": "string", "ResourceId": "string", "ResourceType": "string", "StartTime": number, "Status": "string", "StatusMessage": "string", "Type": "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. Operation Returns the details of an operation. Type: Operation object Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ValidationException The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 Response Elements API Version 2018-05-10 22 AWS Systems Manager for SAP See Also API Reference Guide 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 2018-05-10 23 AWS Systems Manager for SAP API Reference Guide GetResourcePermission Gets permissions associated with the target database. Request Syntax POST /get-resource-permission HTTP/1.1 Content-type: application/json { "ActionType": "string", "ResourceArn": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ActionType Type: String Valid Values: RESTORE Required: No ResourceArn The Amazon Resource Name (ARN) of the resource. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes GetResourcePermission API Version 2018-05-10 24 API Reference Guide AWS Systems Manager for SAP Response Syntax HTTP/1.1 200 Content-type: application/json { "Policy": "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. Policy Type: String Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 Response Syntax API Version 2018-05-10 25 AWS Systems Manager for SAP See Also API Reference Guide 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 2018-05-10 26 AWS Systems Manager for SAP ListApplications API Reference Guide Lists all the applications registered with AWS Systems
ssmsap-api-006
ssmsap-api.pdf
6
See Also API Reference Guide 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 2018-05-10 26 AWS Systems Manager for SAP ListApplications API Reference Guide Lists all the applications registered with AWS Systems Manager for SAP. Request Syntax POST /list-applications HTTP/1.1 Content-type: application/json { "Filters": [ { "Name": "string", "Operator": "string", "Value": "string" } ], "MaxResults": number, "NextToken": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. Filters The filter of name, value, and operator. Type: Array of Filter objects Array Members: Minimum number of 1 item. Maximum number of 10 items. Required: No MaxResults The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. ListApplications API Version 2018-05-10 27 AWS Systems Manager for SAP Type: Integer Valid Range: Minimum value of 1. Maximum value of 50. Required: No NextToken The token for the next page of results. API Reference Guide Type: String Pattern: .{16,1024} Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Applications": [ { "Arn": "string", "DiscoveryStatus": "string", "Id": "string", "Tags": { "string" : "string" }, "Type": "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. Response Syntax API Version 2018-05-10 28 AWS Systems Manager for SAP Applications API Reference Guide The applications registered with AWS Systems Manager for SAP. Type: Array of ApplicationSummary objects NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 Errors API Version 2018-05-10 29 API Reference Guide AWS Systems Manager for SAP • 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 2018-05-10 30 AWS Systems Manager for SAP ListComponents API Reference Guide Lists all the components registered with AWS Systems Manager for SAP. Request Syntax POST /list-components HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "MaxResults": number, "NextToken": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No MaxResults The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. If you do not specify a value for MaxResults, the request returns 50 items per page by default. Type: Integer ListComponents API Version 2018-05-10 31 AWS Systems Manager for SAP API Reference Guide Valid Range: Minimum value of 1. Maximum value of 50. Required: No NextToken The token for the next page of results. Type: String Pattern: .{16,1024} Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Components": [ { "ApplicationId": "string", "Arn": "string", "ComponentId": "string", "ComponentType": "string", "Tags": { "string" : "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. Components List of components registered with AWS System Manager for SAP. Response Syntax API Version 2018-05-10 32 AWS Systems Manager for SAP API Reference Guide Type: Array of ComponentSummary objects NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status
ssmsap-api-007
ssmsap-api.pdf
7
the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Components List of components registered with AWS System Manager for SAP. Response Syntax API Version 2018-05-10 32 AWS Systems Manager for SAP API Reference Guide Type: Array of ComponentSummary objects NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 UnauthorizedException The request is not authorized. HTTP Status Code: 401 ValidationException The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 See Also For more information about using this API in one of the language-specific AWS SDKs, see the following: Errors API Version 2018-05-10 33 API Reference Guide AWS Systems Manager for SAP • 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 2018-05-10 34 AWS Systems Manager for SAP ListDatabases API Reference Guide Lists the SAP HANA databases of an application registered with AWS Systems Manager for SAP. Request Syntax POST /list-databases HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "ComponentId": "string", "MaxResults": number, "NextToken": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No ComponentId The ID of the component. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. ListDatabases API Version 2018-05-10 35 AWS Systems Manager for SAP Pattern: [\w\d-]+ Required: No MaxResults API Reference Guide The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. If you do not specify a value for MaxResults, the request returns 50 items per page by default. Type: Integer Valid Range: Minimum value of 1. Maximum value of 50. Required: No NextToken The token for the next page of results. Type: String Pattern: .{16,1024} Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Databases": [ { "ApplicationId": "string", "Arn": "string", "ComponentId": "string", "DatabaseId": "string", "DatabaseType": "string", "Tags": { "string" : "string" } } Response Syntax API Version 2018-05-10 36 AWS Systems Manager for SAP ], "NextToken": "string" } Response Elements API Reference Guide If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. Databases The SAP HANA databases of an application. Type: Array of DatabaseSummary objects NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. Response Elements API Version 2018-05-10 37 AWS Systems Manager for SAP HTTP Status Code: 400 See Also API Reference Guide 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 2018-05-10 38 AWS Systems Manager for SAP API Reference Guide ListOperationEvents Returns a list of operations events. Available parameters include OperationID, as well as optional parameters MaxResults, NextToken, and Filters. Request Syntax POST /list-operation-events HTTP/1.1 Content-type: application/json { "Filters": [ { "Name": "string", "Operator": "string", "Value": "string" } ], "MaxResults": number, "NextToken": "string", "OperationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. Filters Optionally specify filters to narrow the returned operation event items. Valid filter names include status, resourceID, and resourceType. The valid operator for all three filters is Equals. Type: Array of Filter objects ListOperationEvents API Version 2018-05-10 39 AWS Systems Manager for
ssmsap-api-008
ssmsap-api.pdf
8
OperationID, as well as optional parameters MaxResults, NextToken, and Filters. Request Syntax POST /list-operation-events HTTP/1.1 Content-type: application/json { "Filters": [ { "Name": "string", "Operator": "string", "Value": "string" } ], "MaxResults": number, "NextToken": "string", "OperationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. Filters Optionally specify filters to narrow the returned operation event items. Valid filter names include status, resourceID, and resourceType. The valid operator for all three filters is Equals. Type: Array of Filter objects ListOperationEvents API Version 2018-05-10 39 AWS Systems Manager for SAP API Reference Guide Array Members: Minimum number of 1 item. Maximum number of 10 items. Required: No MaxResults The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. If you do not specify a value for MaxResults, the request returns 50 items per page by default. Type: Integer Valid Range: Minimum value of 1. Maximum value of 50. Required: No NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Required: No OperationId The ID of the operation. Type: String Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { Response Syntax API Version 2018-05-10 40 AWS Systems Manager for SAP API Reference Guide "NextToken": "string", "OperationEvents": [ { "Description": "string", "Resource": { "ResourceArn": "string", "ResourceType": "string" }, "Status": "string", "StatusMessage": "string", "Timestamp": 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. NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} OperationEvents A returned list of operation events that meet the filter criteria. Type: Array of OperationEvent objects Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. Response Elements API Version 2018-05-10 41 AWS Systems Manager for SAP HTTP Status Code: 500 ValidationException The input fails to satisfy the constraints specified by an AWS service. API Reference Guide 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 2018-05-10 42 AWS Systems Manager for SAP ListOperations API Reference Guide Lists the operations performed by AWS Systems Manager for SAP. Request Syntax POST /list-operations HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "Filters": [ { "Name": "string", "Operator": "string", "Value": "string" } ], "MaxResults": number, "NextToken": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes ListOperations API Version 2018-05-10 43 AWS Systems Manager for SAP Filters The filters of an operation. Type: Array of Filter objects API Reference Guide Array Members: Minimum number of 1 item. Maximum number of 10 items. Required: No MaxResults The maximum number of results to return with a single call. To retrieve the remaining results, make another call with the returned nextToken value. If you do not specify a value for MaxResults, the request returns 50 items per page by default. Type: Integer Valid Range: Minimum value of 1. Maximum value of 50. Required: No NextToken The token for the next page of results. Type: String Pattern: .{16,1024} Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "NextToken": "string", "Operations": [ { "EndTime": number, "Id": "string", Response Syntax API Version 2018-05-10 44 AWS Systems Manager for SAP API Reference Guide "LastUpdatedTime": number, "Properties": { "string" : "string" }, "ResourceArn": "string", "ResourceId": "string", "ResourceType": "string", "StartTime": number, "Status": "string", "StatusMessage": "string", "Type": "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. NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Operations List of operations performed by AWS Systems Manager for SAP. Type: Array of Operation objects Errors For information about the errors that are
ssmsap-api-009
ssmsap-api.pdf
9
{ "string" : "string" }, "ResourceArn": "string", "ResourceId": "string", "ResourceType": "string", "StartTime": number, "Status": "string", "StatusMessage": "string", "Type": "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. NextToken The token to use to retrieve the next page of results. This value is null when there are no more results to return. Type: String Pattern: .{16,1024} Operations List of operations performed by AWS Systems Manager for SAP. Type: Array of Operation objects Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. Response Elements API Version 2018-05-10 45 AWS Systems Manager for SAP HTTP Status Code: 500 ValidationException The input fails to satisfy the constraints specified by an AWS service. API Reference Guide 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 2018-05-10 46 AWS Systems Manager for SAP API Reference Guide ListTagsForResource Lists all tags on an SAP HANA application and/or database registered with AWS Systems Manager for SAP. Request Syntax GET /tags/resourceArn HTTP/1.1 URI Request Parameters The request uses the following URI parameters. resourceArn The Amazon Resource Name (ARN) of the resource. Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes Request Body The request does not have a request body. Response Syntax HTTP/1.1 200 Content-type: application/json { "tags": { "string" : "string" } } Response Elements If the action is successful, the service sends back an HTTP 200 response. ListTagsForResource API Version 2018-05-10 47 AWS Systems Manager for SAP API Reference Guide The following data is returned in JSON format by the service. tags Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. Errors For information about the errors that are common to all actions, see Common Errors. ConflictException A conflict has occurred. HTTP Status Code: 409 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 Errors API Version 2018-05-10 48 AWS Systems Manager for SAP • 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 Guide See Also API Version 2018-05-10 49 AWS Systems Manager for SAP API Reference Guide PutResourcePermission Adds permissions to the target database. Request Syntax POST /put-resource-permission HTTP/1.1 Content-type: application/json { "ActionType": "string", "ResourceArn": "string", "SourceResourceArn": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ActionType Type: String Valid Values: RESTORE Required: Yes ResourceArn Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes SourceResourceArn PutResourcePermission API Version 2018-05-10 50 AWS Systems Manager for SAP Type: String API Reference Guide Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { "Policy": "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. Policy Type: String Errors For information about the errors that are common to all actions, see Common Errors. InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 Response Syntax API Version 2018-05-10 51 AWS Systems Manager for SAP ValidationException API Reference Guide The input fails to satisfy the constraints specified by an AWS service. 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 2018-05-10 52 AWS Systems Manager for SAP API Reference Guide RegisterApplication Register an SAP application with AWS Systems Manager for SAP.
ssmsap-api-010
ssmsap-api.pdf
10
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 2018-05-10 52 AWS Systems Manager for SAP API Reference Guide RegisterApplication Register an SAP application with AWS Systems Manager for SAP. You must meet the following requirements before registering. The SAP application you want to register with AWS Systems Manager for SAP is running on Amazon EC2. AWS Systems Manager Agent must be setup on an Amazon EC2 instance along with the required IAM permissions. Amazon EC2 instance(s) must have access to the secrets created in AWS Secrets Manager to manage SAP applications and components. Request Syntax POST /register-application HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "ApplicationType": "string", "ComponentsInfo": [ { "ComponentType": "string", "Ec2InstanceId": "string", "Sid": "string" } ], "Credentials": [ { "CredentialType": "string", "DatabaseName": "string", "SecretId": "string" } ], "DatabaseArn": "string", "Instances": [ "string" ], "SapInstanceNumber": "string", "Sid": "string", "Tags": { "string" : "string" RegisterApplication API Version 2018-05-10 53 AWS Systems Manager for SAP API Reference Guide } } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes ApplicationType The type of the application. Type: String Valid Values: HANA | SAP_ABAP Required: Yes ComponentsInfo This is an optional parameter for component details to which the SAP ABAP application is attached, such as Web Dispatcher. This is an array of ApplicationComponent objects. You may input 0 to 5 items. Type: Array of ComponentInfo objects Array Members: Minimum number of 0 items. Maximum number of 5 items. URI Request Parameters API Version 2018-05-10 54 API Reference Guide AWS Systems Manager for SAP Required: No Credentials The credentials of the SAP application. Type: Array of ApplicationCredential objects Array Members: Minimum number of 0 items. Maximum number of 20 items. Required: No DatabaseArn The Amazon Resource Name of the SAP HANA database. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No Instances The Amazon EC2 instances on which your SAP application is running. Type: Array of strings Array Members: Fixed number of 1 item. Pattern: i-[\w\d]{8}$|^i-[\w\d]{17} Required: Yes SapInstanceNumber The SAP instance number of the application. Type: String Pattern: [0-9]{2} Required: No Sid The System ID of the application. Request Body API Version 2018-05-10 55 API Reference Guide AWS Systems Manager for SAP Type: String Pattern: [A-Z][A-Z0-9]{2} Required: No Tags The tags to be attached to the SAP application. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Application": { "AppRegistryArn": "string", "Arn": "string", "AssociatedApplicationArns": [ "string" ], "Components": [ "string" ], "DiscoveryStatus": "string", "Id": "string", "LastUpdated": number, "Status": "string", "StatusMessage": "string", "Type": "string" }, "OperationId": "string" } Response Elements If the action is successful, the service sends back an HTTP 200 response. Response Syntax API Version 2018-05-10 56 AWS Systems Manager for SAP API Reference Guide The following data is returned in JSON format by the service. Application The application registered with AWS Systems Manager for SAP. Type: Application object OperationId The ID of the operation. Type: String Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Errors For information about the errors that are common to all actions, see Common Errors. ConflictException A conflict has occurred. HTTP Status Code: 409 InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. HTTP Status Code: 400 Errors API Version 2018-05-10 57 AWS Systems Manager for SAP See Also API Reference Guide 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 2018-05-10 58 API Reference Guide AWS Systems Manager for SAP StartApplication Request is an operation which starts an application. Parameter ApplicationId is required. Request Syntax POST /start-application HTTP/1.1 Content-type: application/json { "ApplicationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the
ssmsap-api-011
ssmsap-api.pdf
11
• 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 2018-05-10 58 API Reference Guide AWS Systems Manager for SAP StartApplication Request is an operation which starts an application. Parameter ApplicationId is required. Request Syntax POST /start-application HTTP/1.1 Content-type: application/json { "ApplicationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json StartApplication API Version 2018-05-10 59 AWS Systems Manager for SAP API Reference Guide { "OperationId": "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. OperationId The ID of the operation. Type: String Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Errors For information about the errors that are common to all actions, see Common Errors. ConflictException A conflict has occurred. HTTP Status Code: 409 InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. Response Elements API Version 2018-05-10 60 AWS Systems Manager for SAP HTTP Status Code: 400 See Also API Reference Guide 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 2018-05-10 61 AWS Systems Manager for SAP API Reference Guide StartApplicationRefresh Refreshes a registered application. Request Syntax POST /start-application-refresh HTTP/1.1 Content-type: application/json { "ApplicationId": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes Response Syntax HTTP/1.1 200 Content-type: application/json { "OperationId": "string" StartApplicationRefresh API Version 2018-05-10 62 AWS Systems Manager for SAP } Response Elements API Reference Guide If the action is successful, the service sends back an HTTP 200 response. The following data is returned in JSON format by the service. OperationId The ID of the operation. Type: String Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Errors For information about the errors that are common to all actions, see Common Errors. ConflictException A conflict has occurred. HTTP Status Code: 409 InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 UnauthorizedException The request is not authorized. HTTP Status Code: 401 Response Elements API Version 2018-05-10 63 AWS Systems Manager for SAP ValidationException API Reference Guide The input fails to satisfy the constraints specified by an AWS service. 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 2018-05-10 64 AWS Systems Manager for SAP StopApplication Request is an operation to stop an application. API Reference Guide Parameter ApplicationId is required. Parameters StopConnectedEntity and IncludeEc2InstanceShutdown are optional. Request Syntax POST /stop-application HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "IncludeEc2InstanceShutdown": boolean, "StopConnectedEntity": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes IncludeEc2InstanceShutdown Boolean. If included and if set to True, the StopApplication operation will shut down the associated Amazon EC2 instance in addition to the application. StopApplication API Version 2018-05-10 65 AWS Systems Manager for SAP API Reference Guide Type: Boolean Required: No StopConnectedEntity Specify the ConnectedEntityType. Accepted type is DBMS. If this parameter is included, the connected DBMS (Database Management System) will be stopped. Type: String Valid Values: DBMS Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "OperationId": "string" }
ssmsap-api-012
ssmsap-api.pdf
12
of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: Yes IncludeEc2InstanceShutdown Boolean. If included and if set to True, the StopApplication operation will shut down the associated Amazon EC2 instance in addition to the application. StopApplication API Version 2018-05-10 65 AWS Systems Manager for SAP API Reference Guide Type: Boolean Required: No StopConnectedEntity Specify the ConnectedEntityType. Accepted type is DBMS. If this parameter is included, the connected DBMS (Database Management System) will be stopped. Type: String Valid Values: DBMS Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "OperationId": "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. OperationId The ID of the operation. Type: String Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Errors For information about the errors that are common to all actions, see Common Errors. Response Syntax API Version 2018-05-10 66 API Reference Guide AWS Systems Manager for SAP ConflictException A conflict has occurred. HTTP Status Code: 409 InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 2018-05-10 67 API Reference Guide AWS Systems Manager for SAP TagResource Creates tag for a resource by specifying the ARN. Request Syntax POST /tags/resourceArn HTTP/1.1 Content-type: application/json { "tags": { "string" : "string" } } URI Request Parameters The request uses the following URI parameters. resourceArn The Amazon Resource Name (ARN) of the resource. Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes Request Body The request accepts the following data in JSON format. tags The tags on a resource. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. TagResource API Version 2018-05-10 68 AWS Systems Manager for SAP Required: Yes Response Syntax HTTP/1.1 200 Response Elements API Reference Guide 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. ConflictException A conflict has occurred. HTTP Status Code: 409 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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++ Response Syntax API Version 2018-05-10 69 AWS Systems Manager for SAP • 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 Guide See Also API Version 2018-05-10 70 API Reference Guide AWS Systems Manager for SAP UntagResource Delete the tags for a resource. Request Syntax DELETE /tags/resourceArn?tagKeys=tagKeys HTTP/1.1 URI Request Parameters The request uses the following URI parameters. resourceArn The Amazon Resource Name (ARN) of the resource. Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: Yes tagKeys Adds/updates or removes credentials for applications registered with AWS Systems Manager for SAP. Pattern: (?!aws:)[a-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. UntagResource API Version 2018-05-10 71 AWS Systems Manager for SAP Errors API Reference Guide For information about the errors that are common to all actions, see Common Errors. ConflictException A conflict has occurred. HTTP Status Code: 409 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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
ssmsap-api-013
ssmsap-api.pdf
13
The resource is not available. HTTP Status Code: 404 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 Errors API Version 2018-05-10 72 AWS Systems Manager for SAP API Reference Guide UpdateApplicationSettings Updates the settings of an application registered with AWS Systems Manager for SAP. Request Syntax POST /update-application-settings HTTP/1.1 Content-type: application/json { "ApplicationId": "string", "Backint": { "BackintMode": "string", "EnsureNoBackupInProcess": boolean }, "CredentialsToAddOrUpdate": [ { "CredentialType": "string", "DatabaseName": "string", "SecretId": "string" } ], "CredentialsToRemove": [ { "CredentialType": "string", "DatabaseName": "string", "SecretId": "string" } ], "DatabaseArn": "string" } URI Request Parameters The request does not use any URI parameters. Request Body The request accepts the following data in JSON format. UpdateApplicationSettings API Version 2018-05-10 73 AWS Systems Manager for SAP ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. API Reference Guide Pattern: [\w\d\.-]+ Required: Yes Backint Installation of AWS Backint Agent for SAP HANA. Type: BackintConfig object Required: No CredentialsToAddOrUpdate The credentials to be added or updated. Type: Array of ApplicationCredential objects Array Members: Minimum number of 0 items. Maximum number of 20 items. Required: No CredentialsToRemove The credentials to be removed. Type: Array of ApplicationCredential objects Array Members: Minimum number of 0 items. Maximum number of 20 items. Required: No DatabaseArn The Amazon Resource Name of the SAP HANA database that replaces the current SAP HANA connection with the SAP_ABAP application. Type: String Request Body API Version 2018-05-10 74 AWS Systems Manager for SAP API Reference Guide Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No Response Syntax HTTP/1.1 200 Content-type: application/json { "Message": "string", "OperationIds": [ "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. Message The update message. Type: String OperationIds The IDs of the operations. Type: Array of strings Pattern: [{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]? Errors For information about the errors that are common to all actions, see Common Errors. ConflictException A conflict has occurred. Response Syntax API Version 2018-05-10 75 API Reference Guide AWS Systems Manager for SAP HTTP Status Code: 409 InternalServerException An internal error has occurred. HTTP Status Code: 500 ResourceNotFoundException The resource is not available. HTTP Status Code: 404 UnauthorizedException The request is not authorized. HTTP Status Code: 401 ValidationException The input fails to satisfy the constraints specified by an AWS service. 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 2018-05-10 76 AWS Systems Manager for SAP API Reference Guide Data Types The AWS Systems Manager for SAP 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: • Application • ApplicationCredential • ApplicationSummary • AssociatedHost • BackintConfig • Component • ComponentInfo • ComponentSummary • Database • DatabaseConnection • DatabaseSummary • Filter • Host • IpAddressMember • Operation • OperationEvent • Resilience • Resource API Version 2018-05-10 77 AWS Systems Manager for SAP Application API Reference Guide An SAP application registered with AWS Systems Manager for SAP. Contents AppRegistryArn The Amazon Resource Name (ARN) of the Application Registry. Type: String Pattern: arn:aws:servicecatalog:[a-z0-9:\/-]+ Required: No Arn The Amazon Resource Name (ARN) of the application. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No AssociatedApplicationArns The Amazon Resource Names of the associated AWS Systems Manager for SAP applications. Type: Array of strings Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No Components The components of the application. Type: Array of strings Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Application API Version 2018-05-10 78 AWS Systems Manager for SAP Required: No DiscoveryStatus The latest discovery result for the application. Type: String API Reference Guide Valid Values: SUCCESS | REGISTRATION_FAILED | REFRESH_FAILED | REGISTERING | DELETING Required: No Id The ID of the application. Type: String Length Constraints: Minimum
ssmsap-api-014
ssmsap-api.pdf
14
application. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No AssociatedApplicationArns The Amazon Resource Names of the associated AWS Systems Manager for SAP applications. Type: Array of strings Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No Components The components of the application. Type: Array of strings Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Application API Version 2018-05-10 78 AWS Systems Manager for SAP Required: No DiscoveryStatus The latest discovery result for the application. Type: String API Reference Guide Valid Values: SUCCESS | REGISTRATION_FAILED | REFRESH_FAILED | REGISTERING | DELETING Required: No Id The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No LastUpdated The time at which the application was last updated. Type: Timestamp Required: No Status The status of the application. Type: String Valid Values: ACTIVATED | STARTING | STOPPED | STOPPING | FAILED | REGISTERING | DELETING | UNKNOWN Required: No StatusMessage The status message. Contents API Version 2018-05-10 79 AWS Systems Manager for SAP API Reference Guide Type: String Required: No Type The type of the application. Type: String Valid Values: HANA | SAP_ABAP 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 2018-05-10 80 AWS Systems Manager for SAP API Reference Guide ApplicationCredential The credentials of your SAP application. Contents CredentialType The type of the application credentials. Type: String Valid Values: ADMIN Required: Yes DatabaseName The name of the SAP HANA database. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Required: Yes SecretId The secret ID created in AWS Secrets Manager to store the credentials of the SAP application. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. 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 ApplicationCredential API Version 2018-05-10 81 AWS Systems Manager for SAP • AWS SDK for Ruby V3 API Reference Guide See Also API Version 2018-05-10 82 AWS Systems Manager for SAP API Reference Guide ApplicationSummary The summary of the SAP application registered with AWS Systems Manager for SAP. Contents Arn The Amazon Resource Name (ARN) of the application. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No DiscoveryStatus The status of the latest discovery. Type: String Valid Values: SUCCESS | REGISTRATION_FAILED | REFRESH_FAILED | REGISTERING | DELETING Required: No Id The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No Tags The tags on the application. Type: String to string map ApplicationSummary API Version 2018-05-10 83 AWS Systems Manager for SAP API Reference Guide Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. Maximum length of 256. Required: No Type The type of the application. Type: String Valid Values: HANA | SAP_ABAP 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 2018-05-10 84 API Reference Guide AWS Systems Manager for SAP AssociatedHost Describes the properties of the associated host. Contents Ec2InstanceId The ID of the Amazon EC2 instance. Type: String Required: No Hostname The name of the host. Type: String Required: No IpAddresses The IP addresses of the associated host. Type: Array of IpAddressMember objects Required: No OsVersion The version of the operating system. Type: String 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++ AssociatedHost API Version 2018-05-10 85 AWS Systems Manager for SAP • AWS SDK for Java V2 • AWS SDK for Ruby V3 API Reference Guide See Also API Version 2018-05-10 86 AWS Systems Manager for SAP BackintConfig API Reference Guide Configuration parameters for AWS Backint Agent for SAP HANA. You can backup your SAP HANA database with AWS Backup or Amazon S3. Contents BackintMode AWS service for your database backup. Type: String Valid Values: AWSBackup Required: Yes EnsureNoBackupInProcess Type: Boolean 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 BackintConfig API Version 2018-05-10 87 API Reference Guide AWS Systems Manager for SAP Component The SAP component of your application. Contents ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No Arn The Amazon
ssmsap-api-015
ssmsap-api.pdf
15
AWS service for your database backup. Type: String Valid Values: AWSBackup Required: Yes EnsureNoBackupInProcess Type: Boolean 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 BackintConfig API Version 2018-05-10 87 API Reference Guide AWS Systems Manager for SAP Component The SAP component of your application. Contents ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No Arn The Amazon Resource Name (ARN) of the component. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No AssociatedHost The associated host of the component. Type: AssociatedHost object Required: No ChildComponents The child components of a highly available environment. For example, in a highly available SAP on AWS workload, the child component consists of the primary and secondar instances. Type: Array of strings Length Constraints: Minimum length of 1. Maximum length of 100. Component API Version 2018-05-10 88 AWS Systems Manager for SAP Pattern: [\w\d-]+ Required: No ComponentId The ID of the component. Type: String API Reference Guide Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Required: No ComponentType The type of the component. Type: String Valid Values: HANA | HANA_NODE | ABAP | ASCS | DIALOG | WEBDISP | WD | ERS Required: No DatabaseConnection The connection specifications for the database of the component. Type: DatabaseConnection object Required: No Databases The SAP HANA databases of the component. Type: Array of strings Length Constraints: Minimum length of 1. Maximum length of 300. Pattern: .*[\w\d]+ Required: No Contents API Version 2018-05-10 89 API Reference Guide AWS Systems Manager for SAP HdbVersion The SAP HANA version of the component. Type: String Required: No Hosts This member has been deprecated. The hosts of the component. Type: Array of Host objects Required: No LastUpdated The time at which the component was last updated. Type: Timestamp Required: No ParentComponent The parent component of a highly available environment. For example, in a highly available SAP on AWS workload, the parent component consists of the entire setup, including the child components. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Required: No PrimaryHost This member has been deprecated. The primary host of the component. Type: String Contents API Version 2018-05-10 90 AWS Systems Manager for SAP Required: No Resilience Details of the SAP HANA system replication for the component. API Reference Guide Type: Resilience object Required: No SapFeature The SAP feature of the component. Type: String Required: No SapHostname The hostname of the component. Type: String Required: No SapKernelVersion The kernel version of the component. Type: String Required: No Sid The SAP System Identifier of the application component. Type: String Pattern: [A-Z][A-Z0-9]{2} Required: No Status The status of the component. Contents API Version 2018-05-10 91 AWS Systems Manager for SAP API Reference Guide • ACTIVATED - this status has been deprecated. • STARTING - the component is in the process of being started. • STOPPED - the component is not running. • STOPPING - the component is in the process of being stopped. • RUNNING - the component is running. • RUNNING_WITH_ERROR - one or more child component(s) of the parent component is not running. Call GetComponent to review the status of each child component. • UNDEFINED - AWS Systems Manager for SAP cannot provide the component status based on the discovered information. Verify your SAP application. Type: String Valid Values: ACTIVATED | STARTING | STOPPED | STOPPING | RUNNING | RUNNING_WITH_ERROR | UNDEFINED Required: No SystemNumber The SAP system number of the application component. Type: String Pattern: [0-9]{2} 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 2018-05-10 92 AWS Systems Manager for SAP ComponentInfo API Reference Guide This is information about the component of your SAP application, such as Web Dispatcher. Contents ComponentType This string is the type of the component. Accepted value is WD. Type: String Valid Values: HANA | HANA_NODE | ABAP | ASCS | DIALOG | WEBDISP | WD | ERS Required: Yes Ec2InstanceId This is the Amazon EC2 instance on which your SAP component is running. Accepted values are alphanumeric. Type: String Pattern: i-[\w\d]{8}$|^i-[\w\d]{17} Required: Yes Sid This string is the SAP System ID of the component. Accepted values are alphanumeric. Type: String Pattern: [A-Z][A-Z0-9]{2} Required: Yes ComponentInfo API Version 2018-05-10 93 AWS Systems Manager for SAP See Also API Reference Guide For more information about using this API in one of the language-specific AWS SDKs, see the following: • AWS SDK for C++ •
ssmsap-api-016
ssmsap-api.pdf
16
HANA | HANA_NODE | ABAP | ASCS | DIALOG | WEBDISP | WD | ERS Required: Yes Ec2InstanceId This is the Amazon EC2 instance on which your SAP component is running. Accepted values are alphanumeric. Type: String Pattern: i-[\w\d]{8}$|^i-[\w\d]{17} Required: Yes Sid This string is the SAP System ID of the component. Accepted values are alphanumeric. Type: String Pattern: [A-Z][A-Z0-9]{2} Required: Yes ComponentInfo API Version 2018-05-10 93 AWS Systems Manager for SAP See Also API Reference Guide 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 2018-05-10 94 AWS Systems Manager for SAP API Reference Guide ComponentSummary The summary of the component. Contents ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No Arn The Amazon Resource Name (ARN) of the component summary. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No ComponentId The ID of the component. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Required: No ComponentType The type of the component. Type: String ComponentSummary API Version 2018-05-10 95 AWS Systems Manager for SAP API Reference Guide Valid Values: HANA | HANA_NODE | ABAP | ASCS | DIALOG | WEBDISP | WD | ERS Required: No Tags The tags of the component. Type: String to string map Key Pattern: (?!aws:)[a-zA-Z+-=._:/]+ Value Length Constraints: Minimum length of 1. 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 See Also API Version 2018-05-10 96 AWS Systems Manager for SAP Database API Reference Guide The SAP HANA database of the application registered with AWS Systems Manager for SAP. Contents ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No Arn The Amazon Resource Name (ARN) of the database. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No ComponentId The ID of the component. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Required: No ConnectedComponentArns The Amazon Resource Names of the connected AWS Systems Manager for SAP components. Type: Array of strings Database API Version 2018-05-10 97 AWS Systems Manager for SAP API Reference Guide Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No Credentials The credentials of the database. Type: Array of ApplicationCredential objects Array Members: Minimum number of 0 items. Maximum number of 20 items. Required: No DatabaseId The ID of the SAP HANA database. Type: String Length Constraints: Minimum length of 1. Maximum length of 300. Pattern: .*[\w\d]+ Required: No DatabaseName The name of the database. Type: String Required: No DatabaseType The type of the database. Type: String Valid Values: SYSTEM | TENANT Required: No LastUpdated The time at which the database was last updated. Contents API Version 2018-05-10 98 API Reference Guide AWS Systems Manager for SAP Type: Timestamp Required: No PrimaryHost The primary host of the database. Type: String Required: No SQLPort The SQL port of the database. Type: Integer Required: No Status The status of the database. Type: String Valid Values: RUNNING | STARTING | STOPPED | WARNING | UNKNOWN | ERROR 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 2018-05-10 99 AWS Systems Manager for SAP API Reference Guide DatabaseConnection The connection specifications for the database. Contents ConnectionIp The IP address for connection. Type: String Required: No DatabaseArn The Amazon Resource Name of the connected SAP HANA database. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No DatabaseConnectionMethod The method of connection. Type: String Valid Values: DIRECT | OVERLAY 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 DatabaseConnection API Version 2018-05-10 100 AWS Systems Manager for SAP API Reference Guide See Also API Version 2018-05-10 101 AWS Systems Manager for SAP DatabaseSummary The summary of the database. Contents ApplicationId The ID of the application. Type: String Length Constraints: Minimum length of 1. Maximum length of 60. Pattern: [\w\d\.-]+ Required: No Arn The Amazon Resource Name (ARN) of the database. Type: String Pattern: arn:(.+:){2,4}.+$|^arn:(.+:){1,3}.+\/.+ Required: No ComponentId The ID of the component. Type: String Length Constraints: Minimum length of 1. Maximum length of 100. Pattern: [\w\d-]+ Required: No DatabaseId The ID of the database. Type: String DatabaseSummary API