Architecture#
CDK stack#
Use the same role for two lambdas
const role = new aws_iam.Role(this, 'RoleForLambdaIcaServerlessDemo', {assumedBy: new aws_iam.ServicePrincipal('lambda.amazonaws.com'),roleName: 'RoleForLambdaIcaServerlessDemo'})// inline policiesrole.attachInlinePolicy(new aws_iam.Policy(this, 'PolicyForLambdaIcaServerlessDemo', {policyName: 'PolicyForLambdaIcaServerlessDemo',statements: [// acces s3new aws_iam.PolicyStatement({effect: aws_iam.Effect.ALLOW,actions: ['s3:*', 's3-object-lambda:*'],resources: ['arn:aws:s3:::haimtran-workspace/*']}),// write to dynamo dbnew aws_iam.PolicyStatement({effect: aws_iam.Effect.ALLOW,actions: ['dynamodb:*'],resources: ['*']}),// send snsnew aws_iam.PolicyStatement({effect: aws_iam.Effect.ALLOW,actions: ['sns:*'],resources: ['*']})]}))
lambda to write to dynamodb
const func = new aws_lambda.Function(this, 'CdkLambdaIcaDemo', {functionName: 'CdkLambdaIcaDemo',runtime: aws_lambda.Runtime.PYTHON_3_8,memorySize: 512,timeout: Duration.seconds(15),code: aws_lambda.Code.fromAsset(path.join(__dirname, './../lambda')),handler: 'lambda_write_ddb.handler',role: role})
lambda to send sns
const lambda_sns = new aws_lambda.Function(this, 'IcaLambdaSnsDemo', {functionName: 'LambdaSnsIcaDemo',code: aws_lambda.Code.fromAsset(path.join(__dirname, './../lambda')),handler: 'lambda_send_sns.handler',runtime: aws_lambda.Runtime.PYTHON_3_8,role: role})
an existed S3 trigger lambda
// an existed s3 trigger a lambdaconst bucket = aws_s3.Bucket.fromBucketName(this,'haimtran-bucket-id','haimtran-workspace')bucket.addEventNotification(aws_s3.EventType.OBJECT_CREATED,new aws_s3_notifications.LambdaDestination(func),{prefix: 'notify-lambda/'})
dynamodb table enabled stream
const table = new aws_dynamodb.Table(this, 'S3LambdaEventTable', {tableName: 'S3LambdaEventTable',partitionKey: {name: 'id',type: aws_dynamodb.AttributeType.STRING},billingMode: aws_dynamodb.BillingMode.PAY_PER_REQUEST,stream: aws_dynamodb.StreamViewType.NEW_IMAGE})
dynamodb stream trigger lambda
lambda_sns.addEventSource(new aws_lambda_event_sources.DynamoEventSource(table, {startingPosition: aws_lambda.StartingPosition.LATEST,batchSize: 1,retryAttempts: 2}))
sns topic and subscription
// create a sns topicconst topic = new aws_sns.Topic(this, 'SnsTopicIcaDemo', {topicName: 'SnsTopicIcaDemo'})// subscripttopic.addSubscription(new aws_sns_subscriptions.EmailSubscription('hai@entest.io'))