简体   繁体   中英

CDK create resource if does not exist - typescript

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 },
    });

Unfortunately you can't do that in CDK, because CDK generates CloudFormation template at compile time, not at runtime. I see several options here:

  1. Use CloudFormation Resource Import to import existing table into your stack
  2. Use Custom resource lambda to do an AWS API call to check if table exists. Use Custom resource output in Fn.conditionEquals in CDK code to create table conditionally

I would recommend going with first option if it's a one-off thing you need to do, and option 2 if you expect this to happen regularly.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM