- Newest
- Most votes
- Most comments
To implement conditional creation of a DynamoDB table in AWS CDK using TypeScript, you can use a combination of the TableV2 construct and the fromTableName method. Here's an approach you can take:
-
First, use the
TableV2.fromTableNamemethod to attempt to reference an existing table. This method creates a reference to an existing table without actually creating a new one. -
If the table doesn't exist, this reference will be undefined, and you can then create a new table using the
TableV2construct.
Here's an example of how you might implement this:
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as cdk from 'aws-cdk-lib'; // ... in your stack definition const tableName = 'YourTableName'; // Try to reference an existing table const existingTable = dynamodb.TableV2.fromTableName(this, 'ExistingTable', tableName); let table: dynamodb.TableV2; if (existingTable === undefined) { // Table doesn't exist, create a new one table = new dynamodb.TableV2(this, 'NewTable', { tableName: tableName, partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING }, removalPolicy: cdk.RemovalPolicy.RETAIN, // ... other table properties }); } else { // Table exists, use the reference table = existingTable; } // Now you can use 'table' in the rest of your stack
This approach allows you to conditionally create the table or reference an existing one. The fromTableName method will not throw an error if the table doesn't exist, it will simply return undefined.
Remember that when you're referencing an existing table, you won't be able to modify its properties through CDK. Any changes to the table structure would need to be done outside of this stack.
Also, keep in mind that this approach doesn't guarantee atomicity. There's a small chance that the table could be created between the check and the creation step. If this is a concern, you might need to implement additional error handling or use a more robust strategy.
Lastly, ensure that your IAM permissions allow for describing DynamoDB tables, as the fromTableName method will attempt to describe the table to check its existence.
Sources
aws-cdk-lib.aws_dynamodb module · AWS CDK
CDK Typescript check if S3 already exists | AWS re:Post
Relevant content
asked a year ago
asked 5 years ago
asked a year ago

I implemented the solution as suggested above. The stack is created successfully, but the DynamoDB table is not created. It seems that the method dynamodb.TableV2.fromTableName does not return undefined if the table does not exist in AWS. (Instead, it always assumes the table exists and creates a reference to it, even if the table is not present in AWS.)
Could you please suggest a solution to conditionally create the DynamoDB table only if it does not already exist, and otherwise reference the existing table?
HI Team / Leeroy Hannigan, Could you please suggest solution here ??