In this lab, we will learn how a lambda function can be invoked via Polling.
- Overview
- Source: SQS
- Create a queue and a dead-letter queue (DLQ)
- Target: Lambda – Function
- logs the received message
- does not return any value
- configures the trigger
- Python
1. IAM – Setup the Lambda execution role
- Click “Roles” on the left pane
- Click “Create role“
- Select trusted entity
- Trusted entity type: “AWS service“
- Use: “Lambda“
- Add Permissions
- Search “AWSLambdaSQSQueueExecutionRole” and select it
- Name, review
- Name: “LambdaSQSExecutionRole“
- Click “Create role“
Lambda service needs to poll SQS. Therefore you need to provide the execution permission to the Lambda function.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sqs:ReceiveMessage",
"sqs:DeleteMessage",
"sqs:GetQueueAttributes",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
2. Lambda – Create a Function
- Function Name: “logMessage“
- Runtime: Python 3.9
- Permissions
- Check “Use an existing role“
- Select “LambdaSQSExecutionRole“
- Click “Create function“
3. Lambda – Function Code (Python)
- Type the following code
- Click “Deploy“
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info(json.dumps(event))
4. SQS – Create a dead-letter queue
- Click “Create queue”
- Select “Standard”
- Name: “my-dlq“
- Click “Create queue“
5. SQS – Create a queue
- Click “Create queue”
- Select “Standard”
- Name: “greeting-queue“
- Under the “Dead-letter queue”
- Check “Enabled“
- Select the dead-letter queue “my-dlq“
- Maximum receives: 2
- Click “Create queue“
6. SQS – Test the Dead-letter queue
- Click the “Queues” menu on the left pane
- Select the newly created queue “greeting-queue“
- Click “Send and receive messages“
- Enter any message text and send it –> send 2 more messages
- In the “Receive messages” section, you can see the “Messages available” count -> 3
- Click “Poll for messages” three times
- The messages will be removed.
- Move to the dead-letter queue and check the messages.
7. Lambda – Configure the SQS as a Lambda trigger
- On the “logMessage” function page, “Function overview” -> “Add trigger“
- Select “SQS” as a source
- Select the “greeting-queue“
- Click “Add“
8. SQS- Test
- On the “greeting-queue” page, click “Send and receive messages“
- Enter any message text and send it
9. CouldWatch – Check the Lambda logs
- On the Lambda function page, click the “Monitor” tab
- Check some metrics on the page
- Click the “View logs in the CloudWatch” button
- On the CloudWatch page, click the “Log stream“
- Check the logs