Last updated: Jan 27, 2024
Reading timeยท2 min
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);
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);
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.
You can learn more about the related topics by checking out the following tutorials: