AWS CDK allows us to define these dependencies explicitly, thereby enabling us to control the sequence in which resources are created or deleted.
This article will guide you on how to establish a “DependsOn” relationship between an Amazon RDS Instance and an EC2 Instance in AWS CDK TypeScript.
Let’s get started!
Table of Contents
1. Prerequisites
Before we start building the constructs, you’re required to have done the following prerequisites before you can run AWS CDK code in TypeScript.
- Install AWS CDK and TypeScript NPM packages
- Install the AWS CLI and configure an AWS profile
- Create an AWS CDK TypeScript project
If you’ve already done this, you can proceed with step 2.
1.1 Install AWS CDK
Use the NPM package manager in your terminal to install AWS CDK and TypeScript globally on your system:
➜ npm install -g aws-cdk typescript
added 180 packages, and audited 181 packages in 7s
found 0 vulnerabilities
~ took 7s
Once you’ve installed AWS CDK you can validate that you’re running on the latest version by running the following command in the terminal:
➜ cdk version
2.23.0 (build 50444aa)
1.2 Install AWS CLI and configure an AWS profile
The AWS CLI is a command line tool that allows you to interact with AWS services in your terminal. Depending on if you’re running Linux, macOS, or Windows the installation goes like this:
# macOS install method:
brew install awscli
# Windows install method:
wget https://awscli.amazonaws.com/AWSCLIV2.msi
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
# Linux (Ubuntu) install method:
sudo apt install awscli
In order to access your AWS account with the AWS CLI, you first need to configure an AWS Profile. There are 2 ways of configuring a profile:
- Access and secret key credentials from an IAM user
- AWS Single Sign-on (SSO) user
In this article, I’ll briefly explain how to configure the first method so that you can proceed more quickly to set up the Amazon S3 Bucket in AWS CDK.
If you wish to set up the AWS profile more securely, then I’d suggest you read and apply the steps described in setting up AWS CLI with AWS Single Sign-On (SSO).
In order to configure the AWS CLI with your IAM user’s access and secret key credentials, you need to login to the AWS Console. Go to IAM > Users, select your IAM user and click on the Security credentials tab to create an access and secret key.
Then configure the AWS profile on the AWS CLI as follows:
➜ aws configure
AWS Access Key ID [None]: <insert_access_key>
AWS Secret Access Key [None]: <insert_secret_key>
Default region name [None]: <insert_aws_region>
Default output format [json]: json
Your was credentials are stored in ~/.aws/credentials and you can validate that your AWS profile is working by running the command:
➜ aws sts get-caller-identity
{
"UserId": "AIDA5BRFSNF24CDMD7FNY",
"Account": "012345678901",
"Arn": "arn:aws:iam::012345678901:user/test-user"
}
1.3 Create a new AWS CDK TypeScript Project
Now that we’ve configured our profile and installed the packages, it’s time to create an AWS CDK TypeScript project where you’re going to build the Amazon S3 Bucket construct.
You can generate a new AWS CDK TypeScript project by running the following command in an empty directory:
➜ cdk init sample-app --language=typescript
Applying project template sample-app for typescript
# Welcome to your CDK TypeScript project!
You should explore the contents of this project. It demonstrates a CDK app with an instance of a stack (`CdkProjectStack`)
which contains an Amazon SQS queue that is subscribed to an Amazon SNS topic.
The `cdk.json` file tells the CDK Toolkit how to execute your app.
## Useful commands
* `npm run build` compile typescript to js
* `npm run watch` watch for changes and compile
* `npm run test` perform the jest unit tests
* `cdk deploy` deploy this stack to your default AWS account/region
* `cdk diff` compare deployed stack with current state
* `cdk synth` emits the synthesized CloudFormation template
Initializing a new git repository...
Executing npm install...
✅ All done!
2. How to Create a DependsOn Relation between Resources using AWS CDK TypeScript
Now that we’ve configured our workspace and cdk app, we can proceed with the creation of the constructs.
2.1 Create the CDK Stack with a VPC, EC2 instance and RDS instance
We’ll create the following resources in order to demonstrate how we can set up a DependsOn relation between an RDS Instance and EC2 instance within a VPC.
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import { Construct } from 'constructs';
class MyStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const vpc = new ec2.Vpc(this, 'MyVpc');
const rdsInstance = new rds.DatabaseInstance(this, 'MyRdsInstance', {
engine: rds.DatabaseInstanceEngine.mysql({
version: rds.MysqlEngineVersion.VER_8_0_19,
}),
credentials: rds.Credentials.fromGeneratedSecret('admin'),
vpc,
});
const ec2Instance = new ec2.Instance(this, 'MyEc2Instance', {
vpc,
instanceType: new ec2.InstanceType('t3.micro'),
machineImage: new ec2.AmazonLinuxImage(),
});
}
}
const app = new cdk.App();
new MyStack(app, 'MyStack');
app.synth();
2.2 Establish the DependsOn relationship
his is the final and most crucial step. Here, we will add the DependsOn relationship between the EC2 Instance and the RDS Instance.
We’ll accomplish this by using the addDependency
function:
// Add dependency.
ec2Instance.node.addDependency(rdsInstance);
By adding this line, we ensure that the EC2 Instance is not created until the RDS Instance is up and running.
When you synthesise the stack you’ll see the following under the EC2 instance resource in the CloudFormation template:
Resources:
MyEc2InstanceEC255155:
Type: AWS::EC2::Instance
Properties:
AvailabilityZone:
Fn::Select:
- 0
- Fn::GetAZs: ""
IamInstanceProfile:
Ref: MyEc2InstanceInstanceProfile829F17AB
ImageId:
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestamznamihvmx8664gp2C96584B6F00A464EAD1953AFF4B05118Parameter
InstanceType: t3.micro
SecurityGroupIds:
- Fn::GetAtt:
- MyEc2InstanceInstanceSecurityGroupE6404E7A
- GroupId
SubnetId:
Ref: MyVpcPrivateSubnet1Subnet5057CF7E
Tags:
- Key: Name
Value: ECSCronTaskStack/MyEc2Instance
UserData:
Fn::Base64: "#!/bin/bash"
DependsOn:
- MyEc2InstanceInstanceRole288C5C88
- MyRdsInstanceFB602CDD
- MyRdsInstanceSecretAttachmentC6CA4212
- ECSCronTaskStackMyRdsInstanceSecretDCC7ECCC3fdaad7efa858a3daf9490cf0a702aeb
- MyRdsInstanceSecurityGroup433C5D4C
- MyRdsInstanceSubnetGroup1D56B42D
And as you can see, at the bottom of the yaml template the DependsOn feature contains the RDS instance (MyRdsInstance…) resources.
Conclusion
And there you have it! You’ve successfully established a DependsOn relationship between an EC2 Instance and an RDS Instance using AWS CDK in TypeScript.
By understanding and using resource dependencies effectively, you can prevent unnecessary errors and ensure that your AWS resources are created and deleted in the correct order.
This becomes crucial in larger, more complex projects where there are multiple dependencies to consider.
Everything that you’ve just built by following this article can also be found as a fully working example on my GitHub repository.