1
votes

Created a dynamoDB table in my CDK project. this is fine it is used by lambdas created in the project. We needed to delete the stack which is also fine as we have retain resource set to true on the table.

Now when I try a fresh deploy we get table already exists error and stack rolls back. I need code that will create the table only if it does not exist.

Here is basic creation of a table, i cannot find any documentation anywhere on this issue or even an exception that can be caught or where i can see the type of exception that gets thrown to catch as we only see logs in the cloudformation console on AWS console.

 const dynamoTable = new Table(this, "my-table", {
      tableName: StackConfiguration.tableName,
      partitionKey: { name: "id", type: AttributeType.STRING },
    });
1
Maybe it is worth to look into the static methods that are part of the Table, e.g. static fromTableName(scope, id, tableName). With those you can bring "external"/ existing tables into the CDK app.Stefan Freitag

1 Answers

-2
votes

This isn't a great answer but a workaround, I will leave it here incase it might be of use to someone but we can add the table creation into a try catch in our code, I just caught a general exception rather than a specific one i would be interested if anyone had the correct exception to catch here. This means the stack will deploy.

 try {
     const dynamoTable = new Table(this, "my-table", {
      tableName: StackConfiguration.tableName,
      partitionKey: { name: "id", type: AttributeType.STRING },
    });
    
      return dynamoReplayTable;
    } catch (e) {
      return;
    }

If you want to use the table then in your code you will need to reference the ARN rather than the table variable name or else you could do some import from name thing in the catch block. But the best solution I have found is keep the tables in a separate stack.