CDK 创建资源,如果不存在 - 打字稿 [英] CDK create resource if does not exist - typescript

查看:30
本文介绍了CDK 创建资源,如果不存在 - 打字稿的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 CDK 项目中创建了一个 dynamoDB 表.这很好,它被项目中创建的 lambda 使用.我们需要删除堆栈,这也很好,因为我们在表上将保留资源设置为 true.

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.

这是一个表格的基本创建,我找不到任何关于这个问题的文档,甚至找不到可以捕获的异常,或者我可以看到抛出的异常类型,因为我们只能在 cloudformation 中看到日志AWS 控制台上的控制台.

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

推荐答案

这不是一个很好的答案,而是一种解决方法,我将它留在这里以防它可能对某人有用,但我们可以将表创建添加到在我们的代码中尝试 catch ,我只是捕获了一个一般异常而不是一个特定的异常,如果有人在这里捕获正确的异常,我会感兴趣.这意味着堆栈将部署.

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

如果您想使用该表,那么在您的代码中,您将需要引用 ARN 而不是表变量名称,否则您可以在 catch 块中从名称进行一些导入.但我发现的最佳解决方案是将表放在单独的堆栈中.

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.

这篇关于CDK 创建资源,如果不存在 - 打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆