AWS Cloud Development Kit (CDK) allows you to define cloud infrastructure in code and provision it through AWS CloudFormation. It uses familiar programming languages, including JavaScript, TypeScript, Python, C#, and Java.
The following is an example of how to create an Amazon DynamoDB table with AWS CDK using Python. First, ensure that you have installed the necessary AWS CDK library for DynamoDB. You can do this with the following command:
pip install aws-cdk.aws-dynamodb
Then, use the following Python code to define a new DynamoDB table in your CDK stack:
from aws_cdk import core as cdk
from aws_cdk import aws_dynamodb as dynamodb
class MyCdkStack(cdk.Stack):
def __init__(self, scope: cdk.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# Create a new DynamoDB table
dynamodb.Table(self, "MyTable",
partition_key=dynamodb.Attribute(
name="id",
type=dynamodb.AttributeType.STRING
),
sort_key=dynamodb.Attribute(
name="timestamp",
type=dynamodb.AttributeType.STRING
),
table_name="MyTable",
billing_mode=dynamodb.BillingMode.PROVISIONED,
read_capacity=5,
write_capacity=5,
removal_policy=cdk.RemovalPolicy.RETAIN,
)
This Python code creates a new DynamoDB table named MyTable with a string partition key id a string sort key timestamp. The table will use provisioned capacity mode with 5 RCU and 5 WCU. The removal_policy is set to RemovalPolicy.RETAIN, meaning that if the CDK stack is destroyed, the DynamoDB table will not be deleted.
Deploying CDK
You can deploy your CDK stack using the following command:
cdk deploy
This command will create a CloudFormation stack which will create your DynamoDB table.