I have a use case to send a message from an AWS Lambda function, let's say from Account A,
To an AWS SQS in Account B,
In Account A, I have written a Lambda function that uses aws-sdk
library in NodeJs to use the sendMessage method to send a message to the Queue URL in Account B
,
The Lambda function has a role with permission to sendMessage to the SQS service
In Account B, I have created an SQS, which has permission to allow the ARN of the IAM role of the Lambda function in Account A as a Principal
, and the SQS as the Resource
Lambda code -
import { SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
const sqsClient = new SQSClient({ region: "ap-southeast-1" });
export const handler = async (event) => {
let response;
const params = {
MessageGroupId: "test",
MessageBody: "some message here",
QueueUrl: "https://sqs.ap-southeast-1.amazonaws.com/AWS_ACCOUNT_B_NUMBER/TEST.fifo"
};
try {
const data = await sqsClient.send(new SendMessageCommand(params));
if (data) {
console.log("Success, message sent. MessageID:", data.MessageId);
const bodyMessage = 'Message Sent, MessageId: ' +data.MessageId;
response = {
statusCode: 200,
body: JSON.stringify(bodyMessage),
};
}else{
response = {
statusCode: 500,
body: JSON.stringify('Some error occured !!')
};
}
return response;
}
catch (err) {
console.log("Error", err);
}
};
SQS Permission Statement -
{
"Sid": "Stmt1676274704834",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::AWS_ACCOUNT_A_NUMBER:role/test-ap-southeast-1-lambdaRole"
},
"Action": "sqs:SendMessage",
"Resource": "*"
}
I am getting the following error -
The specified queue does not exist or you do not have access to it.
There are 2 ways to do this :-
Use Access Policy for Sqs queues to allow different account access queue. Typically in the policy you will add lambda role arn to allow access.
Setup role in sqs account which will be assumed by lambda. Give Lambda the assume role permissions to assume role created in sqs account and then lambda will assume and get temporary credentials to perform the operation .