AWS Lambda is a event-driven compute service. Lambda functions are run only when triggered by an event and you pay only for the compute time used. Listed below are the steps on how to use SQS queue as an event source for a AWS Lambda function.
1. Create a SQS queue
- Create a new SQS queue named "testLambdaQueue"
- Set queue type to Standard; which doesn't guarantee order of message delivery
2. Create an IAM Role
- Go to AWS IAM dashboard and create a new role "SQSLambdaRole", and attach managed policy AWSLambdaSQSQueueExecuionRole.
- From Lambda console create a new function "testSQSFunction" with Python 3.7 as runtime.
- Use "SQSLambdaRole" role
- Add SQS Queue "testLambdaQueue" as a trigger.
- Add the following code in Lambda function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import json def lambda_handler(event, context): body = { "message": "Hello SQS", "event": event } print(json.dumps(body)) response = { "statusCode": 200, "body": json.dumps(body) } return response |
- Create a test event "testSQSEvent" using SQS template
- On click Test execution result shows success.
3. Test pipeline by putting data in SQS queue
- Go to SQS console and select testLambdaQueue
- Go to Queue Actions > Send a Message
- Enter a sample message and click Send Message
- CloudWatch log entry shows that the message was received and processed by lambda function.
- SQS Queue (testLambdaQueue) monitoring graphs also confirms that 1 message was received, process and then deleted.
No comments:
Post a Comment