Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

DynamoDB seed data on create with custom resource using CDK (Typescript)

Created with SnapDynamoDB

Create a DynamoDB table and insert data upon creation using custom resource.

This project demonstrates how to create a DynamoDB table and insert data upon creation using custom resource.

import {
  aws_dynamodb as ddb,
  CfnOutput,
  custom_resources,
  RemovalPolicy,
  Stack,
  StackProps
} from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class DynamodbSeedDataOnCreateCdkStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const table = new ddb.Table(this, 'MyDynamoDBTable', {
      partitionKey: { name: 'pk', type: ddb.AttributeType.STRING },
      sortKey: { name: 'type', type: ddb.AttributeType.STRING },
      billingMode: ddb.BillingMode.PAY_PER_REQUEST,
      removalPolicy: RemovalPolicy.DESTROY,
    });

    new custom_resources.AwsCustomResource(this, 'ddbInitData', {
      onCreate: {
        service: 'DynamoDB',
        action: 'putItem',
        parameters: {
          TableName: table.tableName,
          Item: {
            pk: { S: 'DiscountCode_ABC' },
            type: { S: 'DiscountCode' },
            code: { S: 'ABCD' },
          }
        },
        physicalResourceId: custom_resources.PhysicalResourceId.of(Date.now().toString()),
      },
      policy: custom_resources.AwsCustomResourcePolicy.fromSdkCalls({
        resources: [table.tableArn],
      }),
    });

    // Outputs
    new CfnOutput(this, 'DynamoDBTable', {
      value: table.tableName,
      description: 'DyanmoDB Table',
      exportName: 'DyanmoDBTableName',
    });
  }
}

< Back to all patterns


GitHub icon Visit the GitHub repo for this pattern.

Download

git clone https://github.com/aws-samples/serverless-patterns/ cd serverless-patterns/dynamodb-seed-data-on-create-cdk

Deploy

cdk deploy --all


Testing

See the GitHub repo for detailed testing instructions.

Cleanup

Delete the stack: cdk destory --all.

Pubudu Jayawardana

Presented by Pubudu Jayawardana

AWS Community Builder in Serverless category. Serverless advocate and enthusiast.

Follow on LinkedIn