Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New serverless pattern - Kinesis event source for Lambda using Python CDK #1668

Merged
merged 2 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions kinesis-lambda-py-cdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Amazon Kinesis Data Stream trigger AWS Lambda function with CDK

This pattern creates a Kinesis Data Stream that is added as an event source to AWS Lambda function.

Learn more about this pattern at Serverless Land Patterns: <live url to be added>

Important: This application uses various AWS services and there are costs associated with these services after the Free Tier usage. Please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

- [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
- [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
- [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
- [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html) (AWS CDK >= 2.1.0) installed


## Deployment Instructions

1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
```
git clone https://github.com/aws-samples/serverless-patterns
```
2. Change directory to the pattern directory:
```
cd serverless-patterns/kinesis-lambda-py-cdk
```
3. Create a virtual environment for Python:
```
python3 -m venv .venv
```
4. Activate the virtual environment :
```
Linux : source .venv/bin/activate
Windows : .venv\Scripts\activate.bat
```
5. Install the Python required dependencies:
```
pip install -r requirements.txt
```
6. Review the CloudFormation template the cdk generates for you stack using the following AWS CDK CLI command:
```
cdk synth
```
7. From the command line, use AWS CDK to deploy the AWS resources for the serverless application as specified in the app.py file:
```
cdk deploy
```
8. Note the outputs from the CDK deployment process. These contain the API Gateway ID which is used for testing.

## How it works

This pattern creates a Kinsesis Data stream and a Lambda function. The data stream is then added as an event source which can trigger the Lambda function.

## Testing

From the command line, run the following command to send a single data record to the Kinesis data stream. Note that you must edit the <stream_arn> with the Kinesis data stream ARN that is deployed which will be provided in the stack deployment outputs.

```
aws kinesis put-record --stream-arn <stream_arn> --partition-key 123 --data testdata
```

## Cleanup

Run the given command to delete the resources that were created. It might take some time for the CloudFormation stack to get deleted.

```
cdk destroy
```

---

Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
28 changes: 28 additions & 0 deletions kinesis-lambda-py-cdk/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
import os

import aws_cdk as cdk

from svlsland.svlsland_stack import SvlslandStack


app = cdk.App()
SvlslandStack(app, "SvlslandStack",
# If you don't specify 'env', this stack will be environment-agnostic.
# Account/Region-dependent features and context lookups will not work,
# but a single synthesized template can be deployed anywhere.

# Uncomment the next line to specialize this stack for the AWS Account
# and Region that are implied by the current CLI configuration.

#env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')),

# Uncomment the next line if you know exactly what Account and Region you
# want to deploy the stack to. */

#env=cdk.Environment(account='123456789012', region='us-east-1'),

# For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html
)

app.synth()
58 changes: 58 additions & 0 deletions kinesis-lambda-py-cdk/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"python/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true
}
}
54 changes: 54 additions & 0 deletions kinesis-lambda-py-cdk/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"title": "Kinesis to Lambda with error handling",
"description": "Create a Python Lambda function with Event Source as Kinesis Data source",
"language": "Python",
"level": "200",
"framework": "CDK",
"introBox": {
"headline": "How it works",
"text": [
"This pattern creates an Amazon Kinesis Data Stream that integrates with AWS Lambda using AWS CDK in Python.
"In this example, the Kinesis Data Stream is used as an event source for the Lambda function which can be then be coded to process the data from the stream as per requirement."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/kinesis-lambda-py-cdk",
"templateURL": "serverless-patterns/kinesis-lambda-py-cdk",
"projectFolder": "svlsland",
"templateFile": "kinesis-lambda-py-cdk/svlsland/svlsland_stack.py"
}
},
"resources": {
"bullets": [
{
"text": "AWS CDK Construct for Kinesis and Lambda",
"link": "https://docs.aws.amazon.com/solutions/latest/constructs/aws-kinesisstreams-lambda.html"
}
]
},
"deploy": {
"text": [
"cdk deploy"
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"Delete the stack: <code>cdk destroy</code>."
]
},
"authors": [
{
"name": "Sushir V R",
"image": "https://avatars.githubusercontent.com/u/42473846?v=4",
"bio": "Cloud Engineer @ AWS",
"linkedin": "www.linkedin.com/in/sushirvr",
"twitter": ""
}
]
}
3 changes: 3 additions & 0 deletions kinesis-lambda-py-cdk/lambda_function.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

def lambda_handler(event,context):
print("Hello!")
1 change: 1 addition & 0 deletions kinesis-lambda-py-cdk/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==6.2.5
2 changes: 2 additions & 0 deletions kinesis-lambda-py-cdk/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
aws-cdk-lib==2.93.0
constructs>=10.0.0,<11.0.0
13 changes: 13 additions & 0 deletions kinesis-lambda-py-cdk/source.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@echo off

rem The sole purpose of this script is to make the command
rem
rem source .venv/bin/activate
rem
rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows.
rem On Windows, this command just runs this batch file (the argument is ignored).
rem
rem Now we don't need to document a Windows command for activating a virtualenv.

echo Executing .venv\Scripts\activate.bat for you
.venv\Scripts\activate.bat
Empty file.
37 changes: 37 additions & 0 deletions kinesis-lambda-py-cdk/svlsland/svlsland_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from aws_cdk import (
aws_lambda as lambda_,
aws_kinesis as kinesis,
aws_lambda_event_sources as event_sources,
Stack,
Duration
)
from constructs import Construct

class SvlslandStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

# The code that defines your stack goes here
with open("lambda_function.py", encoding="utf8") as fp:
handler_code = fp.read()

kinesis_stream = kinesis.Stream(self, "SampleStream")

lambdaFn = lambda_.Function(
self, 'sampleFn',
handler='index.lambda_handler',
code=lambda_.InlineCode(handler_code),
runtime=lambda_.Runtime.PYTHON_3_8,
timeout=Duration.seconds(30)
)

kinesis_stream.grant_read(lambdaFn)

kinesis_event_source = event_sources.KinesisEventSource(
stream=kinesis_stream,
starting_position=lambda_.StartingPosition.LATEST,
batch_size=1
)

lambdaFn.add_event_source(kinesis_event_source)
16 changes: 16 additions & 0 deletions kinesis-lambda-py-cdk/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless patterns - Service to Service description

# Comment on each global
Globals:


# Comment each resource section to explain usage
Resources:


# List all common outputs for usage
Outputs:


Empty file.
Empty file.
15 changes: 15 additions & 0 deletions kinesis-lambda-py-cdk/tests/unit/test_svlsland_stack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import aws_cdk as core
import aws_cdk.assertions as assertions

from svlsland.svlsland_stack import SvlslandStack

# example tests. To run these tests, uncomment this file along with the example
# resource in svlsland/svlsland_stack.py
def test_sqs_queue_created():
app = core.App()
stack = SvlslandStack(app, "svlsland")
template = assertions.Template.from_stack(stack)

# template.has_resource_properties("AWS::SQS::Queue", {
# "VisibilityTimeout": 300
# })
Loading