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.

Top comments (0)