Namespace Amazon.CDK.AWS.DynamoDB
Amazon DynamoDB Construct Library
The DynamoDB construct library has two table constructs - <code>Table</code> and <code>TableV2</code>. <code>TableV2</code> is the preferred construct for all use cases, including creating a single table or a table with multiple <code>replicas</code>.
Here is a minimal deployable DynamoDB table using TableV2
:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING }
});
By default, TableV2
will create a single table in the main deployment region referred to as the primary table. The properties of the primary table are configurable via TableV2
properties. For example, consider the following DynamoDB table created using the TableV2
construct defined in a Stack
being deployed to us-west-2
:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
ContributorInsights = true,
TableClass = TableClass.STANDARD_INFREQUENT_ACCESS,
PointInTimeRecovery = true
});
The above TableV2
definition will result in the provisioning of a single table in us-west-2
with properties that match the properties set on the TableV2
instance.
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html
Replicas
The TableV2
construct can be configured with replica tables. This will enable you to work with your table as a global table. To do this, the TableV2
construct must be defined in a Stack
with a defined region. The main deployment region must not be given as a replica because this is created by default with the TableV2
construct. The following is a minimal example of defining TableV2
with replicas
. This TableV2
definition will provision three copies of the table - one in us-west-2
(primary deployment region), one in us-east-1
, and one in us-east-2
.
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
Alternatively, you can add new replicas
to an instance of the TableV2
construct using the addReplica
method:
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" } }
});
globalTable.AddReplica(new ReplicaTableProps { Region = "us-east-2", DeletionProtection = true });
The following properties are configurable on a per-replica basis, but will be inherited from the TableV2
properties if not specified:
The following example shows how to define properties on a per-replica basis:
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
ContributorInsights = true,
PointInTimeRecovery = true,
Replicas = new [] { new ReplicaTableProps {
Region = "us-east-1",
TableClass = TableClass.STANDARD_INFREQUENT_ACCESS,
PointInTimeRecovery = false
}, new ReplicaTableProps {
Region = "us-east-2",
ContributorInsights = false
} }
});
To obtain an ITableV2
reference to a specific replica table, call the replica
method on an instance of the TableV2
construct and pass the replica region as an argument:
using Amazon.CDK;
User user;
class FooStack : Stack
{
public TableV2 GlobalTable { get; }
public FooStack(Construct scope, string id, StackProps props) : base(scope, id, props)
{
GlobalTable = new TableV2(this, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
}
}
class BarStackProps : StackProps
{
public ITableV2 ReplicaTable { get; set; }
}
class BarStack : Stack
{
public BarStack(Construct scope, string id, BarStackProps props) : base(scope, id, props)
{
// user is given grantWriteData permissions to replica in us-east-1
props.ReplicaTable.GrantWriteData(user);
}
}
var app = new App();
var fooStack = new FooStack(app, "FooStack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var barStack = new BarStack(app, "BarStack", new BarStackProps {
ReplicaTable = fooStack.GlobalTable.Replica("us-east-1"),
Env = new Environment { Region = "us-east-1" }
});
Note: You can create an instance of the TableV2
construct with as many replicas
as needed as long as there is only one replica per region. After table creation you can add or remove replicas
, but you can only add or remove a single replica in each update.
Billing
The TableV2
construct can be configured with on-demand or provisioned billing:
Note: writeCapacity
can only be configured using autoscaled capacity.
The following example shows how to configure TableV2
with on-demand billing:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Billing = Billing.OnDemand()
});
The following example shows how to configure TableV2
with on-demand billing with optional maximum throughput configured:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Billing = Billing.OnDemand(new MaxThroughputProps {
MaxReadRequestUnits = 100,
MaxWriteRequestUnits = 115
})
});
When using provisioned billing, you must also specify readCapacity
and writeCapacity
. You can choose to configure readCapacity
with fixed capacity or autoscaled capacity, but writeCapacity
can only be configured with autoscaled capacity. The following example shows how to configure TableV2
with provisioned billing:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Billing = Billing.Provisioned(new ThroughputProps {
ReadCapacity = Capacity.Fixed(10),
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MaxCapacity = 15 })
})
});
When using provisioned billing, you can configure the readCapacity
on a per-replica basis:
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Billing = Billing.Provisioned(new ThroughputProps {
ReadCapacity = Capacity.Fixed(10),
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MaxCapacity = 15 })
}),
Replicas = new [] { new ReplicaTableProps {
Region = "us-east-1"
}, new ReplicaTableProps {
Region = "us-east-2",
ReadCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MaxCapacity = 20, TargetUtilizationPercent = 50 })
} }
});
When changing the billing for a table from provisioned to on-demand or from on-demand to provisioned, seedCapacity
must be configured for each autoscaled resource:
var globalTable = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Billing = Billing.Provisioned(new ThroughputProps {
ReadCapacity = Capacity.Fixed(10),
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MaxCapacity = 10, SeedCapacity = 20 })
})
});
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html
Encryption
All user data stored in a DynamoDB table is fully encrypted at rest. When creating an instance of the TableV2
construct, you can select the following table encryption options:
The following is an example of how to configure TableV2
with encryption using an AWS owned key:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Encryption = TableEncryptionV2.DynamoOwnedKey()
});
The following is an example of how to configure TableV2
with encryption using an AWS managed key:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Encryption = TableEncryptionV2.AwsManagedKey()
});
When configuring TableV2
with encryption using customer managed keys, you must specify the KMS key for the primary table as the tableKey
. A map of replicaKeyArns
must be provided containing each replica region and the associated KMS key ARN:
using Amazon.CDK;
using Amazon.CDK.AWS.KMS;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var tableKey = new Key(stack, "Key");
IDictionary<string, string> replicaKeyArns = new Dictionary<string, string> {
{ "us-east-1", "arn:aws:kms:us-east-1:123456789012:key/g24efbna-az9b-42ro-m3bp-cq249l94fca6" },
{ "us-east-2", "arn:aws:kms:us-east-2:123456789012:key/h90bkasj-bs1j-92wp-s2ka-bh857d60bkj8" }
};
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Encryption = TableEncryptionV2.CustomerManagedKey(tableKey, replicaKeyArns),
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
Note: When encryption is configured with customer managed keys, you must have a key already created in each replica region.
Further reading: https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-mgmt
Secondary Indexes
Secondary indexes allow efficient access to data with attributes other than the primaryKey
. DynamoDB supports two types of secondary indexes:
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html
Global Secondary Indexes
TableV2
can be configured with globalSecondaryIndexes
by providing them as a TableV2
property:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
GlobalSecondaryIndexes = new [] { new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING }
} }
});
Alternatively, you can add a globalSecondaryIndex
using the addGlobalSecondaryIndex
method:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
GlobalSecondaryIndexes = new [] { new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi1",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING }
} }
});
table.AddGlobalSecondaryIndex(new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi2",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING }
});
You can configure readCapacity
and writeCapacity
on a globalSecondaryIndex
when an TableV2
is configured with provisioned billing
. If TableV2
is configured with provisioned billing
but readCapacity
or writeCapacity
are not configured on a globalSecondaryIndex
, then they will be inherited from the capacity settings specified with the billing
configuration:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Billing = Billing.Provisioned(new ThroughputProps {
ReadCapacity = Capacity.Fixed(10),
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MaxCapacity = 10 })
}),
GlobalSecondaryIndexes = new [] { new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi1",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
ReadCapacity = Capacity.Fixed(15)
}, new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi2",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MinCapacity = 5, MaxCapacity = 20 })
} }
});
All globalSecondaryIndexes
for replica tables are inherited from the primary table. You can configure contributorInsights
and readCapacity
for each globalSecondaryIndex
on a per-replica basis:
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
ContributorInsights = true,
Billing = Billing.Provisioned(new ThroughputProps {
ReadCapacity = Capacity.Fixed(10),
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MaxCapacity = 10 })
}),
// each global secondary index will inherit contributor insights as true
GlobalSecondaryIndexes = new [] { new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi1",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
ReadCapacity = Capacity.Fixed(15)
}, new GlobalSecondaryIndexPropsV2 {
IndexName = "gsi2",
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
WriteCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MinCapacity = 5, MaxCapacity = 20 })
} },
Replicas = new [] { new ReplicaTableProps {
Region = "us-east-1",
GlobalSecondaryIndexOptions = new Dictionary<string, ReplicaGlobalSecondaryIndexOptions> {
{ "gsi1", new ReplicaGlobalSecondaryIndexOptions {
ReadCapacity = Capacity.Autoscaled(new AutoscaledCapacityOptions { MinCapacity = 1, MaxCapacity = 10 })
} }
}
}, new ReplicaTableProps {
Region = "us-east-2",
GlobalSecondaryIndexOptions = new Dictionary<string, ReplicaGlobalSecondaryIndexOptions> {
{ "gsi2", new ReplicaGlobalSecondaryIndexOptions {
ContributorInsights = false
} }
}
} }
});
Local Secondary Indexes
TableV2
can only be configured with localSecondaryIndexes
when a sortKey
is defined as a TableV2
property.
You can provide localSecondaryIndexes
as a TableV2
property:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
SortKey = new Attribute { Name = "sk", Type = AttributeType.NUMBER },
LocalSecondaryIndexes = new [] { new LocalSecondaryIndexProps {
IndexName = "lsi",
SortKey = new Attribute { Name = "sk", Type = AttributeType.NUMBER }
} }
});
Alternatively, you can add a localSecondaryIndex
using the addLocalSecondaryIndex
method:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
SortKey = new Attribute { Name = "sk", Type = AttributeType.NUMBER },
LocalSecondaryIndexes = new [] { new LocalSecondaryIndexProps {
IndexName = "lsi1",
SortKey = new Attribute { Name = "sk", Type = AttributeType.NUMBER }
} }
});
table.AddLocalSecondaryIndex(new LocalSecondaryIndexProps {
IndexName = "lsi2",
SortKey = new Attribute { Name = "sk", Type = AttributeType.NUMBER }
});
Streams
Each DynamoDB table produces an independent stream based on all its writes, regardless of the origination point for those writes. DynamoDB supports two stream types:
DynamoDB Streams
A dynamoStream
can be configured as a TableV2
property. If the TableV2
instance has replica tables, then all replica tables will inherit the dynamoStream
setting from the primary table. If replicas are configured, but dynamoStream
is not configured, then the primary table and all replicas will be automatically configured with the NEW_AND_OLD_IMAGES
stream view type.
using Amazon.CDK;
using Amazon.CDK.AWS.Kinesis;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(this, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "id", Type = AttributeType.STRING },
DynamoStream = StreamViewType.OLD_IMAGE,
// tables in us-west-2, us-east-1, and us-east-2 all have dynamo stream type of OLD_IMAGES
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html
Kinesis Streams
A kinesisStream
can be configured as a TableV2
property. Replica tables will not inherit the kinesisStream
configured for the primary table and should added on a per-replica basis.
using Amazon.CDK;
using Amazon.CDK.AWS.Kinesis;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var stream1 = new Stream(stack, "Stream1");
var stream2 = Stream.FromStreamArn(stack, "Stream2", "arn:aws:kinesis:us-east-2:123456789012:stream/my-stream");
var globalTable = new TableV2(this, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "id", Type = AttributeType.STRING },
KinesisStream = stream1, // for table in us-west-2
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps {
Region = "us-east-2",
KinesisStream = stream2
} }
});
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/kds.html
Keys
When an instance of the TableV2
construct is defined, you must define its schema using the partitionKey
(required) and sortKey
(optional) properties.
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
SortKey = new Attribute { Name = "sk", Type = AttributeType.NUMBER }
});
Contributor Insights
Enabling contributorInsights
for TableV2
will provide information about the most accessed and throttled items in a table or globalSecondaryIndex
. DynamoDB delivers this information to you via CloudWatch Contributor Insights rules, reports, and graphs of report data.
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
ContributorInsights = true
});
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights_HowItWorks.html
Deletion Protection
deletionProtection
determines if your DynamoDB table is protected from deletion and is configurable as a TableV2
property. When enabled, the table cannot be deleted by any user or process.
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
DeletionProtection = true
});
You can also specify the removalPolicy
as a property of the TableV2
construct. This property allows you to control what happens to tables provisioned using TableV2
during stack
deletion. By default, the removalPolicy
is RETAIN
which will cause all tables provisioned using TableV2
to be retained in the account, but orphaned from the stack
they were created in. You can also set the removalPolicy
to DESTROY
which will delete all tables created using TableV2
during stack
deletion:
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
// applys to all replicas, i.e., us-west-2, us-east-1, us-east-2
RemovalPolicy = RemovalPolicy.DESTROY,
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
deletionProtection
is configurable on a per-replica basis. If the removalPolicy
is set to DESTROY
, but some replicas
have deletionProtection
enabled, then only the replicas
without deletionProtection
will be deleted during stack
deletion:
using Amazon.CDK;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
RemovalPolicy = RemovalPolicy.DESTROY,
DeletionProtection = true,
// only the replica in us-east-1 will be deleted during stack deletion
Replicas = new [] { new ReplicaTableProps {
Region = "us-east-1",
DeletionProtection = false
}, new ReplicaTableProps {
Region = "us-east-2",
DeletionProtection = true
} }
});
Point-in-Time Recovery
pointInTimeRecovery
provides automatic backups of your DynamoDB table data which helps protect your tables from accidental write or delete operations.
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
PointInTimeRecovery = true
});
Table Class
You can configure a TableV2
instance with table classes:
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
TableClass = TableClass.STANDARD_INFREQUENT_ACCESS
});
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html
Tags
You can add tags to a TableV2
in several ways. By adding the tags to the construct itself it will apply the tags to the
primary table.
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Tags = new [] { new CfnTag { Key = "primaryTableTagKey", Value = "primaryTableTagValue" } }
});
You can also add tags to replica tables by specifying them within the replica table properties.
var table = new TableV2(this, "Table", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Replicas = new [] { new ReplicaTableProps {
Region = "us-west-1",
Tags = new [] { new CfnTag { Key = "replicaTableTagKey", Value = "replicaTableTagValue" } }
} }
});
Referencing Existing Global Tables
To reference an existing DynamoDB table in your CDK application, use the TableV2.fromTableName
, TableV2.fromTableArn
, or TableV2.fromTableAttributes
factory methods:
User user;
var table = TableV2.FromTableArn(this, "ImportedTable", "arn:aws:dynamodb:us-east-1:123456789012:table/my-table");
// now you can call methods on the referenced table
table.GrantReadWriteData(user);
If you intend to use the tableStreamArn
(including indirectly, for example by creating an
aws-cdk-lib/aws-lambda-event-sources.DynamoEventSource
on the referenced table), you must use the
TableV2.fromTableAttributes
method and the tableStreamArn
property must be populated.
To grant permissions to indexes for a referenced table you can either set grantIndexPermissions
to true
, or you can provide the indexes via the globalIndexes
or localIndexes
properties. This will enable grant*
methods to also grant permissions to all table indexes.
Resource Policy
Using resourcePolicy
you can add a resource policy to a table in the form of a PolicyDocument
:
// resource policy document
const policy = new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
actions: ['dynamodb:GetItem'],
principals: [new iam.AccountRootPrincipal()],
resources: ['*'],
}),
],
});
// table with resource policy
new dynamodb.TableV2(this, 'TableTestV2-1', {
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
removalPolicy: RemovalPolicy.DESTROY,
resourcePolicy: policy,
});
TableV2 doesn’t support creating a replica and adding a resource-based policy to that replica in the same stack update in Regions other than the Region where you deploy the stack update. To incorporate a resource-based policy into a replica, you'll need to initially deploy the replica without the policy, followed by a subsequent update to include the desired policy.
Grants
Using any of the grant*
methods on an instance of the TableV2
construct will only apply to the primary table, its indexes, and any associated encryptionKey
. As an example, grantReadData
used below will only apply the table in us-west-2
:
using Amazon.CDK;
using Amazon.CDK.AWS.KMS;
User user;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var tableKey = new Key(stack, "Key");
IDictionary<string, string> replicaKeyArns = new Dictionary<string, string> {
{ "us-east-1", "arn:aws:kms:us-east-1:123456789012:key/g24efbna-az9b-42ro-m3bp-cq249l94fca6" },
{ "us-east-2", "arn:aws:kms:us-east-2:123456789012:key/g24efbna-az9b-42ro-m3bp-cq249l94fca6" }
};
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Encryption = TableEncryptionV2.CustomerManagedKey(tableKey, replicaKeyArns),
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
// grantReadData only applys to the table in us-west-2 and the tableKey
globalTable.GrantReadData(user);
The replica
method can be used to grant to a specific replica table:
using Amazon.CDK;
using Amazon.CDK.AWS.KMS;
User user;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var tableKey = new Key(stack, "Key");
IDictionary<string, string> replicaKeyArns = new Dictionary<string, string> {
{ "us-east-1", "arn:aws:kms:us-east-1:123456789012:key/g24efbna-az9b-42ro-m3bp-cq249l94fca6" },
{ "us-east-2", "arn:aws:kms:us-east-2:123456789012:key/g24efbna-az9b-42ro-m3bp-cq249l94fca6" }
};
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Encryption = TableEncryptionV2.CustomerManagedKey(tableKey, replicaKeyArns),
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
// grantReadData applys to the table in us-east-2 and the key arn for the key in us-east-2
globalTable.Replica("us-east-2").GrantReadData(user);
Metrics
You can use metric*
methods to generate metrics for a table that can be used when configuring an Alarm
or Graphs
. The metric*
methods only apply to the primary table provisioned using the TableV2
construct. As an example, metricConsumedReadCapacityUnits
used below is only for the table in us-west-2
:
using Amazon.CDK;
using Amazon.CDK.AWS.CloudWatch;
var app = new App();
var stack = new Stack(app, "Stack", new StackProps { Env = new Environment { Region = "us-west-2" } });
var globalTable = new TableV2(stack, "GlobalTable", new TablePropsV2 {
PartitionKey = new Attribute { Name = "pk", Type = AttributeType.STRING },
Replicas = new [] { new ReplicaTableProps { Region = "us-east-1" }, new ReplicaTableProps { Region = "us-east-2" } }
});
// metric is only for the table in us-west-2
var metric = globalTable.MetricConsumedReadCapacityUnits();
new Alarm(this, "Alarm", new AlarmProps {
Metric = metric,
EvaluationPeriods = 1,
Threshold = 1
});
The replica
method can be used to generate a metric for a specific replica table:
import * as cdk form 'aws-cdk-lib';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';
class FooStack extends cdk.Stack {
public readonly globalTable: dynamodb.TableV2;
public constructor(scope: Construct, id: string, props: cdk.StackProps) {
super(scope, id, props);
this.globalTable = new dynamodb.Tablev2(this, 'GlobalTable', {
partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING },
replicas: [
{ region: 'us-east-1' },
{ region: 'us-east-2' },
],
});
}
}
interface BarStack extends cdk.StackProps {
readonly replicaTable: dynamodb.ITableV2;
}
class BarStack extends cdk.Stack {
public constructor(scope: Construct, id: string, props: BarStackProps) {
super(scope, id, props);
// metric is only for the table in us-east-1
const metric = props.replicaTable.metricConsumedReadCapacityUnits();
new cloudwatch.Alarm(this, 'Alarm', {
metric: metric,
evaluationPeriods: 1,
threshold: 1,
});
}
}
const app = new cdk.App();
const fooStack = new FooStack(app, 'FooStack', { env: { region: 'us-west-2' } });
const barStack = new BarStack(app, 'BarStack', {
replicaTable: fooStack.globalTable.replica('us-east-1'),
env: { region: 'us-east-1' },
});
import from S3 Bucket
You can import data in S3 when creating a Table using the Table
construct.
To import data into DynamoDB, it is required that your data is in a CSV, DynamoDB JSON, or Amazon Ion format within an Amazon S3 bucket.
The data may be compressed using ZSTD or GZIP formats, or you may choose to import it without compression.
The data source can be a single S3 object or multiple S3 objects sharing a common prefix.
Further reading: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/S3DataImport.HowItWorks.html
use CSV format
The InputFormat.csv
method accepts delimiter
and headerList
options as arguments.
If delimiter
is not specified, ,
is used by default.
And if headerList
is specified, the first line of CSV is treated as data instead of header.
using Amazon.CDK;
using Amazon.CDK.AWS.S3;
IBucket bucket;
var app = new App();
var stack = new Stack(app, "Stack");
new Table(stack, "Table", new TableProps {
PartitionKey = new Attribute {
Name = "id",
Type = AttributeType.STRING
},
ImportSource = new ImportSourceSpecification {
CompressionType = InputCompressionType.GZIP,
InputFormat = InputFormat.Csv(new CsvOptions {
Delimiter = ",",
HeaderList = new [] { "id", "name" }
}),
Bucket = bucket,
KeyPrefix = "prefix"
}
});
use DynamoDB JSON format
Use the InputFormat.dynamoDBJson()
method to specify the inputFormat
property.
There are currently no options available.
using Amazon.CDK;
using Amazon.CDK.AWS.S3;
IBucket bucket;
var app = new App();
var stack = new Stack(app, "Stack");
new Table(stack, "Table", new TableProps {
PartitionKey = new Attribute {
Name = "id",
Type = AttributeType.STRING
},
ImportSource = new ImportSourceSpecification {
CompressionType = InputCompressionType.GZIP,
InputFormat = InputFormat.DynamoDBJson(),
Bucket = bucket,
KeyPrefix = "prefix"
}
});
use Amazon Ion format
Use the InputFormat.ion()
method to specify the inputFormat
property.
There are currently no options available.
using Amazon.CDK;
using Amazon.CDK.AWS.S3;
IBucket bucket;
var app = new App();
var stack = new Stack(app, "Stack");
new Table(stack, "Table", new TableProps {
PartitionKey = new Attribute {
Name = "id",
Type = AttributeType.STRING
},
ImportSource = new ImportSourceSpecification {
CompressionType = InputCompressionType.GZIP,
InputFormat = InputFormat.Ion(),
Bucket = bucket,
KeyPrefix = "prefix"
}
});
Classes
Attribute | Represents an attribute for describing the key schema for the table and indexes. |
AttributeType | Data types for attributes within a table. |
AutoscaledCapacityOptions | Options used to configure autoscaled capacity. |
Billing | Represents how capacity is managed and how you are charged for read and write throughput for a DynamoDB table. |
BillingMode | DynamoDB's Read/Write capacity modes. |
Capacity | Represents the amount of read and write operations supported by a DynamoDB table. |
CapacityMode | Capacity modes. |
CfnGlobalTable | The |
CfnGlobalTable.AttributeDefinitionProperty | Represents an attribute for describing the schema for the table and indexes. |
CfnGlobalTable.CapacityAutoScalingSettingsProperty | Configures a scalable target and an autoscaling policy for a table or global secondary index's read or write capacity. |
CfnGlobalTable.ContributorInsightsSpecificationProperty | Configures contributor insights settings for a replica or one of its indexes. |
CfnGlobalTable.GlobalSecondaryIndexProperty | Allows you to specify a global secondary index for the global table. |
CfnGlobalTable.KeySchemaProperty | Represents a single element of a key schema. |
CfnGlobalTable.KinesisStreamSpecificationProperty | The Kinesis Data Streams configuration for the specified global table replica. |
CfnGlobalTable.LocalSecondaryIndexProperty | Represents the properties of a local secondary index. |
CfnGlobalTable.PointInTimeRecoverySpecificationProperty | Represents the settings used to enable point in time recovery. |
CfnGlobalTable.ProjectionProperty | Represents attributes that are copied (projected) from the table into an index. |
CfnGlobalTable.ReadOnDemandThroughputSettingsProperty | Sets the read request settings for a replica table or a replica global secondary index. |
CfnGlobalTable.ReadProvisionedThroughputSettingsProperty | Allows you to specify the read capacity settings for a replica table or a replica global secondary index when the |
CfnGlobalTable.ReplicaGlobalSecondaryIndexSpecificationProperty | Represents the properties of a global secondary index that can be set on a per-replica basis. |
CfnGlobalTable.ReplicaSpecificationProperty | Defines settings specific to a single replica of a global table. |
CfnGlobalTable.ReplicaSSESpecificationProperty | Allows you to specify a KMS key identifier to be used for server-side encryption. |
CfnGlobalTable.ReplicaStreamSpecificationProperty | Represents the DynamoDB Streams configuration for a global table replica. |
CfnGlobalTable.ResourcePolicyProperty | Creates or updates a resource-based policy document that contains the permissions for DynamoDB resources, such as a table, its indexes, and stream. |
CfnGlobalTable.SSESpecificationProperty | Represents the settings used to enable server-side encryption. |
CfnGlobalTable.StreamSpecificationProperty | Represents the DynamoDB Streams configuration for a table in DynamoDB. |
CfnGlobalTable.TargetTrackingScalingPolicyConfigurationProperty | Defines a target tracking scaling policy. |
CfnGlobalTable.TimeToLiveSpecificationProperty | Represents the settings used to enable or disable Time to Live (TTL) for the specified table. |
CfnGlobalTable.WriteOnDemandThroughputSettingsProperty | Sets the write request settings for a global table or a global secondary index. |
CfnGlobalTable.WriteProvisionedThroughputSettingsProperty | Specifies an auto scaling policy for write capacity. |
CfnGlobalTableProps | Properties for defining a |
CfnTable | The |
CfnTable.AttributeDefinitionProperty | Represents an attribute for describing the schema for the table and indexes. |
CfnTable.ContributorInsightsSpecificationProperty | The settings used to enable or disable CloudWatch Contributor Insights. |
CfnTable.CsvProperty | The options for imported source files in CSV format. |
CfnTable.GlobalSecondaryIndexProperty | Represents the properties of a global secondary index. |
CfnTable.ImportSourceSpecificationProperty | Specifies the properties of data being imported from the S3 bucket source to the table. |
CfnTable.InputFormatOptionsProperty | The format options for the data that was imported into the target table. |
CfnTable.KeySchemaProperty | Represents a single element of a key schema. |
CfnTable.KinesisStreamSpecificationProperty | The Kinesis Data Streams configuration for the specified table. |
CfnTable.LocalSecondaryIndexProperty | Represents the properties of a local secondary index. |
CfnTable.OnDemandThroughputProperty | Sets the maximum number of read and write units for the specified on-demand table. |
CfnTable.PointInTimeRecoverySpecificationProperty | The settings used to enable point in time recovery. |
CfnTable.ProjectionProperty | Represents attributes that are copied (projected) from the table into an index. |
CfnTable.ProvisionedThroughputProperty | Throughput for the specified table, which consists of values for |
CfnTable.ResourcePolicyProperty | Creates or updates a resource-based policy document that contains the permissions for DynamoDB resources, such as a table, its indexes, and stream. |
CfnTable.S3BucketSourceProperty | The S3 bucket that is being imported from. |
CfnTable.SSESpecificationProperty | Represents the settings used to enable server-side encryption. |
CfnTable.StreamSpecificationProperty | Represents the DynamoDB Streams configuration for a table in DynamoDB. |
CfnTable.TimeToLiveSpecificationProperty | Represents the settings used to enable or disable Time to Live (TTL) for the specified table. |
CfnTableProps | Properties for defining a |
CsvOptions | The options for imported source files in CSV format. |
EnableScalingProps | Properties for enabling DynamoDB capacity scaling. |
GlobalSecondaryIndexProps | Properties for a global secondary index. |
GlobalSecondaryIndexPropsV2 | Properties used to configure a global secondary index. |
ImportSourceSpecification | Properties for importing data from the S3. |
InputCompressionType | Type of compression to use for imported data. |
InputFormat | The format of the source data. |
LocalSecondaryIndexProps | Properties for a local secondary index. |
MaxThroughputProps | Properties used to configure maximum throughput for an on-demand table. |
Operation | Supported DynamoDB table operations. |
OperationsMetricOptions | Options for configuring metrics that considers multiple operations. |
ProjectionType | The set of attributes that are projected into the index. |
ReplicaGlobalSecondaryIndexOptions | Options used to configure global secondary indexes on a replica table. |
ReplicaTableProps | Properties used to configure a replica table. |
SchemaOptions | Represents the table schema attributes. |
SecondaryIndexProps | Properties for a secondary index. |
StreamViewType | When an item in the table is modified, StreamViewType determines what information is written to the stream for this table. |
SystemErrorsForOperationsMetricOptions | Options for configuring a system errors metric that considers multiple operations. |
Table | Provides a DynamoDB table. |
TableAttributes | Reference to a dynamodb table. |
TableAttributesV2 | Attributes of a DynamoDB table. |
TableBase | |
TableBaseV2 | Base class for a DynamoDB table. |
TableClass | DynamoDB's table class. |
TableEncryption | What kind of server-side encryption to apply to this table. |
TableEncryptionV2 | Represents server-side encryption for a DynamoDB table. |
TableOptions | Properties of a DynamoDB Table. |
TableOptionsV2 | Options used to configure a DynamoDB table. |
TableProps | Properties for a DynamoDB Table. |
TablePropsV2 | Properties used to configure a DynamoDB table. |
TableV2 | A DynamoDB Table. |
ThroughputProps | Properties used to configure provisioned throughput for a DynamoDB table. |
UtilizationScalingProps | Properties for enabling DynamoDB utilization tracking. |
Interfaces
CfnGlobalTable.IAttributeDefinitionProperty | Represents an attribute for describing the schema for the table and indexes. |
CfnGlobalTable.ICapacityAutoScalingSettingsProperty | Configures a scalable target and an autoscaling policy for a table or global secondary index's read or write capacity. |
CfnGlobalTable.IContributorInsightsSpecificationProperty | Configures contributor insights settings for a replica or one of its indexes. |
CfnGlobalTable.IGlobalSecondaryIndexProperty | Allows you to specify a global secondary index for the global table. |
CfnGlobalTable.IKeySchemaProperty | Represents a single element of a key schema. |
CfnGlobalTable.IKinesisStreamSpecificationProperty | The Kinesis Data Streams configuration for the specified global table replica. |
CfnGlobalTable.ILocalSecondaryIndexProperty | Represents the properties of a local secondary index. |
CfnGlobalTable.IPointInTimeRecoverySpecificationProperty | Represents the settings used to enable point in time recovery. |
CfnGlobalTable.IProjectionProperty | Represents attributes that are copied (projected) from the table into an index. |
CfnGlobalTable.IReadOnDemandThroughputSettingsProperty | Sets the read request settings for a replica table or a replica global secondary index. |
CfnGlobalTable.IReadProvisionedThroughputSettingsProperty | Allows you to specify the read capacity settings for a replica table or a replica global secondary index when the |
CfnGlobalTable.IReplicaGlobalSecondaryIndexSpecificationProperty | Represents the properties of a global secondary index that can be set on a per-replica basis. |
CfnGlobalTable.IReplicaSpecificationProperty | Defines settings specific to a single replica of a global table. |
CfnGlobalTable.IReplicaSSESpecificationProperty | Allows you to specify a KMS key identifier to be used for server-side encryption. |
CfnGlobalTable.IReplicaStreamSpecificationProperty | Represents the DynamoDB Streams configuration for a global table replica. |
CfnGlobalTable.IResourcePolicyProperty | Creates or updates a resource-based policy document that contains the permissions for DynamoDB resources, such as a table, its indexes, and stream. |
CfnGlobalTable.ISSESpecificationProperty | Represents the settings used to enable server-side encryption. |
CfnGlobalTable.IStreamSpecificationProperty | Represents the DynamoDB Streams configuration for a table in DynamoDB. |
CfnGlobalTable.ITargetTrackingScalingPolicyConfigurationProperty | Defines a target tracking scaling policy. |
CfnGlobalTable.ITimeToLiveSpecificationProperty | Represents the settings used to enable or disable Time to Live (TTL) for the specified table. |
CfnGlobalTable.IWriteOnDemandThroughputSettingsProperty | Sets the write request settings for a global table or a global secondary index. |
CfnGlobalTable.IWriteProvisionedThroughputSettingsProperty | Specifies an auto scaling policy for write capacity. |
CfnTable.IAttributeDefinitionProperty | Represents an attribute for describing the schema for the table and indexes. |
CfnTable.IContributorInsightsSpecificationProperty | The settings used to enable or disable CloudWatch Contributor Insights. |
CfnTable.ICsvProperty | The options for imported source files in CSV format. |
CfnTable.IGlobalSecondaryIndexProperty | Represents the properties of a global secondary index. |
CfnTable.IImportSourceSpecificationProperty | Specifies the properties of data being imported from the S3 bucket source to the table. |
CfnTable.IInputFormatOptionsProperty | The format options for the data that was imported into the target table. |
CfnTable.IKeySchemaProperty | Represents a single element of a key schema. |
CfnTable.IKinesisStreamSpecificationProperty | The Kinesis Data Streams configuration for the specified table. |
CfnTable.ILocalSecondaryIndexProperty | Represents the properties of a local secondary index. |
CfnTable.IOnDemandThroughputProperty | Sets the maximum number of read and write units for the specified on-demand table. |
CfnTable.IPointInTimeRecoverySpecificationProperty | The settings used to enable point in time recovery. |
CfnTable.IProjectionProperty | Represents attributes that are copied (projected) from the table into an index. |
CfnTable.IProvisionedThroughputProperty | Throughput for the specified table, which consists of values for |
CfnTable.IResourcePolicyProperty | Creates or updates a resource-based policy document that contains the permissions for DynamoDB resources, such as a table, its indexes, and stream. |
CfnTable.IS3BucketSourceProperty | The S3 bucket that is being imported from. |
CfnTable.ISSESpecificationProperty | Represents the settings used to enable server-side encryption. |
CfnTable.IStreamSpecificationProperty | Represents the DynamoDB Streams configuration for a table in DynamoDB. |
CfnTable.ITimeToLiveSpecificationProperty | Represents the settings used to enable or disable Time to Live (TTL) for the specified table. |
IAttribute | Represents an attribute for describing the key schema for the table and indexes. |
IAutoscaledCapacityOptions | Options used to configure autoscaled capacity. |
ICfnGlobalTableProps | Properties for defining a |
ICfnTableProps | Properties for defining a |
ICsvOptions | The options for imported source files in CSV format. |
IEnableScalingProps | Properties for enabling DynamoDB capacity scaling. |
IGlobalSecondaryIndexProps | Properties for a global secondary index. |
IGlobalSecondaryIndexPropsV2 | Properties used to configure a global secondary index. |
IImportSourceSpecification | Properties for importing data from the S3. |
ILocalSecondaryIndexProps | Properties for a local secondary index. |
IMaxThroughputProps | Properties used to configure maximum throughput for an on-demand table. |
IOperationsMetricOptions | Options for configuring metrics that considers multiple operations. |
IReplicaGlobalSecondaryIndexOptions | Options used to configure global secondary indexes on a replica table. |
IReplicaTableProps | Properties used to configure a replica table. |
IScalableTableAttribute | Interface for scalable attributes. |
ISchemaOptions | Represents the table schema attributes. |
ISecondaryIndexProps | Properties for a secondary index. |
ISystemErrorsForOperationsMetricOptions | Options for configuring a system errors metric that considers multiple operations. |
ITable | An interface that represents a DynamoDB Table - either created with the CDK, or an existing one. |
ITableAttributes | Reference to a dynamodb table. |
ITableAttributesV2 | Attributes of a DynamoDB table. |
ITableOptions | Properties of a DynamoDB Table. |
ITableOptionsV2 | Options used to configure a DynamoDB table. |
ITableProps | Properties for a DynamoDB Table. |
ITablePropsV2 | Properties used to configure a DynamoDB table. |
ITableV2 | Represents an instance of a DynamoDB table. |
IThroughputProps | Properties used to configure provisioned throughput for a DynamoDB table. |
IUtilizationScalingProps | Properties for enabling DynamoDB utilization tracking. |