How to set up AWS CDK - complete guide

How to set up AWS CDK - complete guide

Install AWS CDK by running the following command in your terminal: npm install -g aws-cdk. Then you can continue to initialize your first project.

Featured on Hashnode

To use AWS CDK you need to install it first. This can be done by running the following command in your terminal npm install -g aws-cdk. After you have set up AWS CDK then you can initialize your first project and deploy it

Here is how you can set up AWS CDK and get started on your first project:

Install AWS CDK

To install the AWS CDK toolkit on your machine, we use the node package manager in your terminal to install the package globally.

npm install -g aws-cdk

The result will look like

➜ npm install -g aws-cdk

added 180 packages, and audited 181 packages in 7s

found 0 vulnerabilities
~ took 7s

Once you've installed AWS CDK you can validate that it's working by running a command like cdk version

➜ cdk version
1.105.0 (build 4813992)

You might wonder what options and commands are at your disposal with the AWS CDK Toolkit. This can be check with:

cdk --help

Initialize AWS CDK Project

To create an AWS CDK project you can initialize it using the cdk init command. Here you specify your desired template and programming language, see the example for possible options:

➜ cdk init --list
Available templates:
* app: Template for a CDK Application
   └─ cdk init app --language=[csharp|fsharp|go|java|javascript|python|typescript]
* lib: Template for a CDK Construct Library
   └─ cdk init lib --language=typescript
* sample-app: Example CDK Application with some constructs
   └─ cdk init sample-app --language=[csharp|fsharp|java|javascript|python|typescript]

It might be the first time that you're running AWS CDK. So let's start out with the sample-app. This project contains some sample resources and demonstrates how a stack is created. To create the cdk project run thecdk init sample-app --language typescript command in your project folder:

➜ 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!

The command has automatically created the project structure and the necessary code to run the example app in AWS CDK. The project structure looks like this:

├── README.md
├── bin
│   └── cdk-project.ts
├── cdk.json
├── jest.config.js
├── lib
│   └── cdk-project-stack.ts
├── package-lock.json
├── package.json
├── test
│   └── cdk-project.test.ts
└── tsconfig.json

If you look closely you should see a lib folder at the root of your project folder. This contains the stack which contains the code for the resources. Since we've initialized AWS CDK with a sample-app it already creates an SQS queue and an SNS topic + subscription.

Generate CloudFormation templates with AWS CDK Synth

Now it's time to use AWS CDK to generate the CloudFormation template which we can use to deploy to our AWS Account. To do that we run the cdk synth command in the folder that you initialized in step 2:

➜ cdk synth
Resources:
  CdkProjectQueueD30BD26F:
    Type: AWS::SQS::Queue
    Properties:
      VisibilityTimeout: 300
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: CdkProjectStack/CdkProjectQueue/Resource
  CdkProjectQueuePolicy60E3A509:
    Type: AWS::SQS::QueuePolicy
    Properties:
      PolicyDocument:
        Statement:
          - Action: sqs:SendMessage
            Condition:
              ArnEquals:
                aws:SourceArn:
                  Ref: CdkProjectTopicCABDBCE5
            Effect: Allow
            Principal:
              Service: sns.amazonaws.com
            Resource:
              Fn::GetAtt:
                - CdkProjectQueueD30BD26F
                - Arn
        Version: "2012-10-17"
      Queues:
        - Ref: CdkProjectQueueD30BD26F
    Metadata:
      aws:cdk:path: CdkProjectStack/CdkProjectQueue/Policy/Resource
  CdkProjectQueueCdkProjectStackCdkProjectTopicEA58E728E3BEF797:
    Type: AWS::SNS::Subscription
    Properties:
      Protocol: sqs
      TopicArn:
        Ref: CdkProjectTopicCABDBCE5
      Endpoint:
        Fn::GetAtt:
          - CdkProjectQueueD30BD26F
          - Arn
    Metadata:
      aws:cdk:path: CdkProjectStack/CdkProjectQueue/CdkProjectStackCdkProjectTopicEA58E728/Resource
  CdkProjectTopicCABDBCE5:
    Type: AWS::SNS::Topic
    Metadata:
      aws:cdk:path: CdkProjectStack/CdkProjectTopic/Resource
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAAE1WNQQ6CMBBFz8K+HZEYL8AFFNwbmNZkAFvoUI0hvbu0TUzczP//5SVTQQmldAinonuzRDXKiXrY2rXDUezovvHCsF299lrUD5NLuhc7EX5+MM8g2Ox+63tGR/NK1kTjb9/sTBhpKiHE2mi23mH6UVujKJpBGKs0DHx4Hc9QQVkMTCSdNys9NTQ5vwsqLY3EAAAA
    Metadata:
      aws:cdk:path: CdkProjectStack/CDKMetadata/Default
    Condition: CDKMetadataAvailable
Conditions:
  CDKMetadataAvailable:
    Fn::Or:
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - af-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ca-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-northwest-1
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-2
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-3
          - Fn::Equals:
              - Ref: AWS::Region
              - me-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - sa-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-2
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-2
Parameters:
  BootstrapVersion:
    Type: AWS::SSM::Parameter::Value<String>
    Default: /cdk-bootstrap/hnb659fds/version
    Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store.
Rules:
  CheckBootstrapVersion:
    Assertions:
      - Assert:
          Fn::Not:
            - Fn::Contains:
                - - "1"
                  - "2"
                  - "3"
                - Ref: BootstrapVersion

As you can see in the result above, the command cdk synth shows the CloudFormation template in YAML format in your terminal. But for the actual deploy the template is saved in the cdk.out folder in JSON format.

Deploy with AWS CDK

To deploy the template that you synthesized with cdk synth on an AWS account. You need to have AWS CLI installed on your system and set up an AWS Profile. If you haven't set it up yet, then check this blog post below in which I explain how to set up AWS CLI including AWS Single Sign-On (SSO):

If you've done that you can proceed with the deployment. First, make sure to export your AWS profile with export AWS_PROFILE=<your_aws_profile_name>. Then you can deploy the synthesized template with cdk deploy:

➜ cdk deploy
This deployment will make potentially sensitive changes according to your current security approval level (--require-approval broadening).
Please confirm you intend to make the following modifications:

IAM Statement Changes

(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Do you wish to deploy these changes (y/n)? y
CdkProjectStack: deploying...
[0%] start: Publishing 8b185148d5516d058cb628a72cfac1ab6eff61aa5c83bc5c396601822bc9d954:current_account-current_region
[100%] success: Published 8b185148d5516d058cb628a72cfac1ab6eff61aa5c83bc5c396601822bc9d954:current_account-current_region
CdkProjectStack: creating CloudFormation changeset...
[██████████████████████████████████████████████████████████] (6/6)

 ✅  CdkProjectStack

Stack ARN:
arn:aws:cloudformation:eu-central-1:012345678901:stack/CdkProjectStack/5a8b31a0-bff0-11eb-833c-06576399fc58

Done! You've deployed your first AWS CDK App!

You now know how to set up AWS CDK, initialize a CDK project, synthesize a CloudFormation template and then deploy it on your AWS account.

If you wish to remove the stack from your AWS account, then run the following command cdk destroy.

Autocomplete AWS CDK L1 constructs with this extension for VS Code

If you want to make developing with AWS CDK easier, then have a look at this VS Code extension that I published on the marketplace that autocompletes every AWS CDK L1 construct for TypeScript. You can read more about it in this blogpost:

AWS CDK - FAQ

What is AWS CDK?

AWS CDK is an open-source framework that allows you to generate CloudFormation templates with modern programming languages like Python, TypeScript, Java, or C#.

Should I use AWS CDK?

That depends. If you're familiar with object-oriented programming then I would recommend you to use AWS CDK. AWS CDK does a lot of work for you behind the scenes when it generates CloudFormation templates. So it's not worth the effort to learn all the tiny details that CloudFormation has to offer. Learning the basics of it should be enough to get started effectively with AWS CDK.

If you're not a programmer or you're a beginner in the Cloud, then I would recommend getting started with CloudFormation. This is mainly because learning two concepts (programming + CloudFormation) can be really tough. So take one step at a time and begin with CloudFormatioon.

Is CDK better than CloudFormation?

The simple answer is yes! AWS CDK allows you to use logic like for-loops etc to define infrastructure. Whereas with CloudFormation you need to statically define infrastructure which causes large amounts of code.

Another advantage is that you're able to use object-oriented techniques to create reusable code. You also gain the ability to test your code whereas in CloudFormation you're limited to linting.


👋 Enjoyed this article? Reach out in the comments below or on Twitter to let me know what you think of it.

If you found some value in reading this, please consider showing your support by sponsoring me. Thanks to your support, I'm able to continue doing what I enjoy the most, which is sharing my learnings with the Cloud Community. Donate here 👇