Depends On relations in AWS CDK

Borislav Hadzhiev

Last updated: Jan 27, 2024
2 min


# Adding Depends on relationships in AWS CDK

Sometimes CDK can't infer the right order in which to provision our resources. For example, if we have an EC2 Internet Gateway, it is going to depend on our VPC resource.

Another example would be if we have a Postgres RDS instance and an EC2 instance. We'd like for our EC2 instance to be created after the database. That allows us to run initialization code, create the tables and seed the data if necessary.

In CDK, by adding the DependsOn attribute on resource A we specify that the creation of resource A should follow the creation of resource B.

To specify a dependency in CDK we use the addDependency() method on the node - docs.

For example, let's specify that a Cognito User Pool client depends on the creation of a Cognito Identity Pool OAuth Provider.

const userPoolClient = new cognito.UserPoolClient(this, 'userpool-client', { // ...props }); const identityProviderFacebook = new cognito.UserPoolIdentityProviderFacebook( this, 'idp-facebook', { // ...props }, ); // Add the dependency ๐Ÿ‘‡ userPoolClient.node.addDependency(identityProviderFacebook);
With the code snippet, we indicate to CDK that it should only create our User Pool Client after the Facebook Identity Provider has been created.

In pseudo-code, specifying that an EC2 instance should only be created after our database is created looks as follows.

const ec2Instance = new EC2Instance(); const database = new DatabaseConstruct(); // Add the dependency ๐Ÿ‘‡ ec2Instance.node.addDependency(database);

# Discussion

By using the constructA.node.addDependency(constructB) method, we are able to specify the order of resource creation in AWS CDK.

Most of the time CDK can infer the order of resource creation from our code, however, there are some corner cases where we have to be explicit.

I've also written a tutorial on how to provision and configure an RDS instance in AWS CDK.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev