Follow these steps to deploy and invoke the Lambda. You may follow Chapter 1, Getting Started with Serverless Computing on AWS and use CloudFormation for Lambda provisioning:
- Run mvn clean package from inside the Lambda project root folder to create the Uber JAR
- Upload the Uber JAR to S3:
aws s3 cp
target/lambda-invoke-sqs-event-0.0.1-SNAPSHOT.jar
s3://serverless-cookbook/lambda-invoke-sqs-event-0.0.1-SNAPSHOT.jar
--profile admin
- Create a role for the Lambda with an appropriate trust relationship definition:
aws iam create-role
--role-name lambda-invoke-sqs-event-role
--assume-role-policy-document file://iam-role-trust-relationship.txt
--profile admin
The trust document, iam-role-trust-relationship.txt, is defined as follows:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
- Create a policy for basic logging permissions and attach it to the role
- Create a policy for required SQS permissions and attach it to the role
The policy document with required SQS permissions is shown here:
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"sqs:GetQueueAttributes",
"sqs:ReceiveMessage",
"sqs:DeleteMessage",
"sqs:SendMessage",
"sqs:SendMessageBatch"
],
"Resource":[
"arn:aws:sqs:*:*:*"
]
}
]
}
A Lambda configured to be invoked by an SQS even source should have the following permissions:
- sqs:GetQueueAttributes
- sqs:ReceiveMessage
- sqs:DeleteMessage
I have also added the send message permissions, as we will be forwarding the messages to another queue
- Create the Lambda function, as shown here:
aws lambda create-function
--function-name lambda-invoke-sqs-event
--runtime java8
--role arn:aws:iam::855923912133:role/lambda-invoke-sqs-event-role
--handler tech.heartin.books.serverlesscookbook.LambdaSqsEventHandler::handleRequest
--code S3Bucket=serverless-cookbook,S3Key=lambda-invoke-sqs-event-0.0.1-SNAPSHOT.jar
--environment Variables={SPC_OUTPUT_QUEUE_URL='https://queue.amazonaws.com/855923912133/my-output-queue'}
--timeout 15
--memory-size 512
--region us-east-1
--profile admin
- Configure an SQS event source for the Lambda:
aws lambda create-event-source-mapping
--event-source-arn arn:aws:sqs:us-east-1:855923912133:my-input-queue
--function-name lambda-invoke-sqs-event
--batch-size 4
--profile admin
The batch-size parameter specifies the maximum number of messages to be retrieved from the queue together