Depends On relations in AWS CDK

avatar

Borislav Hadzhiev

Fri Apr 23 20212 min read

Updated on Fri Apr 23 2021

Adding Depends on relationships in AWS CDK #

Sometimes CDK can't infer the right order to provision our resources in. 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.

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:

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 above 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 like:

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.

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee