Depends On relations in AWS CDK


Borislav Hadzhiev

Wed Apr 13 20222 min read

Updated - Wed Apr 13 2022

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 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 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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.