Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS-CDK - DynamoDB Initial Data

Using the AWS CDK for a Serverless project but I've hit a sticking point. My project deploys a DynamoDB table which I need to populate with data prior to my Lambda function executing.

The data that needs to be loaded is generated by making API calls and isn't static data that can be loaded by a .json file or something simple.

Any ideas on how to approach this requirement for a production workload?

like image 834
ServerMonkey Avatar asked Jul 04 '20 01:07

ServerMonkey


1 Answers

You can use AwsCustomResource in order to make a PutItem call to the table.

AwsSdkCall initializeData = AwsSdkCall.builder()
        .service("DynamoDB")
        .action("putItem")
        .physicalResourceId(PhysicalResourceId.of(tableName + "_initialization"))
        .parameters(Map.ofEntries(
                Map.entry("TableName", tableName),
                Map.entry("Item", Map.ofEntries(
                        Map.entry("id", Map.of("S", "0")),
                        Map.entry("data", Map.of("S", data))
                )),
                Map.entry("ConditionExpression", "attribute_not_exists(id)")
        ))
        .build();

AwsCustomResource tableInitializationResource = AwsCustomResource.Builder.create(this, "TableInitializationResource")
        .policy(AwsCustomResourcePolicy.fromStatements(List.of(
                PolicyStatement.Builder.create()
                        .effect(Effect.ALLOW)
                        .actions(List.of("dynamodb:PutItem"))
                        .resources(List.of(table.getTableArn()))
                        .build()
        )))
        .onCreate(initializeData)
        .onUpdate(initializeData)
        .build();
tableInitializationResource.getNode().addDependency(table);

The PutItem operation will be triggered if the stack is created or if table is updated (tableName is supposed to be different in that case). If it doesn't work for some reason, you can set physicalResourceId to random value, i.e. UUID, to trigger the operation for each stack update (the operation is idempotent due to ConditionExpression)

like image 124
Roman Kishchenko Avatar answered Oct 07 '22 01:10

Roman Kishchenko