AWS Cloud9 is no longer available to new customers. Existing customers of
AWS Cloud9 can continue to use the service as normal.
Learn more
AWS CDK tutorial for AWS Cloud9
This tutorial shows you how to work with the AWS Cloud Development Kit (AWS CDK) in an AWS Cloud9 development environment. The AWS CDK is a set of software tools and libraries that developers can use to model AWS infrastructure components as code.
The AWS CDK includes the AWS Construct Library that you can use to quickly resolve many
tasks on AWS. For example, you can use the Fleet construct to fully and
securely deploy code to a fleet of hosts. You can create your own constructs to model various
elements of your architectures, share them with others, or publish them to the community. For
more information, see the AWS Cloud Development Kit Developer
Guide.
Following this tutorial and creating this sample might result in charges to your AWS
account. These include possible charges for services such as Amazon EC2, Amazon SNS, and Amazon SQS. For more
information, see Amazon EC2 Pricing
Topics
Prerequisites
Before you use this sample, make sure that your setup meets the following requirements:
-
You must have an existing AWS Cloud9 EC2 development environment. This sample assumes that you already have an EC2 environment that's connected to an Amazon EC2 instance that runs Amazon Linux or Ubuntu Server. If you have a different type of environment or operating system, you might need to adapt this sample's instructions to set up related tools. For more information, see Creating an environment in AWS Cloud9.
-
You have the AWS Cloud9 IDE for the existing environment already open. When you open an environment, AWS Cloud9 opens the IDE for that environment in your web browser. For more information, see Opening an environment in AWS Cloud9.
Step 1: Install required tools
In this step, you install all of the tools in your environment that the AWS CDK needs to run a sample that is written in the TypeScript programming language.
-
Node Version Manager, or
nvm, which you use to install Node.js later. -
Node.js, which is required by the sample and contains Node Package Manager, or
npm, which you use to install TypeScript and the AWS CDK later. -
TypeScript, which is required by this sample. (The AWS CDK also provides support for several other programming languages.)
-
The AWS CDK.
Step 1.1: Install Node Version Manager (nvm)
-
In a terminal session in the AWS Cloud9 IDE, ensure the latest security updates and bug fixes are installed. To do this, run the
yum update(for Amazon Linux) orapt updatecommand (for Ubuntu Server). (To start a new terminal session, on the menu bar, choose Window, New Terminal.)For Amazon Linux:
sudo yum -y updateFor Ubuntu Server:
sudo apt update -
Confirm whether
nvmis already installed. To do this, run thenvmcommand with the--versionoption.nvm --versionIf successful, the output contains the
nvmversion number, and you can skip ahead to Step 1.2: Install Node.js. -
Download and install
nvm. To do this, run the install script. In this example, v0.33.0 is installed, but you can check for the latest version ofnvmhere. curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash -
Start using
nvm. You can either close the terminal session and then restart it, or source the~/.bashrcfile that contains the commands to loadnvm.. ~/.bashrc
Step 1.2: Install Node.js
-
Confirm whether you already have Node.js installed, and if you do, confirm that the installed version is 16.17.0 or greater. This sample has been tested with Node.js 16.17.0. To check, with the terminal session still open in the IDE, run the
nodecommand with the--versionoption.node --versionIf you do have Node.js installed, the output contains the version number. If the version number is v16.17.0 skip ahead to Step 1.3: Install TypeScript.
-
Install Node.js 16 by running the
nvmcommand with theinstallaction.Note
You can also run
nvm install nodeto install the long-term support (LTS) version of Node.js. AWS Cloud9 support tracks the LTS version of Node.js.nvm install v16 -
Start using Node.js 16. To do this, run the
nvmcommand with thealiasaction, the version number to alias, and the version to use for that alias, as follows.nvm alias default 16Note
The preceding command sets Node.js 16 as the default version of Node.js. Alternatively, you can run the
nvmcommand along with theuseaction instead of thealiasaction (for example,nvm use 16.17.0). However, theuseaction causes that version of Node.js to run only while the current terminal session is running. -
To confirm that you're using Node.js 16 run the
node --versioncommand again. If the correct version is installed, the output contains version v16.
Step 1.3: Install TypeScript
-
Confirm whether you already have TypeScript installed. To do this, with the terminal session still open in the IDE, run the command line TypeScript compiler with the
--versionoption.tsc --versionIf you do have TypeScript installed, the output contains the TypeScript version number. If TypeScript is installed, skip ahead to Step 1.4: Install the AWS CDK.
-
Install TypeScript. To do this, run the
npmcommand with theinstallaction, the-goption, and the name of the TypeScript package. This installs TypeScript as a global package in the environment.npm install -g typescript -
Confirm that TypeScript is installed. To do this, run the command line TypeScript compiler with the
--versionoption.tsc --versionIf TypeScript is installed, the output contains the TypeScript version number.
Step 1.4: Install the AWS CDK
-
Confirm whether you already have the AWS CDK installed. To do this, with the terminal session still open in the IDE, run the
cdkcommand with the--versionoption.cdk --versionIf the AWS CDK is installed, the output contains the AWS CDK version and build numbers. Skip ahead to Step 2: Add code.
-
Install the AWS CDK by running the
npmcommand along with theinstallaction, the name of the AWS CDK package to install, and the-goption to install the package globally in the environment.npm install -g aws-cdk -
Confirm that the AWS CDK is installed and correctly referenced. To do this, run the
cdkcommand with the--versionoption.cdk --versionIf successful, the AWS CDK version and build numbers are displayed.
Step 2: Add code
In this step, you create a sample TypeScript project that contains all of the source code you need for the AWS CDK to programmatically deploy an AWS CloudFormation stack. This stack creates an Amazon SNS topic and an Amazon SQS queue in your AWS account and then subscribes the queue to the topic.
-
With the terminal session still open in the IDE, create a directory to store the project's source code, for example a
~/environment/hello-cdkdirectory in your environment. Then switch to that directory.rm -rf ~/environment/hello-cdk # Remove this directory if it already exists. mkdir ~/environment/hello-cdk # Create the directory. cd ~/environment/hello-cdk # Switch to the directory. -
Set up the directory as a TypeScript language project for the AWS CDK. To do this, run the
cdkcommand with theinitaction, thesample-apptemplate, and the--languageoption along with the name of the programming language.cdk init sample-app --language typescriptThis creates the following files and subdirectories in the directory.
-
A hidden
.gitsubdirectory and a hidden.gitignorefile, which makes the project compatible with source control tools such as Git. -
A
libsubdirectory, which includes ahello-cdk-stack.tsfile. This file contains the code for your AWS CDK stack. This code is described in the next step in this procedure. -
A
binsubdirectory, which includes ahello-cdk.tsfile. This file contains the entry point for your AWS CDK app. -
A
node_modulessubdirectory, which contains supporting code packages that the app and stack can use as needed. -
A hidden
.npmignorefile, which lists the types of subdirectories and files thatnpmdoesn't need when it builds the code. -
A
cdk.jsonfile, which contains information to make running thecdkcommand easier. -
A
package-lock.jsonfile, which contains information thatnpmcan use to reduce possible build and run errors. -
A
package.jsonfile, which contains information to make running thenpmcommand easier and with possibly fewer build and run errors. -
A
README.mdfile, which lists useful commands you can run withnpmand the AWS CDK. -
A
tsconfig.jsonfile, which contains information to make running thetsccommand easier and with possibly fewer build and run errors.
-
-
In the Environment window, open the
lib/hello-cdk-stack.tsfile, and browse the following code in that file.import sns = require('@aws-cdk/aws-sns'); import sqs = require('@aws-cdk/aws-sqs'); import cdk = require('@aws-cdk/cdk'); export class HelloCdkStack extends cdk.Stack { constructor(parent: cdk.App, name: string, props?: cdk.StackProps) { super(parent, name, props); const queue = new sqs.Queue(this, 'HelloCdkQueue', { visibilityTimeoutSec: 300 }); const topic = new sns.Topic(this, 'HelloCdkTopic'); topic.subscribeQueue(queue); } }-
The
Stack,App,StackProps,Queue, andTopicclasses represent an AWS CloudFormation stack and its properties, an executable program, an Amazon SQS queue, and an Amazon SNS topic, respectively. -
The
HelloCdkStackclass represents the AWS CloudFormation stack for this application. This stack contains the new Amazon SQS queue and Amazon SNS topic for this application.
-
-
In the Environment window, open the
bin/hello-cdk.tsfile, and browse the following code in that file.#!/usr/bin/env node import cdk = require('@aws-cdk/cdk'); import { HelloCdkStack } from '../lib/hello-cdk-stack'; const app = new cdk.App(); new HelloCdkStack(app, 'HelloCdkStack'); app.run();This code loads, instantiates, and then runs the
HelloCdkStackclass from thelib/hello-cdk-stack.tsfile. -
Use
npmto run the TypeScript compiler to check for coding errors, and then enable the AWS CDK to execute the project'sbin/hello-cdk.jsfile. To do this, from the project's root directory, run thenpmcommand with therunaction, specifying thebuildcommand value in thepackage.jsonfile, as follows.npm run buildThe preceding command runs the TypeScript compiler, which adds supporting
bin/hello-cdk.d.tsandlib/hello-cdk-stack.d.tsfiles. The compiler also transpiles thehello-cdk.tsandhello-cdk-stack.tsfiles intohello-cdk.jsandhello-cdk-stack.jsfiles.
Step 3: Run the code
In this step, you instruct the AWS CDK to create a AWS CloudFormation stack template based on the code
in the bin/hello-cdk.js file. You then instruct the AWS CDK to deploy
the stack, which creates the Amazon SNS topic and Amazon SQS queue and then subscribes the queue to
the topic. You then confirm that the topic and queue were successfully deployed by sending
a message from the topic to the queue.
-
Have the AWS CDK create the AWS CloudFormation stack template. To do this, with the terminal session still open in the IDE, from the project's root directory, run the
cdkcommand with thesynthaction and the name of the stack.cdk synth HelloCdkStackIf successful, the output displays the AWS CloudFormation stack template's
Resourcessection. -
The first time that you deploy an AWS CDK app into an environment for a specific AWS account and AWS Region combination, you must install a bootstrap stack. This stack includes various resources that the AWS CDK needs to complete its various operations. For example, this stack includes an Amazon S3 bucket that the AWS CDK uses to store templates and assets during its deployment processes. To install the bootstrap stack, run the
cdkcommand with thebootstrapaction.cdk bootstrapNote
If you run
cdk bootstrapwithout specifying any options, the default AWS account and AWS Region are used. You can also bootstrap a specific environment by specifying a profile and account/Region combination. For example:cdk bootstrap --profile test 123456789012/us-east-1 -
Have the AWS CDK run the AWS CloudFormation stack template to deploy the stack. To do this, from the project's root directory, run the
cdkcommand with thedeployaction and the name of the stack.cdk deploy HelloCdkStackIf successful, the output displays that the
HelloCdkStackstack deployed without errors.Note
If the output displays a message that the stack does not define an environment and that AWS credentials could not be obtained from standard locations or no region was configured, make sure that your AWS credentials are set correctly in the IDE, and then run the
cdk deploycommand again. For more information, see Calling AWS services from an environment in AWS Cloud9. -
To confirm that the Amazon SNS topic and Amazon SQS queue were successfully deployed, send a message to the topic, and then check the queue for the received message. To do this, you can use a tool such as the AWS Command Line Interface (AWS CLI) or the AWS CloudShell. For more information about these tools, see the AWS CLI and aws-shell tutorial for AWS Cloud9.
For example, to send a message to the topic, with the terminal session still open in the IDE, use the AWS CLI to run the Amazon SNS
publishcommand, supplying the message's subject and body, the AWS Region for the topic, and the topic's Amazon Resource Name (ARN).aws sns publish --subject "Hello from the AWS CDK" --message "This is a message from the AWS CDK." --topic-arn arn:aws:sns:us-east-2:123456789012:HelloCdkStack-HelloCdkTopic1A234567-8BCD9EFGHIJ0KIn the preceding command, replace
arn:aws:sns:us-east-2:123456789012:HelloCdkStack-HelloCdkTopic1A234567-8BCD9EFGHIJ0Kwith the ARN that AWS CloudFormation assigns to the topic. To get the ID, you can run the Amazon SNSlist-topicscommand.aws sns list-topics --output table --query 'Topics[*].TopicArn'If successful, the output of the
publishcommand displays theMessageIdvalue for the message that was published.To check the queue for the received message, run the Amazon SQS
receive-messagecommand, supplying the queue's URL.aws sqs receive-message --queue-url https://queue.amazonaws.com/123456789012/HelloCdkStack-HelloCdkQueue1A234567-8BCD9EFGHIJ0KIn the preceding command, replace
https://queue.amazonaws.com/123456789012/HelloCdkStack-HelloCdkQueue1A234567-8BCD9EFGHIJ0Kwith the ARN that AWS CloudFormation assigns to the queue. To get the URL, you can run the Amazon SQSlist-queuescommand.aws sqs list-queues --output table --query 'QueueUrls[*]'If successful, the output of the
receive-messagecommand displays information about the message that was received.
Step 4: Clean up
To prevent ongoing charges to your AWS account after you're done using this sample, you should delete the AWS CloudFormation stack. This deletes the the Amazon SNS topic and Amazon SQS queue. You should also delete the environment.
Step 4.1: Delete the stack
With the terminal session still open in the IDE, from the project's root directory,
run the
cdk
command with the
destroy
action and the stack's name.
cdk destroy HelloCdkStack
When prompted to delete the stack, type y, and then press
Enter.
If successful, the output displays that the HelloCdkStack stack was
deleted without errors.
Step 4.2: Delete the environment
To delete the environment, see Deleting an environment in AWS Cloud9.