Populate dynamodb table with default values in CDK

Viewed 1351

I'm working on a CDK project in which I need to populate dynamodb table that I'm creating with CDK with some default items. How can I achieve this using AWS-CDK? If not is there any option to run a secondary script once the dynamodb table is created.

2 Answers

There you go, an example on how to use Custom Resource to populate a DynamoDB table:

import * as cr from '@aws-cdk/custom-resources';

const dynamoDb = new Table(this, 'UserDatabase', {
  partitionKey: { name: 'Name', type: AttributeType.STRING, },
  pointInTimeRecovery: true,
  billingMode: BillingMode.PAY_PER_REQUEST,
  timeToLiveAttribute: 'ttl'
});

new cr.AwsCustomResource(this, 'initTable', {
      onCreate: {
        service: 'DynamoDB',
        action: 'putItem',
        parameters: {
            TableName: dynamoDb.tableName,
            Item: { Name: { S: "User1" } }
        },
        physicalResourceId: cr.PhysicalResourceId.of(dynamoDb.tableName + '_initialization')
      },
      policy: cr.AwsCustomResourcePolicy.fromSdkCalls({ resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE }),
    });

The following article helped me to get it working: https://dev.to/elthrasher/exploring-aws-cdk-loading-dynamodb-with-custom-resources-jlf

You could use a Custom Resource for that. It allows you to run any AWS SDK commands you want on trigger.

Related