Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate dynamodb table with default values in CDK

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.

like image 823
Djlynux Avatar asked Oct 30 '25 14:10

Djlynux


1 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

like image 150
Manu Avatar answered Nov 02 '25 14:11

Manu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!