In a CDK project, I wanted the ability to create the DynamoDB tables defined in my stack in a locally running DynamoDB container so that I could run integration tests with a real DB. Unfortunately there doesn't seem to be an obvious way to do this.
If you're using the serverless framework, there is a plugin called serverless-dynamodb-local which achieves this for you with a single command. It hooks in to the CloudFormation building process, extracts the tables, and makes requests to the DynamoDB API to create them.
There doesn't seem to be a sanctioned way of hooking in to the CDK synthesizing process, however, running cdk synth does export the CloudFormation templates in cdk.out, which are easy enough to parse.
So the plan is simple:
- Synthesize the stack(s) to create the CloudFormation output (as JSON), via
cdk synth). - Read the templates and extract the tables from each stack, filtering on their resource type.
- Convert each table in to a table creation request (by removing a few keys).
- Create the tables via the DynamoDB API.
Python code for creating the tables is included below.
This can be executed as part of a GitHub actions job like this:
- name: CDK Synth
run: cdk synth
- name: Start DynamoDB Local
uses: rrainn/[email protected]
with:
port: ${{ env.DYNAMODB_PORT }}
cors: '*'
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Pip install
run: pip install boto3
- name: Create DynamoDB tables
run: python ./.github/workflows/scripts/create_stack_dynamodb_tables.py