AWS CDKでDynamoDBのテーブルを作成する

2019.04.16

AWS CDK で DynamoDB テーブルを作成する

import cdk = require("@aws-cdk/cdk");
import dynamodb = require("@aws-cdk/aws-dynamodb");

export class MainStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    new dynamodb.CfnTable(this, "DynamoDBTable", {
      tableName: "SampleTable",
      billingMode: dynamodb.BillingMode.PayPerRequest,
      keySchema: [
        { attributeName: "id", keyType: "HASH" },
        { attributeName: "createdAt", keyType: "RANGE" }
      ],
      attributeDefinitions: [
        { attributeName: "id", attributeType: dynamodb.AttributeType.String },
        {
          attributeName: "createdAt",
          attributeType: dynamodb.AttributeType.String
        }
      ]
    });
  }
}

billingMode でオンデマンドを指定するには、dynamodb.BillingMode.PayPerRequest を指定すればよい。

@aws-cdk/aws-dynamodb には、CfnTable と Table の 2 つが定義されているが、どちらでも DynamoDB のテーブルを作成することができた。

CfnTable と Table で微妙にコンストラクタの 3 番目の引数の形が違うので注意が必要。