Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a DependsOn relation between EC2 and RDS using aws-cdk

I am currently using the aws-cdk (TypeScript) to create a stack that consists of an EC2 instance and a RDS databaseInstance.

The RDS instance needs to be setup before the EC2 instance can be started and userdata will be executed.

The problem I have is, that I could not find a way to define the DepensOn (Cloudformation) attribute between the two resources.

The workaround is, that I am using netsted stacks.

The code looks something like this:

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

Now I would like to define something like instance.dependsOn(rdsInstance).

Did anybody run into the same issue?

like image 320
F. Werkmeister Avatar asked Apr 16 '20 12:04

F. Werkmeister


People also ask

How do I add Dependson to CDK?

In order to specify a dependency in CDK we use the addDependency() method on the node - docs. For example, lets specify that a Cognito User Pool client depends on the creation of a Cognito Identity Pool OAuth Provider: Copied! const userPoolClient = new cognito.

Is AWS CDK better than CloudFormation?

Because the AWS CDK expands the number of resources that developers can manipulate through a code base, it offers more functionality than limited tools such as CloudFormation and Hashicorp TerraForm. The AWS CDK not only streamlines the provisioning process, it also simplifies verification and review.

What is a stack in AWS CDK?

The unit of deployment in the AWS CDK is called a stack. All AWS resources defined within the scope of a stack, either directly or indirectly, are provisioned as a single unit. Because AWS CDK stacks are implemented through AWS CloudFormation stacks, they have the same limitations as in AWS CloudFormation.


2 Answers

The solution here is to use addDependency() on the node, this will handle all the necessary CloudFormation DependsOn for you:

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

rdsInstance.node.addDependency(instance);

From the JSDoc of addDependency(): Add an ordering dependency on another Construct. All constructs in the dependency's scope will be deployed before any construct in this construct's scope.

like image 117
jogold Avatar answered Sep 29 '22 18:09

jogold


Hope the following helps you.

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

instance.addDependsOn(rdsInstance);
like image 21
Sam Avatar answered Sep 29 '22 18:09

Sam