AWS CDK for DynamoDB and Python: A Developer’s Guide

AWS CDK for DynamoDB blog image

Manual AWS Console setups don’t scale. If you’re deploying infrastructure repeatedly, across environments, or as part of a CI/CD pipeline, you want Infrastructure as Code (IaC). That’s where AWS CDK (Cloud Development Kit) comes in—and using Python makes it accessible to a broad base of developers. In particular, we can use AWS CDK for DynamoDB to create and operate your DynamoDB stack programmatically.

This blog walks through creating a DynamoDB table using AWS CDK in Python, explains why this approach is better than manual configuration or using CloudFormation directly, and provides production-minded guidance.

Why Use AWS CDK for DynamoDB?

Before diving into code, let’s get clear on why you’d want to use AWS CDK:

FeatureWhy It Matters
Code-first IaCDefine infra using Python (or TypeScript, Java, etc.), not JSON/YAML.
Reusable constructsBuild reusable components (e.g., a “UserTable” module) and share across projects.
Version controlYour infrastructure is in Git. Rollbacks, diffs, code reviews all work.
Automation-friendlyIntegrates with CI/CD tools and enables true DevOps pipelines.
Validation and testingUse Python logic to validate configuration before deploys.

Prerequisites

To follow along, you’ll need:

  • Python 3.10 (or later! Avoid old versions as they are deprecated and often have security issues and bugs)
  • Node.js and npm
  • AWS CLI configured
  • AWS CDK installed (npm install -g aws-cdk)
  • A virtualenv and basic Python package management experience

Step-by-Step: Creating a DynamoDB Table with CDK in Python

1. Set Up Your CDK Project

Here you are creating an empty directory and changing into it. Then you are going to initialize the CDK stack and tell it you’ll be using Python:

mkdir cdk-dynamodb && cd cdk-dynamodb
cdk init app --language python

Activate your virtual environment and install pip. Pip is a package manager for Python and allows you to install extra modules:

source .venv/bin/activate
pip install -r requirements.txt

Install the AWS CDK DynamoDB module:

pip install aws-cdk.aws-dynamodb

2. Define the DynamoDB Table in Code

In an AWS CDK project, each resource you want to define (like a DynamoDB table, Lambda function, or S3 bucket) is typically organized into a stack.

This file defines the logic for your DynamoDB stack — a reusable unit of infrastructure. It’s where you declare the resources you want to deploy, in this case, a DynamoDB table.

By creating a custom stack in cdk_dynamodb_stack.py, you’re:

  • Allowing CDK to manage the lifecycle of the table automatically
  • Encapsulating the table’s configuration
  • Making the code clean and modular
from aws_cdk import (
    Stack,
    aws_dynamodb as dynamodb
)
from constructs import Construct

class CdkDynamodbStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Create the DynamoDB table
        table = dynamodb.Table(
            self, "UsersTable",
            partition_key=dynamodb.Attribute(
                name="user_id",
                type=dynamodb.AttributeType.STRING
            ),
            billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,  # On-demand pricing
            table_name="Users"
        )

Let’s explain each section bit by bit.

Firstly the import statement. The import lets us use other modules that aren’t included by default. Each module adds complexity and requires resources to use so keeping these to the minimum needed for your code will help it run faster and more efficiently. In this file we are importing:

  • aws_dynamodb: Lets you use high-level constructs to define a DynamoDB table.
  • Stack: Base class that represents a CloudFormation stack.
  • Construct: Core building block of CDK apps.

Next, we define the stack.

Remember, this is a set of resources to be created in AWS. This line looks a bit confusing but, all it’s doing is defining a Construct (also called a parent) and then assigning an ID to this stack so you can identify it later and then it’s asking for any other arguments (parameters or variables) that it needs to be able to run the commands. As we are keeping it simple we don’t have any arguments to pass so we add the None. Don’t forget in general we build Applications using CDK and not one-off components in this way, so the Construct element would point to the App you are building as this would be a part of that (don’t worry about this as a DBA but it’s useful to be able to picture it as a table in a database! The Construct here is the database and the Stack is the table).

The next part is the DynamoDB table definition:

  • table: This part defines the table as an element in Stack. Self refers to the Stack you are creating (see the previous code block and find the Self keyname). The UsersTables is both the table name we are creating and also serves as the prefix String for the unique ID of this resource in the Stack
  • partition_key: Defines the primary key (no sort key in this example).
  • billing_mode: We use on-demand to avoid provisioning throughput manually.

3. Deploy the Stack

First, bootstrap your environment (only once per account/region). Bootstrapping prepares the AWS environment to accept a CDK deployment. It’s similar to running a compiler if you’ve come from a Java background:

cdk bootstrap

Then deploy:

cdk deploy

CDK will show the changes and ask for confirmation. Once accepted, your table will be live.

4. Accessing the Table in Code

After deployment, you can access the table’s name or ARN in other parts of your stack like this:

table.table_name
table.table_arn

This is useful if you want to grant Lambda functions or other services access to the table dynamically. For example, you can now pass these details to your application so that it can programmatically gain access to the table without anyone having to type anything further or manually change configuration files! Amazing for development when you want to test something quickly, right?

Why This Beats ClickOps or Raw CloudFormation

ApproachDownsides
AWS Console (ClickOps)Not reproducible. Error-prone.
Raw CloudFormation YAML/JSONVerbose, hard to reuse, lacks testing logic.
CDK with PythonConcise, readable, reusable, testable, and version-controlled.

When building production systems, automation and repeatability matter. CDK gives you that without the tedium of verbose templates.

Production Considerations

If you’re building beyond a toy project:

  • Use Point-in-Time Recovery: Add point_in_time_recovery=True to your table config.
  • Add sort keys, GSIs, or LSIs for access pattern optimization.
  • Use environment variables or context variables to manage settings per environment.
  • Integrate with CI/CD for zero-touch deploys.
  • Write unit tests for your constructs using assertions module.

Wrapping Up

Using AWS CDK with Python to create DynamoDB tables is faster, safer, and cleaner than traditional methods. You get real infrastructure as code, complete with flexibility, automation, and the power of Python behind your deployments.

This was just a simple introduction showing the most basic of use cases. As always, the best way to go and learn is to stop reading and start doing! All of this will be covered under the AWS Free Tier so go and have a play and let me know how you get on.

If you’re still writing YAML or clicking through the AWS console, it’s time to level up. Or you can always get in touch!

Loading

Related Post