sorenandersen.com

Deploy DynamoDB seed data with a Node script

August 11, 2020

Here’s a handy way of deploying seed data into DynamoDB while still using dynamic naming of resources such as DynamoDB tables.

By using the serverless-export-env plugin to export environment variables defined in serverless.yml - and then the commonly used dotenv package to load them into process.env - it’s easy to prepopulate e.g. test data with a simple Node script.

I’ve put together a runnable example here which can roughly be distilled into the following code listings.

serverless.yml

service: ...
provider:
  name: aws
  runtime: nodejs12.x
  environment:
    TABLE_NAME: !Ref SeedDemoTempTable

resources:
  Resources:
    SeedDemoTempTable:
      Type: AWS::DynamoDB::Table
      ...

deploy-seed-data.js

require('dotenv').config()

const seedData = [
  {
    PK: '1',
    Name: 'Foo',
  },
  ...
]

const putReqs = seedData.map((x) => ({
  PutRequest: {
    Item: x,
  },
}))

const req = {
  RequestItems: {
    [process.env.TABLE_NAME]: putReqs,
  },
}

dynamodb
  .batchWrite(req)
  .promise()
  .then(() => console.log('Done!'))
  .catch((err) => console.error(err))

Now simply 1) export variables and 2) deploy seed data with the Node script.

# Export environment variables to .env
$ sls export-env

# Deploy seed data
$ node deploy-seed-data.js

References

I learned this technique attending Yan Cui’s “Production-Ready Serverless” workshop. I really recommend this workshop for anyone wanting to up their AWS serverlesss skills.


Søren Andersen

Digital garden of Søren Andersen.
Posts on tech that I use and learn.