import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as eventSources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
const cluster = new documentdb.CfnDBCluster(this, 'Cluster', {
dbClusterIdentifier: 'myCluster',
engine: 'docdb',
masterUsername: 'myUsername',
masterUserPassword: 'myPassword',
backtrackWindow: 0,
deletionProtection: false,
backupRetentionPeriod: 1,
preferredBackupWindow: '07:00-09:00',
dbSubnetGroupName: subnetGroup.dbSubnetGroupName,
vpcSecurityGroupIds: [securityGroup.securityGroupId]
});
const table = new dynamodb.Table(this, 'Table', {
partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING },
sortKey: { name: 'sk', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST
});
const fn = new lambda.Function(this, 'Function', {
runtime: lambda.Runtime.NODEJS_12_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
environment: {
TABLE_NAME: table.tableName
},
timeout: cdk.Duration.seconds(30)
});
const mapping = new eventSources.DynamoEventSource(table, {
startingPosition: lambda.StartingPosition.TRIM_HORIZON,
batchSize: 100
});
fn.addEventSourceMapping('Mapping', mapping);
const vpc = new ec2.Vpc(this, 'Vpc', {
cidr: '10.0.0.0/16',
maxAzs: 2,
subnetConfiguration: [
{ name: 'public', subnetType: ec2.SubnetType.PUBLIC }
]
});
const subnetGroup = new documentdb.CfnDBSubnetGroup(this, 'SubnetGroup', {
dbSubnetGroupName: 'mySubnetGroup',
subnetIds: vpc.publicSubnets.map(subnet => subnet.subnetId)
});
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
vpc,
allowAllOutbound: true
});
securityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(27017));
cluster.addOverride('Properties.VpcSecurityGroupIds', [securityGroup.securityGroupId]);
cdk deploy
const myLambda = new lambda.Function(stack, 'MyLambda', { ... });
myLambda.addEventSourceMapping('Mapping', {
batchSize: 10,
eventSourceArn: mapping.eventSourceArn,
function: myLambda
});
Asked: 2022-05-07 11:00:00 +0000
Seen: 11 times
Last updated: Aug 08 '21