fbpx Skip to content

How to Install and Upgrade the AWS CDK CLI

 AWS CDK CLI, a command-line interface tool, is an essential part of the AWS CDK that helps developers and operations engineers interact with the AWS CDK framework.

This article will provide a step-by-step guide on installing and upgrading your machine’s AWS CDK CLI. We will also cover how to check the version of the AWS CDK CLI installed on your device and why it’s essential to upgrade to the latest version.

Furthermore, we will cover how to troubleshoot common issues that users may encounter during the installation and upgrade.

Following this guide, you can successfully install and upgrade the AWS CDK CLI. This will enable you to start building infrastructure using the AWS CDK framework, allowing you to automate the creation, deployment, and management of AWS resources.

Keeping the AWS CDK CLI up to date will let you take advantage of new features and bug fixes, making it easier to manage your AWS resources and stay ahead of the competition.

How to install AWS Cloud Development Kit (CDK)?

To install AWS Cloud Development Kit (CDK) into your operating system, you need an AWS account to manage your AWS resources and AWS Command Line Interface (CLI).

Read the book: AWS Command Line Interface User Guide

This article will use the NPM package manager to install AWS CDK. Additionally, the NPM package manager is a universal installation method, that’s why you can use this method for any OS (macOSWindows, and Linux (Ubuntu)).

To Install the AWS CDK toolkit on your machine, type the following code in your terminal:

npm install -g aws-cdk

Check the CDK Version

Before using AWS CDK, confirm that you are using the latest version. To check the version of CDK, enter the following command:

cdk version

How to Troubleshoot and Upgrade the AWS CDK CLI?

After completing all the above steps, you successfully install the CDK CLI, but what if you face some problems while installing? AWS CDK CLI users commonly encountered an error of:

This CDK CLI is no compatible with the CDK library used by your application. Please upgrade the CLI to the latest version

With a single line command, you can quickly sort this issue, and the command line is given below:

npm install -g aws-cdk@latest

If you are using Yarn folk, run the below command:

yarn global upgrade aws-cdk

Sometimes Upgrading the CDK version does not solve problems of outdated dependency services between the aws-cdk. Core and other modules. Use the following commands to solve:

pip list --local --outdated |grep cdk  | awk '{print $1}' > requirements.txt
pip install --upgrade -r requirements.txt

Doing this lets you eliminate all the errors and successfully install the AWS CDK CLI on your machine. Let’s jump to the available command lines.

What are the available AWS CDK commands?

After installing, you must know the available command lines to use them properly. You can easily find all the commands and arguments available in the AWS CDK Toolkit by running the following:

➜ cdk --help

Usage: cdk -a <cdk-app> COMMAND
  cdk list [STACKS..]             Lists all stacks in the app      [aliases: ls]
  cdk synthesize [STACKS..]       Synthesizes and prints the CloudFormation
                                  template for this stack       [aliases: synth]
  cdk bootstrap [ENVIRONMENTS..]  Deploys the CDK toolkit stack into an AWS
  cdk deploy [STACKS..]           Deploys the stack(s) named STACKS into your
                                  AWS account
  cdk import [STACK]              Import existing resource(s) into the given
  cdk watch [STACKS..]            Shortcut for 'deploy --watch'
  cdk destroy [STACKS..]          Destroy the stack(s) named STACKS
  cdk diff [STACKS..]             Compares the specified stack with the deployed
                                  stack or a local template file, and returns
                                  with status 1 if any difference is found
  cdk metadata [STACK]            Returns all metadata associated with this
  cdk acknowledge [ID]            Acknowledge a notice so that it does not show
                                  up anymore                      [aliases: ack]
  cdk notices                     Returns a list of relevant notices
  cdk init [TEMPLATE]             Create a new, empty CDK project from a
  cdk context                     Manage cached context values
  cdk docs                        Opens the reference documentation in a browser
                                                                  [aliases: doc]
  cdk doctor                      Check your set-up for potential problems

  -a, --app                REQUIRED: command-line for executing your app or a
                           cloud assembly directory (e.g. "node bin/my-app.js")
      --build              Command-line for a pre-synth build           [string]
  -c, --context            Add contextual string parameter (KEY=VALUE)   [array]
  -p, --plugin             Name or path of a node package that extend the CDK
                           features. Can be specified multiple times     [array]
      --trace              Print trace for stack warnings              [boolean]
      --strict             Do not construct stacks with warnings       [boolean]
      --lookups            Perform context lookups (synthesis fails if this is
                           disabled and context lookups need to be performed)
                                                       [boolean] [default: true]
      --ignore-errors      Ignores synthesis errors, which will likely produce
                           an invalid output          [boolean] [default: false]
  -j, --json               Use JSON output instead of YAML when templates are
                           printed to STDOUT          [boolean] [default: false]
  -v, --verbose            Show debug logs (specify multiple times to increase
                           verbosity)                   [count] [default: false]
      --debug              Enable emission of additional debugging information,
                           such as creation stack traces of tokens
                                                      [boolean] [default: false]
      --profile            Use the indicated AWS profile as the default
                           environment                                  [string]
      --proxy              Use the indicated proxy. Will read from HTTPS_PROXY
                           environment variable if not specified        [string]
      --ca-bundle-path     Path to CA certificate to use when validating HTTPS
                           requests. Will read from AWS_CA_BUNDLE environment
                           variable if not specified                    [string]
  -i, --ec2creds           Force trying to fetch EC2 instance credentials.
                           Default: guess EC2 instance status          [boolean]
      --version-reporting  Include the "AWS::CDK::Metadata" resource in
                           synthesized templates (enabled by default)  [boolean]
      --path-metadata      Include "aws:cdk:path" CloudFormation metadata for
                           each resource (enabled by default)
                                                       [boolean] [default: true]
      --asset-metadata     Include "aws:asset:*" CloudFormation metadata for
                           resources that uses assets (enabled by default)
                                                       [boolean] [default: true]
  -r, --role-arn           ARN of Role to use when invoking CloudFormation
      --staging            Copy assets to the output directory (use --no-staging
                           to disable, needed for local debugging the source
                           files with SAM CLI)         [boolean] [default: true]
  -o, --output             Emits the synthesized cloud assembly into a directory
                           (default: cdk.out)                           [string]
      --notices            Show relevant notices                       [boolean]
      --no-color           Removes colors and other style from console output
                                                      [boolean] [default: false]
      --version            Show version number                         [boolean]
  -h, --help               Show help                                   [boolean]

If your app has a single stack, there is no need to specify the stack name

If one of cdk.json or ~/.cdk.json exists, options specified there will be used
as defaults. Settings in cdk.json take precedence.

Read more about: How to host static website on AWS S3?

How to Create an AWS CDK project?

By using the cdk init command, you can create an AWS CDK project. Additionally, you can specify your desired programming language and template here. Let’s see the 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]

In this article, I’m going to start with a sample app. Additionally, this project contains some sample resources and demonstrates how a stack is created.

Read Also: AWS vs Google Cloud vs Microsoft Azure

First, go to your project folder and run the cdk init sample-app –language typescript command to create the CDK project as shown below:

➜ 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 above command automatically creates the sample project structure and necessary code documentation to run the sample app in CDK. Below is a sample of the form:

├── 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

In the above sample code, there is a root folder named lib. There is a stack under the root folder, which contains the code and resources. Since we’ve initialized AWS CDK, sample-app,it already creates an SQS queue and an SNS topic + subscription.

Build AWS CDK App

We have already generated an AWS CDK project with a stack cdk-project-stack.ts that contains a sample AWS SQS queue. Now we need to build the AWS CDK App.

Know more about: Cloud Security Managed Services.

Firstly, we need to build CloudFormations templates based on the code defined on the AWS CDK App. To do this and build an app, run cdk synth as shown below:

➜ cdk synth

    Type: AWS::SQS::Queue
      VisibilityTimeout: 300
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
      aws:cdk:path: CdkProjectStack/CdkProjectQueue/Resource
    Type: AWS::SQS::QueuePolicy
          - Action: sqs:SendMessage
                  Ref: CdkProjectTopicCABDBCE5
            Effect: Allow
              Service: sns.amazonaws.com
                - CdkProjectQueueD30BD26F
                - Arn
        Version: "2012-10-17"
        - Ref: CdkProjectQueueD30BD26F
      aws:cdk:path: CdkProjectStack/CdkProjectQueue/Policy/Resource
    Type: AWS::SNS::Subscription
      Protocol: sqs
        Ref: CdkProjectTopicCABDBCE5
          - CdkProjectQueueD30BD26F
          - Arn
      aws:cdk:path: CdkProjectStack/CdkProjectQueue/CdkProjectStackCdkProjectTopicEA58E728/Resource
    Type: AWS::SNS::Topic
      aws:cdk:path: CdkProjectStack/CdkProjectTopic/Resource
    Type: AWS::CDK::Metadata
      Analytics: v2:deflate64:H4sIAAAAAAAAE1WNQQ6CMBBFz8K+HZEYL8AFFNwbmNZkhpKiHE2AAA
      aws:cdk:path: CdkProjectStack/CDKMetadata/Default
    Condition: CDKMetadataAvailable
      - 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
    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.
      - Assert:
            - Fn::Contains:
                - - "1"
                  - "2"
                  - "3"
                - Ref: BootstrapVersion

This will show the CloudFormation template in YAML format in your terminal. However, the actual template is saved in the cdk.out folder in JSON format.

Also Read: AWS Certified Cloud Practitioner Study Guide

Deploy AWS CDK App

If you have AWS CLI installed on your system and set up an AWS profile, deploying the synthesized template on an AWS account is easy.

Explore more about: AWS S3 use cases and benefits.

First, we need to export our AWS account with export AWS_PROFILE=<your_aws_profile_name> the command. Then we need to deploy the synthesized application with the command cdk deploy as shown below:

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

By completing this process, we can successfully set up AWS CDK, initialize an AWS CDK project, synthesize a CloudFormation template, and then deploy it to your AWS account.

Read Also: Serverless security best practices.

Below, we learn how to destroy or remove the stack from the AWS account.

How to Destroy or Remove the Stack from AWS Account?

It is more effortless to destroy the stack from AWS than you think. You just need to run the single-line command cdk destroy, and the work is done.

Share this article on:

More Resources: