Configure DynamoDB in CDK

Link to chapter β€” https://serverless-stack.com/chapters/configure-dynamodb-in-cdk.html

How can I create multiple tables at once?

1 Like

I found a way to do it by duplicating everything inside the Stack!

1 Like

Yeah exactly. Just create multiple instances of the DynamoDB construct.

Here’s an example if someone else is looking for it:

import { CfnOutput } from "@aws-cdk/core";
import * as dynamodb from "@aws-cdk/aws-dynamodb";
import * as sst from "@serverless-stack/resources";

export default class DynamoDBStack extends sst.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);

    const app = this.node.root;

    const activitiesTable = new dynamodb.Table(this, "ActivitiesTable", {
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, // Use on-demand billing mode
      sortKey: { name: "activityId", type: dynamodb.AttributeType.STRING },
      partitionKey: { name: "userId", type: dynamodb.AttributeType.STRING },
    });

    const profilesTable = new dynamodb.Table(this, "ProfilesTable", {
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, // Use on-demand billing mode
      sortKey: { name: "profileId", type: dynamodb.AttributeType.STRING },
      partitionKey: { name: "userId", type: dynamodb.AttributeType.STRING },
    });

    // Output values for Activities Table
    new CfnOutput(this, "ActivitiesTableName", {
      value: activitiesTable.tableName,
      exportName: app.logicalPrefixedName("ActivitiesTableName"),
    });
    new CfnOutput(this, "ActivitiesTableArn", {
      value: activitiesTable.tableArn,
      exportName: app.logicalPrefixedName("ActivitiesTableArn"),
    });

    // Output values for Profiles Table
    new CfnOutput(this, "ProfilesTableName", {
      value: profilesTable.tableName,
      exportName: app.logicalPrefixedName("ProfilesTableName"),
    });
    new CfnOutput(this, "ProfilesTableArn", {
      value: profilesTable.tableArn,
      exportName: app.logicalPrefixedName("ProfilesTableArn"),
    });
  }
}

Shoot me your email and we can go from there.