AWS CDK Toolkit (cdk command) - AWS Cloud Development Kit (AWS CDK)

AWS CDK Toolkit (cdk command)

The AWS CDK Toolkit, the CLI command cdk, is the primary tool for interacting with your AWS CDK app. It executes your app, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK. It also provides other features useful for creating and working with AWS CDK projects. This topic contains information on common use cases of the CDK Toolkit.

The AWS CDK Toolkit is installed with the Node Package Manager. In most cases, we recommend installing it globally.

npm install -g aws-cdk # install latest version npm install -g aws-cdk@X.YY.Z # install specific version
Tip

If you regularly work with multiple versions of the AWS CDK, you may want to install a matching version of the AWS CDK Toolkit in individual CDK projects. To do this, omit -g from the npm install command. Then use npx cdk to invoke it; this will run the local version if one exists, falling back to a global version if not.

Toolkit commands

All CDK Toolkit commands start with cdk, which is followed by a subcommand (list, synthesize, deploy, etc.). Some subcommands have a shorter version (ls, synth, etc.) that is equivalent. Options and arguments follow the subcommand in any order. The available commands are summarized here.

Command

Function

cdk list (ls)

Lists the stacks in the app

cdk synthesize (synth)

Synthesizes and prints the CloudFormation template for the specified stack(s)

cdk bootstrap

Deploys the CDK Toolkit stack, required to deploy stacks containing assets

cdk deploy

Deploys the specified stack(s)

cdk destroy

Destroys the specified stack(s)

cdk diff

Compares the specified stack with the deployed stack or a local CloudFormation template

cdk metadata

Displays metadata about the specified stack

cdk init

Creates a new CDK project in the current directory from a specified template

cdk context

Manages cached context values

cdk docs (doc)

Opens the CDK API reference in your browser

cdk doctor

Checks your CDK project for potential problems

For the options available for each command, see Toolkit reference or Built-in help.

Built-in help

The AWS CDK Toolkit has integrated help. You can see general help about the utility and a list of the provided subcommands by issuing:

cdk --help

To see help for a particular subcommand, for example deploy, specify it before the --help flag.

cdk deploy --help

Issue cdk version to display the version of the AWS CDK Toolkit. Provide this information when requesting support.

Version reporting

To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as AWS::CDK::Metadata. This resource is added to AWS CloudFormation templates, and can easily be reviewed. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information.

By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time:

  • AWS CDK core module

  • AWS Construct Library modules

  • AWS Solutions Constructs module

  • AWS Render Farm Deployment Kit module

The AWS::CDK::Metadata resource looks something like the following.

CDKMetadata:
  Type: "AWS::CDK::Metadata"
  Properties:
    Modules: "@aws-cdk/core=X.YY.Z,@aws-cdk/s3=X.YY.Z,@aws-solutions-consturcts/aws-apigateway-lambda=X.YY.Z,aws-rfdk=X.YY.Z"

To opt out of version reporting, use one of the following methods:

  • Use the cdk command with the --no-version-reporting argument to opt out for a single command.

    cdk --no-version-reporting synth

    Remember, the AWS CDK Toolkit synthesizes fresh templates before deploying, so you should also add --no-version-reporting to cdk deploy commands.

  • Set versionReporting to false in ./cdk.json or ~/.cdk.json. This opts out unless you opt in by specifying --version-reporting on an individual command.

    { "app": "...", "versionReporting": false }

Specifying the environment

In AWS CDK terms, the environment consists of a region and AWS credentials valid in that region. The CDK Toolkit needs credentials in order to query your AWS account and to deploy CloudFormation templates.

Important

We strongly recommend against using your AWS root account for day-to-day tasks. Instead, create a user in IAM and use its credentials with the CDK.

If you have the AWS CLI installed, the easiest way to satisfy this requirement is to install the AWS CLI and issue the following command:

aws configure

Provide your AWS access key ID, secret access key, and default region when prompted.

You may also manually create or edit the ~/.aws/config and ~/.aws/credentials (Mac OS X or Linux) or %USERPROFILE%\.aws\config and %USERPROFILE%\.aws\credentials (Windows) files to contain credentials and a default region, in the following format.

  • In ~/.aws/config or %USERPROFILE%\.aws\config

    [default] region=us-west-2
  • In ~/.aws/credentials or %USERPROFILE%\.aws\credentials

    [default] aws_access_key_id=AKIAI44QH8DHBEXAMPLE aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY

Besides specifying AWS credentials and a region under the [default] section, you can also put them in a [profile NAME] section, where NAME is the name of the profile. You can add any number of named profiles, with or without a [default] section. Be sure to add the same profile sections to both the configuration and credentials files.

Tip

Don't name a profile default. That's just confusing.

Use the --profile flag to choose a set of credentials and default region from these configuration files for a given command.

cdk deploy --profile test PipelineStack

Instead of using the configuration files, you can set the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION to appropriate values.

You may optionally use the --role-arn (or -r) option to specify the ARN of an IAM role that should be used for deployment. This role must be assumable by the AWS account being used.

Specifying the app command

Many features of the CDK Toolkit require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application. Since the AWS CDK supports programs written in a variety of languages, it uses a configuration option to specify the exact command necessary to run your app. This option can be specified in two ways.

First, and most commonly, it can be specified using the app key inside the file cdk.json, which is in the main directory of your AWS CDK project. The CDK Toolkit provides an appropriate command when creating a new project with cdk init. Here is the cdk.json from a fresh TypeScript project, for instance.

{ "app": "npx ts-node bin/hello-cdk.ts" }

The CDK Toolkit looks for cdk.json in the current working directory when attempting to run your app, so you might keep a shell open in your project's main directory for issuing CDK Toolkit commands.

The CDK Toolkit also looks for the app key in ~/.cdk.json (that is, in your home directory) if it can't find it in ./cdk.json. Adding the app command here can be useful if you usually work with CDK code in the same language, as it does not require you to be in the app's main directory when you run a cdk command.

If you are in some other directory, or if you want to run your app via a command other than the one in cdk.json, you can use the --app (or -a) option to specify it.

cdk --app "npx ts-node bin/hello-cdk.ts" ls

Specifying stacks

Many CDK Toolkit commands (for example, cdk deploy) work on stacks defined in your app. If your app contains only one stack, the CDK Toolkit assumes you mean that one if you don't specify a stack explicitly.

Otherwise, you must specify the stack or stacks you want to work with. You can do this by specifying the desired stacks by ID individually on the command line. Recall that the ID is the value specified by the second argument when you instantiate the stack.

cdk synth PipelineStack LambdaStack

You may also use wildcards to specify IDs that match a pattern.

  • ? matches any single character

  • * matches any number of characters

When using wildcards, enclose the pattern in quotes. If you don't, your shell may try to expand the pattern to the names of files in the current directory. At best, this won't do what you expect; at worst, you could deploy stacks you didn't intend to.

cdk synth "*Stack" # PipelineStack, LambdaStack, etc. cdk synth "Stack?" # StackA, StackB, Stack1, etc. cdk synth "*" # All stacks in the app
Note

The CDK Toolkit does not guarantee that stacks are processed in the specified order. If for some reason the order of the stacks is important, use multiple cdk commands.

Bootstrapping your AWS environment

Stacks that contain assets or large AWS Lambda functions require special dedicated AWS CDK resources to be provisioned. Currently, this is only an Amazon S3 bucket. The cdk bootstrap command creates the necessary resources for you. You only need to bootstrap if you are deploying a stack that requires these dedicated resources.

cdk bootstrap # bootstraps default account/region cdk bootstrap --profile test # bootstraps test environment

You may also bootstrap a specific environment. Credentials must be configured (e.g. in ~/.aws/credentials) for the specified account and region. You may specify a profile that contains the required credentials.

cdk bootstrap ACCOUNT-NUMBER/REGION # e.g. cdk bootstrap 1111111111/us-east-1 aws bootstrap --profile test 1111111111/us-east-1
Important

Each environment (account/region combination) to which you deploy such a stack must be bootstrapped separately.

You may incur charges for what the AWS CDK stores in the bucket. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK. From time to time, then, you might want to clear out the bucket from the Amazon S3 console.

You can use the --bootstrap-bucket-name option of cdk bootstrap to specify the name of the bootstrap bucket, if the default (StagingBucket) is not suitable for some reason. You can use the --toolkit-stack-name option if the standard name of the stack itself (CDKToolkit) is not suitable.

Creating a new app

To create a new app, create a directory for it, then, inside the directory, issue cdk init.

mkdir my-cdk-app cd my-cdk-app cdk init TEMPLATE --language LANGUAGE

The supported languages (LANGUAGE) are:

Code

Language

typescript

TypeScript

javascript

JavaScript

python

Python

java

Java

csharp

C#

TEMPLATE is an optional template. If the desired template is app, the default, you may omit it. The available templates are:

Template

Description

app (default)

Creates an empty AWS CDK app.

sample-app

Creates an AWS CDK app with a stack containing an Amazon SQS queue and an Amazon SNS topic.

The templates use the name of the project folder to generate names for files and classes inside your new app.

Synthesizing stacks

The cdk synthesize command (almost always abbreviated synth) synthesizes a stack defined in your app into a CloudFormation template.

cdk synth # if app contains only one stack cdk synth MyStack cdk synth Stack1 Stack2 cdk synth "*" # all stacks in app
Note

The CDK Toolkit actually runs your app and synthesizes fresh templates before most operations (e.g. when deploying or comparing stacks). These templates are stored by default in the cdk.out directory. The cdk synth command simply prints the generated templates for the specified stack(s).

See cdk synth --help for all available options. A few of the most-frequently-used options are covered below.

Specifying context values

Use the --context or -c option to pass runtime context values to your CDK app.

# specify a single context value cdk synth –context key=value MyStack # specify multiple context values (any number) cdk synth --context key1=value1 --context key2=value2 MyStack

When deploying multiple stacks, the specified context values are normally passed to all of them. If you wish, you may specify different values for each stack by prefixing the stack name to the context value.

# different context values for each stack cdk synth --context Stack1:key=value Stack2:key=value Stack1 Stack2

Specifying display format

By default, the synthesized template is displayed in YAML format. Add the --json flag to display it in JSON format instead.

cdk synth –json MyStack

Specifying output directory

Add the --output (-o) option to write the synthesized templates to a directory other than cdk.out.

cdk synth –output=~/templates

Deploying stacks

The cdk deploy subcommand deploys the specified stack(s) to your AWS account.

cdk deploy # if app contains only one stack cdk deploy MyStack cdk deploy Stack1 Stack2 cdk deploy "*" # all stacks in app
Note

The CDK Toolkit runs your app and synthesizes fresh AWS CloudFormation templates before deploying anything. Therefore, most command line options you can use with cdk synth (for example, --context) can also be used with cdk deploy.

See cdk deploy --help for all available options. A few of the most-frequently-used options are covered below.

Specifying AWS CloudFormation parameters

The AWS CDK Toolkit supports specifying AWS CloudFormation parameters at deployment. You may provide these on the command line following the --parameters flag.

cdk deploy MyStack --parameters uploadBucketName=UploadBucket

To define multiple parameters, use multiple --parameters flags.

cdk deploy MyStack --parameters uploadBucketName=UpBucket --parameters downloadBucketName=DownBucket

If you are deploying multiple stacks, you can specify a different value of each parameter for each stack by prefixing the name of the parameter with the stack name and a colon. Otherwise, the same value is passed to all stacks.

cdk deploy MyStack YourStack --parameters MyStack:uploadBucketName=UploadBucket --parameters YourStack:uploadBucketName=UpBucket

By default, the AWS CDK retains values of parameters from previous deployments and uses them in later deployments if they are not specified explicitly. Use the --no-previous-parameters flag to require all parameters to be specified.

Specifying outputs file

If your stack declares AWS CloudFormation outputs, these are normally displayed on the screen at the conclusion of deployment. To write them to a file in JSON format, use the --output-file flag.

cdk deploy –output-file outputs.json MyStack

Security-related changes

To protect you against unintended changes that affect your security posture, the AWS CDK Toolkit prompts you to approve security-related changes before deploying them.

You can change the level of change that requires approval by specifying:

cdk deploy --require-approval LEVEL

LEVEL can be one of the following:

Term

Meaning

never

Approval is never required

any-change

Requires approval on any IAM or security-group-related change

broadening (default)

Requires approval when IAM statements or traffic rules are added; removals don't require approval

The setting can also be configured in the cdk.json file.

{ "app": "...", "requireApproval": "never" }

Comparing stacks

The cdk diff command compares the current version of a stack defined in your app with the already-deployed version, or with a saved AWS CloudFormation template, and displays a list of differences.

[~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501
 ├─ [~] DeletionPolicy
 │   ├─ [-] Retain
 │   └─ [+] Delete
 └─ [~] UpdateReplacePolicy
     ├─ [-] Retain
     └─ [+] Delete

To compare your app's stack(s) with the existing deployment:

cdk diff MyStack

To compare your app's stack(s) with a saved CloudFormation template:

cdk diff --template ~/stacks/MyStack.old MyStack

Toolkit reference

This section provides a reference for the AWS CDK Toolkit derived from its help, first a general reference with the options available with all commands, then (in collapsible sections) specific references with options available only with specific subcommands.

Usage: cdk -a <cdk-app> COMMAND

Commands:

  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
                                  environment

  cdk deploy [STACKS..]           Deploys the stack(s) named STACKS into your
                                  AWS account

  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
                                  stack

  cdk init [TEMPLATE]             Create a new, empty CDK project from a
                                  template. Invoked without TEMPLATE, the app
                                  template will be used.

  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

Options:

  --app, -a             REQUIRED: command-line for executing your app or a cloud
                        assembly directory (e.g. "node bin/my-app.js")  [string]

  --context, -c         Add contextual string parameter (KEY=VALUE)      [array]

  --plugin, -p          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]

  --ignore-errors       Ignores synthesis errors, which will likely produce an
                        invalid output                [boolean] [default: false]

  --json, -j            Use JSON output instead of YAML when templates are
                        printed to STDOUT             [boolean] [default: false]

  --verbose, -v         Show debug logs (specify multiple times to increase
                        verbosity)                      [count] [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]

  --ec2creds, -i        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 user assets (enabled by default)
                                                       [boolean] [default: true]

  --role-arn, -r        ARN of Role to use when invoking CloudFormation [string]

  --toolkit-stack-name  The name of the CDK toolkit stack               [string]

  --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]

  --output, -o          Emits the synthesized cloud assembly into a directory
                        (default: cdk.out)                              [string]

  --no-color            Removes colors and other style from console output
                                                      [boolean] [default: false]

  --fail                Fail with exit code 1 in case of diff
                                                      [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.
cdk list [STACKS..]

Lists all stacks in the app

Options:

  --long, -l            Display environment information for each stack
                                                      [boolean] [default: false]
cdk synthesize [STACKS..]

Synthesizes and prints the CloudFormation template for this stack

Options:

  --exclusively, -e     Only synthesize requested stacks, don't include
                        dependencies                                   [boolean]
cdk bootstrap [ENVIRONMENTS..]

Deploys the CDK toolkit stack into an AWS environment

Options:

  --bootstrap-bucket-name, -b,              The name of the CDK toolkit bucket;
  --toolkit-bucket-name                     bucket will be created and must not
                                            exist                       [string]

  --bootstrap-kms-key-id                    AWS KMS master key ID used for the
                                            SSE-KMS encryption          [string]

  --qualifier                               Unique string to distinguish
                                            multiple bootstrap stacks   [string]

  --public-access-block-configuration       Block public access configuration
                                            on CDK toolkit bucket (enabled by
                                            default)   [boolean] [default: true]

  --tags, -t                                Tags to add for the stack
                                            (KEY=VALUE)    [array] [default: []]

  --execute                                 Whether to execute ChangeSet
                                            (--no-execute will NOT execute the
                                            ChangeSet) [boolean] [default: true]

  --force, -f                               Always bootstrap even if it would
                                            downgrade template version
                                                      [boolean] [default: false]

  --termination-protection                  Toggle CloudFormation termination
                                            protection on the bootstrap stacks
                                                      [boolean] [default: false]
cdk deploy [STACKS..]

Deploys the stack(s) named STACKS into your AWS account

Options:

  --build-exclude, -E    Do not rebuild asset with the given ID. Can be
                         specified multiple times.         [array] [default: []]

  --exclusively, -e      Only deploy requested stacks, don't include
                         dependencies                                  [boolean]

  --require-approval     What security-sensitive changes need manual approval
                         [string] [choices: "never", "any-change", "broadening"]

  --ci                   Force CI detection (deprecated)
                                                      [boolean] [default: false]

  --notification-arns    ARNs of SNS topics that CloudFormation will notify with
                         stack related events                            [array]

  --tags, -t             Tags to add to the stack (KEY=VALUE)            [array]

  --execute              Whether to execute ChangeSet (--no-execute will NOT
                         execute the ChangeSet)        [boolean] [default: true]

  --force, -f            Always deploy stack even if templates are identical
                                                      [boolean] [default: false]

  --parameters           Additional parameters passed to CloudFormation at
                         deploy time (STACK:KEY=VALUE)     [array] [default: {}]

  --outputs-file, -O     Path to file where stack outputs will be written as
                         JSON                                           [string]

  --previous-parameters  Use previous values for existing parameters (you must
                         specify all parameters on every deployment if this is
                         disabled)                     [boolean] [default: true]
cdk destroy [STACKS..]

Destroy the stack(s) named STACKS

Options:

  --exclusively, -e     Only destroy requested stacks, don't include dependees
                                                                       [boolean]

  --force, -f           Do not ask for confirmation before destroying the stacks
                                                                       [boolean]
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

Options:

  --exclusively, -e     Only diff requested stacks, don't include dependencies
                                                                       [boolean]

  --context-lines       Number of context lines to include in arbitrary JSON
                        diff rendering                     [number] [default: 3]

  --template            The path to the CloudFormation template to compare with
                                                                        [string]
cdk init [TEMPLATE]

Create a new, empty CDK project from a template. Invoked without TEMPLATE, the
app template will be used.

Options:

  --language, -l        The language to be used for the new project (default can
                        be configured in ~/.cdk.json)
          [string] [choices: "csharp", "fsharp", "java", "javascript", "python",
                                                                   "typescript"]

  --list                List the available templates                   [boolean]

  --generate-only       If true, only generates project files, without executing
                        additional operations such as setting up a git repo,
                        installing dependencies or compiling the project
                                                      [boolean] [default: false]
cdk context

Manage cached context values

Options:

  --reset, -e           The context key (or its index) to reset         [string]

  --clear               Clear all context                              [boolean]

Help us help you

Did you find what you were looking for? We recently revamped this topic and are keenly interested in hearing about how it's working for you. Please click Provide feedback at the bottom of the page and let us know! Providing your e-mail address is optional, but very helpful if we have further questions. (We'll keep it to ourselves.)