【问题标题】:How can I create a DependsOn relation between EC2 and RDS using aws-cdk如何使用 aws-cdk 在 EC2 和 RDS 之间创建 DependsOn 关系
【发布时间】:2020-07-29 17:22:25
【问题描述】:

我目前正在使用 aws-cdk (TypeScript) 创建一个堆栈,该堆栈由一个 EC2 实例和一个 RDS 数据库实例组成。

RDS 实例需要在 EC2 实例可以启动并执行 userdata 之前设置。

我遇到的问题是,我找不到在两个资源之间定义 DepensOn (Cloudformation) 属性的方法。

解决方法是,我使用的是 netsted 堆栈。

代码如下所示:

const instance = new ec2.Instance(this, 'Instance', {...})
const rdsInstance = new rds.DatabaseInstance(this, 'DbInstance', {...})

现在我想定义类似 instance.dependsOn(rdsInstance) 的东西。

有人遇到过同样的问题吗?

【问题讨论】:

    标签: amazon-web-services amazon-ec2 amazon-rds aws-cdk


    【解决方案1】:

    这里的解决方案是在node 上使用addDependency(),这将为您处理所有必要的CloudFormation DependsOn

    const instance = new ec2.Instance(this, 'Instance', {...});
    const rdsInstance = new rds.DatabaseInstance(this, 'DbInstance', {...});
    
    rdsInstance.node.addDependency(instance);
    

    来自addDependency() 的 JSDoc:添加对另一个 Construct 的排序依赖。依赖项范围内的所有构造都将在此构造范围内的任何构造之前部署。

    【讨论】:

    • 我还尝试了将这两种解决方案部署在一个堆栈中。这会导致异常...aws-cdk/node_modules/constructs/lib/private/dependency.ts:86 throw new Error(${instance} 没有实现 DependableTrait); Error: [object Object] does not implement DependableTrait at Function.get ...node_modules/constructs/lib/private/dependency.ts:86:13)
    • 您使用的是哪个版本的 CDK?所有模块都使用相同的确切版本?
    • 仔细检查一下:它的版本是 1.32.2(构建 e19e206),并且 package.json 中的所有依赖项都有这个版本。
    • 刚刚再次查看答案,我发现在rdsInstance.node.addDependency(instance); 实例中没有.node。所以它就像@jogold 描述的那样工作。非常感谢!!
    • @Sanjari 你可以做resource.node.addDependency(...otherResources)
    【解决方案2】:

    希望以下内容对您有所帮助。

    const instance = new ec2.Instance(this, 'Instance', { /* ... */ }).getInstance();
    const rdsInstance = new rds.DatabaseInstance(this, 'DbInstance', { /* ... */ }).getInstance();
    
    instance.addDependsOn(rdsInstance);
    

    【讨论】:

    • 感谢您的回答,但这在某种程度上不起作用,因为ec2.Instancerds.DatabaseInstance 没有方法getInstance()。但不知何故,如果我理解正确from the docs,我们需要让底层CfnRessource 调用addDependsOn(otherResource)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2022-09-23
    • 2022-11-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多