Skip to content

Conditional Creation of DynamoDB

0

I implemented the solution as below. 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.

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?

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
3 Answers
1

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

0

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:

  1. Use a custom resource in your CDK stack to check if the table exists.
  2. 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

  • 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 ?

0

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:

  1. Changed catchErrorPattern to ignoreErrorCodesMatching:
ignoreErrorCodesMatching: 'ResourceNotFoundException'

This tells the custom resource to not fail when the table doesn't exist.

  1. 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.

  1. 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;
}
AWS
EXPERT

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.