A DynamoDB table with a stream and a GSI
Terraform needs every key attribute declared, including the index key, and CDK's default ALL projection must be stated. CDK generated a table name, so the Terraform version sets one: use the deployed name when you import.
import { Stack, StackProps, RemovalPolicy } from "aws-cdk-lib";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import { Construct } from "constructs";
export class OrdersStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
const table = new dynamodb.Table(this, "Orders", {
partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING },
sortKey: { name: "sk", type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
stream: dynamodb.StreamViewType.NEW_AND_OLD_IMAGES,
removalPolicy: RemovalPolicy.RETAIN,
});
table.addGlobalSecondaryIndex({
indexName: "byCustomer",
partitionKey: { name: "customerId", type: dynamodb.AttributeType.STRING },
});
}
}
resource "aws_dynamodb_table" "orders" {
name = "orders"
billing_mode = "PAY_PER_REQUEST"
hash_key = "pk"
range_key = "sk"
stream_enabled = true
stream_view_type = "NEW_AND_OLD_IMAGES"
attribute {
name = "pk"
type = "S"
}
attribute {
name = "sk"
type = "S"
}
attribute {
name = "customerId"
type = "S"
}
global_secondary_index {
name = "byCustomer"
hash_key = "customerId"
projection_type = "ALL"
}
lifecycle {
prevent_destroy = true
}
}