DEV Community

Mikaeel Khalid for AWS Community Builders

Posted on • Originally published at blog.mikaeels.com on

Dependency relation in AWS CDK

AWS CDK

Sometimes when using the AWS Cloud Development Kit (CDK), the correct order for provisioning resources may not be automatically inferred. For instance, if you have an Amazon Elastic Compute Cloud (EC2), it will depend on your Virtual Private Cloud (VPC) resource.

Another example will be if you have a MySQL Relational Database Service (RDS) instance and an EC2 instance. In this case, you may want the EC2 instance to be created after the database so that you can run initialization code, and create tables, if necessary.

To specify dependencies in CDK, you can use the addDependency() method on the resource node and include the DependsOn attribute to indicate that the creation of resource A should follow that of resource B.

Here is an example of how you might use the addDependency() method in the AWS CDK to specify a dependency between two resources:

const vpc = new ec2.Vpc(this, 'my-vpc', {
  cidr: '10.0.0.0/16',
});

const db = new rds.DatabaseInstance(this, 'my-db', {
  engine: rds.DatabaseInstanceEngine.MYSQL,
  vpc,
});

const ec2 = new ec2.Instance(this, 'my-ec2', {
  instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2,                     
  ec2.InstanceSize.MICRO),
  machineImage: new ec2.AmazonLinuxImage(),
  vpc,
});

// Add a dependency between the EC2 instance and the RDS database
ec2.node.addDependency(db);

Enter fullscreen mode Exit fullscreen mode

This will ensure that the RDS the database is created before the EC2 instance, allowing you to run any necessary initialization code on the EC2 instance after the database is available.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Create a simple OTP system with AWS Serverless cover image

Create a simple OTP system with AWS Serverless

Implement a One Time Password (OTP) system with AWS Serverless services including Lambda, API Gateway, DynamoDB, Simple Email Service (SES), and Amplify Web Hosting using VueJS for the frontend.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay