Search code examples
amazon-web-servicesamazon-sqs

How to send messages to an SQS queue in a different AWS account?


My company has multiple accounts and I am writing a lambda in account 1 that needs to write to an SQS queue in account 2. My code looks like this:

logger.info(f"{len(entries)} batch entries built")
    sqs_queue = environ["SQS_QUEUE"]
    try:
        logger.info("Getting SQS queue url...")
        queue_url = sqs.get_queue_url(QueueName=sqs_queue)['QueueUrl']
        # iterate over entries in batches of 10
        for batch in [entries[index:index + sqs_batch_limit] for index in range(0, len(entries), sqs_batch_limit)]:
            logger.info(f"Sending batch of {len(batch)} records to sqs...")
            sqs.send_message_batch(
                QueueUrl=queue_url,
                Entries=batch
            )

The problem is that in both accounts, there's an SQS queue named sqs-queue-data so the code I wrote above will be default write to the SQS queue in the same account as this lambda. So what can be done?


Solution

  • Use the QueueOwnerAWSAccountId argument when you're calling get_queue_url e.g.

    queue_url = sqs.get_queue_url(
      QueueName=sqs_queue,
      QueueOwnerAWSAccountId=1234567890
    )['QueueUrl']
    

    Docs: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.html#SQS.Client.get_queue_url