In this lab, we will learn how a lambda function can be invoked via Polling.
- Overview
- Source: DynamoDB Stream
- Create a DynamoDB Table
- Enable the Stream
- 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 “AWSLambdaDynamoDBExecutionRole” and select it
- Name, review
- Name: “LambdaDynamoDBExecutionRole“
- 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": [
"dynamodb:DescribeStream",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
"dynamodb:ListStreams",
"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 “LambdaDynamoDBExecutionRole“
- 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. DynamoDB – Create a table
- Click “Create table”
- Table name: “Orders“
- Partition key: “OrderId“, “Number“
- Sort Key: “Item“, “String“
- Click “Create table“
5. DynamoDB – Enable the Stream
- Click “Tables” on the left pane
- Select the “Orders” table
- Click the “Exports and streams” tab
- DynamoDB stream details
- Click “Enable“
- Check “New and old images“
- Click “Enable stream“
6. Lambda – Configure the DynamoDB Stream as a Lambda trigger
- On the “logMessage” function page, “Function overview” -> “Add trigger“
- Select “DynamoDB” as a source
- Table: “Orders“
- Batch size: 5
- Click “Add“
7. DynamoDB – Test
- On the “Orders” table page, click “Explore table items“
- Click “Create Item”
- OrderId: 100
- Item: Computer
- Price: 1000 (Add new attribute – Number)
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