Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
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
.
In order 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.