Search code examples
amazon-dynamodbmicroservicesserverless-frameworkseeding

Best way to add default rows in DynamoDB table when the stack is deployed


There is some application default I would like to be added to the DynamoDB table of each of the microservices when the stack is deployed for the first time.

I am using a Serverless framework. What is the best way to do it?

I came across this https://www.npmjs.com/package/serverless-dynamodb-seed but because of the possibility of overwriting data in the table, I'd like to use a safer option.


Solution

  • To seed DynamoDB data post-create with the Serverless Framework you need two things:

    1. A script invoking the AWS DynamoDB SDK Client's PutItem or BatchWriteItem commands with your seed data*. This is what the serverless-dynamodb-seed plugin does. You can write a node.js script yourself, no need for a fancy plugin.
    2. A way to trigger the script after a stack create

    Which triggering option is "best" depends on your use case. There are several options, here are two:

    1. Run your seed scripts manually from the terminal after you deploy the first time
    2. Use the serverless-scriptable-plugin, which "supports running node.js scripts in any build stage", to run the script automatically after the stack is created (but not after updates)
    # https://github.com/weixu365/serverless-scriptable-plugin
    plugins:
      - serverless-scriptable-plugin
    
    custom:
      scriptable:
        hooks:
          after:aws:deploy:deploy:createStack:  path/to/seed-script.js
    

    * PutItem writes a single record, optionally with a condition to prevent overwriting. BatchWriteItem puts several items at once, but without a conditional check. The serverless-dynamodb-seed plugin warns about possible overwrites because it calls BatchWriteItem under the hood.