
Overview
Take this example as a starting point. This is not a production-ready code, probably some tweaks for permissions will be necessary to meet your requirements.
AWS resources we need
- Lambda Function
- SQS queue
- Lambda Role
- SQS Policy
Lambda Function
let response;
exports.lambdaHandler = async (event, context) => {
try {
response = {
'statusCode': 200,
'body': JSON.stringify({
message: 'hello world',
})
}
} catch (err) {
console.log(err);
return err;
}
return response
};
SAM template
For the sake of simplicity, we are going to allow all operations over de queue but make sure you set the minimum permissions you need
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
Trigger a Lambda function when writing a message in SQS
Parameters:
Environment:
Type: String
Description: example, staging
Resources:
MyQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${Environment}-my-queue"
MyFunction:
Type: AWS::Serverless::Function
DependsOn:
- MyQueue
Tags:
Name: !Sub "${Environment}-my-function"
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
MySQSEvent:
Type: SQS
Properties:
Queue: !GetAtt MyQueue.Arn
BatchSize: 10
Role:
Fn::GetAtt:
- MyFunctionRole
- Arn
MyQueuePolicy:
Type: AWS::SQS::QueuePolicy
DependsOn:
- MyQueue
Properties:
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- "sqs.amazonaws.com"
Action:
- "sqs:*"
Resource:
Fn::GetAtt:
- MyQueue
- Arn
Queues:
- Ref: MyQueue
MyFunctionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Action: "sts:AssumeRole"
Principal:
Service:
- "lambda.amazonaws.com"
Version: "2012-10-17"
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: AccessAll
PolicyDocument:
Statement:
- Effect: Allow
Action: "sqs:*"
Resource:
- Fn::GetAtt:
- "MyQueue"
- "Arn"
Version: "2012-10-17"
Deploy
Build our lambda and template. This will check also the syntax of your template
sam build
Only for the first time run and follow the steps
sam deploy --guided
The second time and so on you can execute
sam deploy --no-confirm-changeset
Clean up your test AWS resources. Delete unused lambdas, buckets, etc to keep your account organized and the most important: no extra costs