- Newest
- Most votes
- Most comments
hey there!
what i'd do is remove the logic that tries to conditionally create the table, and instead just define the table using new dynamodb.TableV2. if the table doesn't exist, CDK will create it when you deploy. if the table already exists but was created outside CDK, the deployment will fail unless CDK already manages it.
const table = new dynamodb.TableV2(this, tableName, {
tableName: 'YourTableName',
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
just make sure that the CDK created and owns the table and that it's not created manually or in any other way so you don't get the fail.
answered a year ago
The approach you've taken is on the right track, but there's a slight misunderstanding about how the fromTableName method works in CDK. This method always returns a reference to a table, regardless of whether the table actually exists in AWS or not. It's designed to create a reference without verifying the table's existence.
To conditionally create a DynamoDB table only if it doesn't exist, you'll need to use a different approach. Here's a solution that should work:
- Use a custom resource in your CDK stack to check if the table exists.
- Based on the result of this check, either create a new table or reference the existing one.
Here's how you can implement this:
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as cdk from 'aws-cdk-lib'; import * as cr from 'aws-cdk-lib/custom-resources'; import * as iam from 'aws-cdk-lib/aws-iam'; // In your stack definition const tableName = 'YourTableName'; // Custom resource to check if the table exists const checkTableExists = new cr.AwsCustomResource(this, 'CheckTableExists', { onUpdate: { service: 'DynamoDB', action: 'describeTable', parameters: { TableName: tableName, }, physicalResourceId: cr.PhysicalResourceId.of(Date.now().toString()), }, policy: cr.AwsCustomResourcePolicy.fromStatements([ new iam.PolicyStatement({ actions: ['dynamodb:DescribeTable'], resources: ['*'], }), ]), }); // Catch and handle the error if the table doesn't exist const tableExists = checkTableExists.getResponseField('Table.TableName'); // Conditionally create the table const table = tableExists ? dynamodb.Table.fromTableName(this, 'ExistingTable', tableName) : new dynamodb.Table(this, 'NewTable', { tableName: tableName, partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING }, removalPolicy: cdk.RemovalPolicy.RETAIN, // ... other table properties }); // Now you can use 'table' in the rest of your stack
This solution uses a custom resource to call the DynamoDB describeTable API. If the table exists, it will return the table details. If it doesn't exist, it will throw an error, which is caught and handled.
Based on whether the table exists or not, we either reference the existing table using fromTableName or create a new one.
Remember to handle any errors that might occur during this process and ensure your IAM permissions are set up correctly to allow describing and creating DynamoDB tables.
Sources
CDK TypeScript: Conditional Creation of DynamoDB Table | AWS re:Post
Boto3, Is there a straightforward convention on checking that a DynamoDB table exists? | AWS re:Post
answered a year ago
When the table doesn't exist, the getResponseField will throw an error because there's no response to get fields from. Here's a better implementation:
import * as cdk from 'aws-cdk-lib'; import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as cr from 'aws-cdk-lib/custom-resources'; export class MyStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const tableName = 'YourTableName'; // Create a Custom Resource to check if the table exists const tableExistenceCheck = new cr.AwsCustomResource(this, 'CheckTableExistence', { onCreate: { service: 'DynamoDB', action: 'describeTable', parameters: { TableName: tableName }, physicalResourceId: cr.PhysicalResourceId.of(tableName), ignoreErrorCodesMatching: 'ResourceNotFoundException', // This is key }, policy: cr.AwsCustomResourcePolicy.fromSdkCalls({ resources: cr.AwsCustomResourcePolicy.ANY_RESOURCE, }), }); // Add explicit dependency to ensure the check happens first const tableExists = tableExistenceCheck.getResponseField('Table') !== undefined; let table: dynamodb.ITable; if (tableExists) { console.log(`Table ${tableName} exists, creating reference`); table = dynamodb.Table.fromTableName(this, 'ExistingTable', tableName); } else { console.log(`Table ${tableName} does not exist, creating new table`); table = new dynamodb.TableV2(this, 'NewTable', { tableName: tableName, partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING }, removalPolicy: cdk.RemovalPolicy.RETAIN, }); } } }
Key changes and explanations:
- Changed
catchErrorPatterntoignoreErrorCodesMatching:
ignoreErrorCodesMatching: 'ResourceNotFoundException'
This tells the custom resource to not fail when the table doesn't exist.
- Changed the existence check:
const tableExists = tableExistenceCheck.getResponseField('Table') !== undefined;
When the table doesn't exist, the response will be undefined, making this check safe.
- You can also add error handling using a try-catch block:
let tableExists = false; try { tableExists = tableExistenceCheck.getResponseField('Table') !== undefined; } catch (error) { console.log('Error checking table existence:', error); tableExists = false; }
Relevant content
asked a year ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 3 years ago

as suggested above, Custom resource to check if the table exists but what if table doesn't exists? it will thrown an 'ResourceNotFoundException' error ? is 'getResponseField' is compatible with 'ResourceNotFoundException' error ?