AWS Cloud Development Kit (AWS CDK)
Developer Guide

AWS CDK Tools

This section contains information about AWS CDK tools.

AWS CDK Command Line Interface (cdk)

The AWS CDK 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 the npx cdk instead of just cdk.

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]
  --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]
  --ci                  Force CI detection. Use --no-ci to disable CI
                        autodetection.                [boolean] [default: false]
  --tags, -t            tags to add to the stack (KEY=VALUE)             [array]
  --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 your app has a single stack, you don't have to specify the stack name.

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

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

The AWS CDK reports the name and version of npm modules that are loaded into the application at synthesis time, unless their package.json file contains the "private": true attribute.

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,lodash=4.17.10"

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 lambda = require('@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. Compile your AWS CDK app and create a AWS CloudFormation template

    npm run build 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"

On this page: