AWS CDK tools - AWS Cloud Development Kit (AWS CDK)

AWS CDK tools

This section contains information about AWS CDK tools.

AWS Toolkit for Visual Studio code

The AWS Toolkit for Visual Studio Code is an open source plug-in for Visual Studio Code that makes it easier to create, debug, and deploy applications on AWS. The toolkit provides an integrated experience for developing AWS CDK applications, including the AWS CDK Explorer feature to list your AWS CDK projects and browse the various components of the CDK application. Install the AWS Toolkit and learn more about using the AWS CDK Explorer.

AWS CDK Toolkit (cdk)

The AWS CDK Toolkit, the CLI cdk, is the main tool you use to interact with your AWS CDK app. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK.

There are two ways to tell cdk what command to use to run your AWS CDK app. The first way is to include an explicit --app option whenever you use a cdk command.

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

The second way is to add the following entry to the cdk.json file (if you use the cdk init command, the command does this for you).

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

You can also use npx cdk instead of just cdk. npx cdk looks for a locally-installed copy of the AWS CDK CLI in the current project before falling back to a global installation.

Here are the actions you can take on your AWS CDK app (this is the output of the cdk --help command).

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

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

If a cdk.json or ~/.cdk.json file exists, options specified there are used as defaults. Settings in cdk.json take precedence.

AWS CDK toolkit commands

The AWS CDK CLI supports several distinct commands. Help for each (including only the command-line options specific to the particular command) follows. Commands with no command-specific options are not listed. All commands additionally accept the options listed above.

cdk list (ls)

cdk list [STACKS..]

Lists all stacks in the app

Options:

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

cdk synthesize (synth)

cdk synthesize [STACKS..]

Synthesizes and prints the CloudFormation template for this stack

Options:

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

If your app has a single stack, you don't have to specify the stack name.

cdk bootstrap

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]

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

cdk deploy

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]

If your app has a single stack, you don't have to specify the stack name.

cdk destroy

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]

If your app has a single stack, you don't have to specify the stack name.

cdk init

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

cdk context

Manage cached context values

Options:

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

  --clear               Clear all context                              [boolean]

Bootstrapping your AWS environment

Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app. Currently the bootstrap command creates only an Amazon S3 bucket.

You incur any 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. You can get rid of the bucket by deleting the CDKToolkit stack from your AWS account.

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 change the level of changes that requires approval by specifying:

cdk deploy --require-approval LEVEL

Where LEVEL can be one of the following:

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" }

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

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

CDKMetadata:
  Type: "AWS::CDK::Metadata"
  Properties:
    Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-consturcts/aws-apigateway-lambda=0.8.0"

Opting out from version reporting

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

  • Use the cdk command with the --no-version-reporting argument.

    cdk --no-version-reporting synth
  • Set versionReporting to false in ./cdk.json or ~/.cdk.json.

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

SAM CLI

This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda function locally. For further information, see Invoking Functions Locally. To install the SAM CLI, see Installing the AWS SAM CLI.

  1. The first step is to create a AWS CDK application and add the Lambda package.

    mkdir cdk-sam-example cd cdk-sam-example cdk init app --language typescript npm install @aws-cdk/aws-lambda
  2. Add a Lambda reference to lib/cdk-sam-example-stack.ts:

    import * as lambda from '@aws-cdk/aws-lambda';
  3. Replace the comment in lib/cdk-sam-example-stack.ts with the following Lambda function:

    new lambda.Function(this, 'MyFunction', { runtime: lambda.Runtime.PYTHON_3_7, handler: 'app.lambda_handler', code: lambda.Code.asset('./my_function'), });
  4. Create the directory my_function

    mkdir my_function
  5. Create the file app.py in my_function with the following content:

    def lambda_handler(event, context): return "This is a Lambda Function defined through CDK"
  6. Run your AWS CDK app and create a AWS CloudFormation template

    cdk synth --no-staging > template.yaml
  7. Find the logical ID for your Lambda function in template.yaml. It will look like MyFunction12345678, where 12345678 represents an 8-character unique ID that the AWS CDK generates for all resources. The line right after it should look like:

    Type: AWS::Lambda::Function
  8. Run the function by executing:

    sam local invoke MyFunction12345678 --no-event

    The output should look something like the following.

    2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) Fetching lambci/lambda:python3.7 Docker container image...... 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB "This is a Lambda Function defined through CDK"