I am trying to have a lambda publish a SQS message to the same SQS Url the lambda is consuming on. However, I can't find out how to get the queue url during runtime and don't want to use AWS secrets. How can I get the SQS Url during runtime?
Your best bet here would probably be to use an environment variable in your lamda function with "QUEUE_NAME" or "QUEUE_URL" or something similar. Don't forget to make sure your lambda function has the correct policy to allow it to publish new messages on the SQS queue!
If you can provide more details with the language you are using and if you are using some IaC like CDK then I could provide a code example.
PS. I don't know the exact application of this but be wary of infinite execution loops!
Edit: Added code example below:
using Amazon.CDK;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.SQS;
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AWS.Events.Targets;
using Amazon.CDK.AWS.Lambda.EventSources;
...
// Function which gets called from cloudwatch event...
var scheduledFunction = new Function(this, "scheduled-function", new FunctionProps
{
// add props here
});
// SQS Queue which is consumed and added to...
var sqsQueue = new Queue(this, "sqs-queue", new QueueProps
{
// add props here
});
// Function which handles SQS messages from the queue...
var messageHandlerFunction = new Function(this, "code-function", new FunctionProps
{
// add props here
Environment = new Dictionary<string, string>
{
{"SQS_URL",sqsQueue.QueueUrl}
}
});
// Allow scheduler function to send SQS messages...
sqsQueue.GrantSendMessages(scheduledFunction);
// Allow scheduler function to consume and send SQS messages...
sqsQueue.GrantConsumeMessages(messageHandlerFunction);
sqsQueue.GrantSendMessages(messageHandlerFunction);
// Set event message handler function to consume messages...
messageHandlerFunction.AddEventSource(new SqsEventSource(sqsQueue));
// Scheduled event to run every 30 minutes...
var scheduledEvent = new Rule(this, "every-half-hour-rule", new RuleProps
{
Description = "Every 30 minutes.",
Enabled = true,
RuleName = "every-thirty-minutes",
Schedule = null,
Targets = new IRuleTarget[]
{
new LambdaFunction(scheduledFunction)
}
});
...