This is the AWS CDK v2 Developer Guide. The older CDK v1 entered maintenance on June 1, 2022 and ended support on June 1, 2023.
AWS CDK CLI reference
The AWS Cloud Development Kit (AWS CDK) Command Line Interface (AWS CDK CLI), also known as the CDK Toolkit, 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 about common use cases of the CDK CLI.
The CDK CLI 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, consider installing a matching version of the
CDK CLI in individual CDK projects. To do this, omit -g
from the npm install
command. Then use npx aws-cdk
to invoke it. This runs the local version if one exists, falling back to a
global version if not.
CDK CLI commands
All CDK CLI 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.
For a description of all subcommands, options, and arguments, see AWS CDK CLI command reference.
Specify options and their values
Command line options begin with two hyphens (--
). Some frequently used options have single-letter
synonyms that begin with a single hyphen (for example, --app
has a synonym -a
). The order of
options in an CDK CLI command is not important.
All options accept a value, which must follow the option name. The value may be separated from the name by white
space or by an equals sign =
. The following two options are equivalent.
--toolkit-stack-name MyBootstrapStack --toolkit-stack-name=MyBootstrapStack
Some options are flags (Booleans). You may specify true
or false
as their value. If you
do not provide a value, the value is taken to be true
. You may also prefix the option name with
no-
to imply false
.
# sets staging flag to true --staging --staging=true --staging true # sets staging flag to false --no-staging --staging=false --staging false
A few options, namely --context
, --parameters
, --plugin
,
--tags
, and --trust
, may be specified more than once to specify multiple values. These are
noted as having [array]
type in the CDK CLI help. For example:
cdk bootstrap --tags costCenter=0123 --tags responsibleParty=jdoe
Built-in help
The CDK CLI 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 CDK CLI. Provide this information when
requesting support.
Version reporting
To gain insight into how the AWS CDK is used, the constructs 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 by AWS to identify stacks using a construct with known security
or reliability issues. It can also be used to contact their users with important information.
Note
Before version 1.93.0, the AWS CDK reported the names and versions of the modules loaded during synthesis, instead of the constructs used in the stack.
By default, the AWS CDK reports the use of constructs in the following NPM modules that are used in the stack:
-
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: Analytics: "v2:deflate64:H4sIAND9SGAAAzXKSw5AMBAA0L1b2PdzBYnEAdio3RglglY60zQi7u6TWL/XKmNUlxeQSOKwaPTBqrNhwEWU3hGHiCzK0dWWfAxoL/Fd8mvk+QkS/0X6BdjnCdgmOOQKWz+AqqLDt2Y3YMnLYWwAAAA="
The Analytics
property is a gzipped, base64-encoded, prefix-encoded list of the constructs in the
stack.
Opt out of version reporting
You can opt out of version reporting by using the CDK CLI or by configuring your project's
cdk.json
file.
To opt out of version reporting using the CDK CLI
-
Use the
--no-version-reporting
option with any CDK CLI command to opt out for a single command. The following is an example of opting out during template synthesis:$
cdk synth --no-version-reporting
Since the AWS CDK synthesizes templates automatically when you run
cdk deploy
, you should also use--no-version-reporting
with thecdk deploy
command.
To opt out of version reporting by configuring the cdk.json
file
-
Set
versionReporting
tofalse
in./cdk.json
or~/.cdk.json
. This opts you out by default. The following is an example:{ "app": "...", "versionReporting": false }
After configuring, you can override this behavior and opt in by specifying
--version-reporting
on an individual command.
Note
When you opt out of version reporting, the AWS CDK will not collect or report data on which constructs you are using. Because of this, the AWS CDK will not be able to identify if you've been impacted by security issues and will not send you notifications for them.
Authentication with AWS
There are different ways in which you can configure programmatic access to AWS resources, depending on the environment and the AWS access available to you.
To choose your method of authentication and configure it for the CDK CLI, see Configure security credentials for the AWS CDK CLI.
The recommended approach for new users developing locally, who are not given a method of authentication by their employer, is to set up AWS IAM Identity Center. This method includes installing the AWS CLI for ease of configuration and for regularly signing in to the AWS access portal. If you choose this method, your environment should contain the following elements after you complete the procedure for IAM Identity Center authentication in the AWS SDKs and Tools Reference Guide:
-
The AWS CLI, which you use to start an AWS access portal session before you run your application.
-
A shared AWS
config
file having a[default]
profile with a set of configuration values that can be referenced from the AWS CDK. To find the location of this file, see Location of the shared files in the AWS SDKs and Tools Reference Guide. -
The shared
config
file sets theregion
setting. This sets the default AWS Region the AWS CDK and CDK CLI use for AWS requests. -
The CDK CLI uses the profile's SSO token provider configuration to acquire credentials before sending requests to AWS. The
sso_role_name
value, which is an IAM role connected to an IAM Identity Center permission set, should allow access to the AWS services used in your application.The following sample
config
file shows a default profile set up with SSO token provider configuration. The profile'ssso_session
setting refers to the namedsso-session
section. Thesso-session
section contains settings to initiate an AWS access portal session.[default] sso_session =
my-sso
sso_account_id =111122223333
sso_role_name =SampleRole
region =us-east-1
output = json [sso-sessionmy-sso
] sso_region =us-east-1
sso_start_url =https://provided-domain.awsapps.com/start
sso_registration_scopes = sso:account:access
Start an AWS access portal session
Before accessing AWS services, you need an active AWS access portal session for the CDK CLI to use IAM Identity Center authentication to resolve credentials. Depending on your configured session lengths, your access will eventually expire and the CDK CLI will encounter an authentication error. Run the following command in the AWS CLI to sign in to the AWS access portal.
aws sso login
If your SSO token provider configuration is using a named profile instead of the default profile, the command is
aws sso login --profile
. Also specify this profile when issuing
cdk commands using the --profile option or the NAME
AWS_PROFILE
environment variable.
To test if you already have an active session, run the following AWS CLI command.
aws sts get-caller-identity
The response to this command should report the IAM Identity Center account and permission set configured in the shared
config
file.
Note
If you already have an active AWS access portal session and run aws sso login
, you will not be
required to provide credentials.
The sign in process may prompt you to allow the AWS CLI access to your data. Since the AWS CLI is built on top of
the SDK for Python, permission messages may contain variations of the botocore
name.
Specify Region and other configuration
The CDK CLI needs to know the AWS Region that you're deploying into and how to authenticate with AWS. This is needed for deployment operations and to retrieve context values during synthesis. Together, your account and Region make up the environment.
Region may be specified using environment variables or in configuration files. These are the same variables and files used by other AWS tools such as the AWS CLI and the various AWS SDKs. The CDK CLI looks for this information in the following order.
-
The
AWS_DEFAULT_REGION
environment variable. -
A named profile defined in the standard AWS
config
file and specified using the--profile
option oncdk
commands. -
The
[default]
section of the standard AWSconfig
file.
Besides specifying AWS authentication and a Region in the [default]
section, you can also add one or
more [profile
sections, where NAME
]NAME
is the name
of the profile. For more information about named profiles, see Shared
config and credentials files in the AWS SDKs and Tools Reference Guide.
The standard AWS config
file is located at ~/.aws/config
(macOS/Linux)
or %USERPROFILE%\.aws\config
(Windows). For details and alternate locations, see Location of the shared config and credentials files in the
AWS SDKs and Tools Reference Guide
The environment that you specify in your AWS CDK app by using the stack's env
property is used during
synthesis. It's used to generate an environment-specific AWS CloudFormation template, and during deployment, it overrides the
account or Region specified by one of the preceding methods. For more information, see Environments for the AWS CDK.
Note
The AWS CDK uses credentials from the same source files as other AWS tools and SDKs, including the AWS Command Line Interface. However, the AWS CDK might behave somewhat differently from these tools. It uses the AWS SDK for JavaScript under the hood. For complete details on setting up credentials for the AWS SDK for JavaScript, see Setting credentials.
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.
Specify the app command
Many features of the CDK CLI require one or more AWS CloudFormation templates be synthesized, which in turn requires running your application. The AWS CDK supports programs written in a variety of languages. Therefore, 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
. This is in the main directory of your AWS CDK project. The CDK CLI 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 CLI looks for cdk.json
in the current working directory when attempting to run
your app. Because of this, you might keep a shell open in your project's main directory for issuing CDK CLI
commands.
The CDK CLI 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.
If you are in some other directory, or to run your app using a command other than the one in
cdk.json
, use the --app
(or -a
) option to specify it.
cdk --app "npx ts-node bin/hello-cdk.ts" ls
When deploying, you may also specify a directory containing synthesized cloud assemblies, such as
cdk.out
, as the value of --app. The specified stacks are deployed from this
directory; the app is not synthesized.
Specify stacks
Many CDK CLI commands (for example, cdk deploy
) work on stacks defined in your app. If your
app contains only one stack, the CDK CLI 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 (*
alone matches all stacks) -
**
matches everything in a hierarchy
You may also use the --all option to specify all stacks.
If your app uses CDK Pipelines, the CDK CLI understands your
stacks and stages as a hierarchy. Also, the --all option and the *
wildcard only match
top-level stacks. To match all the stacks, use **
. Also use **
to indicate all the stacks
under a particular hierarchy.
When using wildcards, enclose the pattern in quotes, or escape the wildcards with \
. 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. This isn't strictly necessary on Windows because
cmd.exe
does not expand wildcards, but is good practice nonetheless.
cdk synth "*Stack" # PipelineStack, LambdaStack, etc. cdk synth 'Stack?' # StackA, StackB, Stack1, etc. cdk synth \* # All stacks in the app, or all top-level stacks in a CDK Pipelines app cdk synth '**' # All stacks in a CDK Pipelines app cdk synth 'PipelineStack/Prod/**' # All stacks in Prod stage in a CDK Pipelines app
Note
The order in which you specify the stacks is not necessarily the order in which they will be processed. The
CDK CLI accounts for dependencies between stacks when deciding the order in which to process them. For
example, let's say that one stack uses a value produced by another (such as the ARN of a resource defined in the
second stack). In this case, the second stack is synthesized before the first one because of this dependency. You can
add dependencies between stacks manually using the stack's addDependency()
method.
Bootstrap your AWS environment
Deploying stacks with the CDK requires special dedicated AWS CDK resources to be provisioned. 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. See AWS CDK bootstrapping for details.
cdk bootstrap
If issued with no arguments, as shown here, the cdk bootstrap
command synthesizes the current app and
bootstraps the environments its stacks will be deployed to. If the app contains environment-agnostic stacks, which
don't explicitly specify an environment, the default account and Region are bootstrapped, or the environment specified
using --profile
.
Outside of an app, you must explicitly specify the environment to be bootstrapped. You may also do so to bootstrap
an environment that's not specified in your app or local AWS profile. 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 cdk 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 AWS charges for what the AWS CDK stores in the bootstrapped resources. Additionally, if you use
-bootstrap-customer-key
, an AWS KMS key will be created, which also incurs charges per
environment.
Note
Earlier versions of the bootstrap template created a KMS key by default. To avoid charges, re-bootstrap using
--no-bootstrap-customer-key
.
Note
CDK CLI v2 does not support the original bootstrap template, dubbed the legacy template, used by default with CDK v1.
Important
The modern bootstrap template effectively grants the permissions implied by
the --cloudformation-execution-policies
to any AWS account in the
--trust
list. By default, this extends permissions to read and
write to any resource in the bootstrapped account. Make sure to configure the bootstrapping stack with
policies and trusted accounts that you are comfortable with.
Create 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
--languageLANGUAGE
The supported languages (LANGUAGE
) are:
Code |
Language |
---|---|
|
TypeScript |
|
JavaScript |
|
Python |
|
Java |
|
C# |
TEMPLATE
is an optional template. If the desired template is app,
the default, you may omit it. The available templates are:
Template |
Description |
---|---|
|
Creates an empty AWS CDK 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.
List stacks
To see a list of the IDs of the stacks in your AWS CDK application, enter one of the following equivalent commands:
cdk list cdk ls
If your application contains CDK Pipelines stacks, the CDK CLI
displays stack names as paths according to their location in the pipeline hierarchy. (For example,
PipelineStack
, PipelineStack/Prod
, and
PipelineStack/Prod/MyService
.)
If your app contains many stacks, you can specify full or partial stack IDs of the stacks to be listed. For more information, see Specify stacks.
Add the --long
flag to see more information about the stacks, including the stack names and their
environments (AWS account and Region).
Synthesize 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 CLI actually runs your app and synthesizes fresh templates before most operations (such as 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 one or more specified stacks.
See cdk synth --help
for all available options. A few of the most frequently used options are covered
in the following section.
Specify 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 want, you can 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
Specify 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
Specify the output directory
Add the --output
(-o
) option to write the synthesized templates to a directory other
than cdk.out
.
cdk synth --output=~/templates
Deploy stacks
The cdk deploy
subcommand deploys one or more specified stacks 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 CLI 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 useful options are covered in the
following section.
Skip synthesis
The cdk deploy command normally synthesizes your app's stacks before deploying to make sure
that the deployment reflects the latest version of your app. If you know that you haven't changed your code since
your last cdk synth, you can suppress the redundant synthesis step when deploying. To do so,
specify your project's cdk.out
directory in the --app option.
cdk deploy --app cdk.out StackOne StackTwo
Disable rollback
AWS CloudFormation has the ability to roll back changes so that deployments are atomic. This means that they either succeed or fail as a whole. The AWS CDK inherits this capability because it synthesizes and deploys AWS CloudFormation templates.
Rollback makes sure that your resources are in a consistent state at all times, which is vital for production stacks. However, while you're still developing your infrastructure, some failures are inevitable, and rolling back failed deployments can slow you down.
For this reason, the CDK CLI lets you disable rollback by adding --no-rollback
to your
cdk deploy
command. With this flag, failed deployments are not rolled back. Instead, resources
deployed before the failed resource remain in place, and the next deployment starts with the failed resource. You'll
spend a lot less time waiting for deployments and a lot more time developing your infrastructure.
Hot swapping
Use the --hotswap
flag with cdk deploy
to attempt to update your AWS resources
directly instead of generating an AWS CloudFormation change set and deploying it. Deployment falls back to AWS CloudFormation deployment if hot
swapping is not possible.
Currently hot swapping supports Lambda functions, Step Functions state machines, and Amazon ECS container images. The
--hotswap
flag also disables rollback (i.e., implies --no-rollback
).
Important
Hot-swapping is not recommended for production deployments.
Watch mode
The CDK CLI's watch mode ( cdk deploy --watch, or cdk watch for short) continuously monitors your CDK app's source files and assets for changes. It immediately performs a deployment of the specified stacks when a change is detected.
By default, these deployments use the --hotswap
flag, which fast-tracks deployment of changes to
Lambda functions. It also falls back to deploying through AWS CloudFormation if you have changed infrastructure configuration. To
have cdk watch
always perform full AWS CloudFormation deployments, add the --no-hotswap
flag to
cdk watch
.
Any changes made while cdk watch
is already performing a deployment are combined into a single
deployment, which begins as soon as the in-progress deployment is complete.
Watch mode uses the "watch"
key in the project's cdk.json
to determine which
files to monitor. By default, these files are your application files and assets, but this can be changed by modifying
the "include"
and "exclude"
entries in the "watch"
key. The following
cdk.json
file shows an example of these entries.
{ "app": "mvn -e -q compile exec:java", "watch": { "include": "src/main/**", "exclude": "target/*" } }
cdk watch
executes the "build"
command from cdk.json
to build your
app before synthesis. If your deployment requires any commands to build or package your Lambda code (or anything else
that's not in your CDK app), add it here.
Git-style wildcards, both *
and **
, can be used in the "watch"
and
"build"
keys. Each path is interpreted relative to the parent directory of
cdk.json
. The default value of include
is **/*
, meaning all files
and directories in the project root directory. exclude
is optional.
Important
Watch mode is not recommended for production deployments.
Specify AWS CloudFormation parameters
The CDK CLI 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. To do so, prefix 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.
Specify 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 --outputs-file
flag.
cdk deploy --outputs-file outputs.json MyStack
Approve security-related changes
To protect you against unintended changes that affect your security posture, the CDK CLI prompts you to approve security-related changes before deploying them. You can specify the level of change that requires approval:
cdk deploy --require-approval
LEVEL
LEVEL
can be one of the following:
Term |
Meaning |
---|---|
|
Approval is never required |
|
Requires approval on any IAM or security-group-related change |
|
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" }
Compare stacks
The cdk diff
command compares the current version of a stack (and its dependencies) defined in your
app with the already-deployed versions, or with a saved AWS CloudFormation template, and displays a list of changes.
Stack HelloCdkStack IAM Statement Changes ┌───┬──────────────────────────────┬────────┬──────────────────────────────┬──────────────────────────────┬───────────┐ │ │ Resource │ Effect │ Action │ Principal │ Condition │ ├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ │ + │ ${Custom::S3AutoDeleteObject │ Allow │ sts:AssumeRole │ Service:lambda.amazonaws.com │ │ │ │ sCustomResourceProvider/Role │ │ │ │ │ │ │ .Arn} │ │ │ │ │ ├───┼──────────────────────────────┼────────┼──────────────────────────────┼──────────────────────────────┼───────────┤ │ + │ ${MyFirstBucket.Arn} │ Allow │ s3:DeleteObject* │ AWS:${Custom::S3AutoDeleteOb │ │ │ │ ${MyFirstBucket.Arn}/* │ │ s3:GetBucket* │ jectsCustomResourceProvider/ │ │ │ │ │ │ s3:GetObject* │ Role.Arn} │ │ │ │ │ │ s3:List* │ │ │ └───┴──────────────────────────────┴────────┴──────────────────────────────┴──────────────────────────────┴───────────┘ IAM Policy Changes ┌───┬────────────────────────────────────────────────────────┬────────────────────────────────────────────────────────┐ │ │ Resource │ Managed Policy ARN │ ├───┼────────────────────────────────────────────────────────┼────────────────────────────────────────────────────────┤ │ + │ ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Ro │ {"Fn::Sub":"arn:${AWS::Partition}:iam::aws:policy/serv │ │ │ le} │ ice-role/AWSLambdaBasicExecutionRole"} │ └───┴────────────────────────────────────────────────────────┴────────────────────────────────────────────────────────┘ (NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299) Parameters [+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3Bucket AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3BucketBF7A7F3F: {"Type":"String","Description":"S3 bucket for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} [+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/S3VersionKey AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392S3VersionKeyFAF93626: {"Type":"String","Description":"S3 key for asset version \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} [+] Parameter AssetParameters/4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392/ArtifactHash AssetParameters4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392ArtifactHashE56CD69A: {"Type":"String","Description":"Artifact hash for asset \"4cd61014b71160e8c66fe167e43710d5ba068b80b134e9bd84508cf9238b2392\""} Resources [+] AWS::S3::BucketPolicy MyFirstBucket/Policy MyFirstBucketPolicy3243DEFD [+] Custom::S3AutoDeleteObjects MyFirstBucket/AutoDeleteObjectsCustomResource MyFirstBucketAutoDeleteObjectsCustomResourceC52FCF6E [+] AWS::IAM::Role Custom::S3AutoDeleteObjectsCustomResourceProvider/Role CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092 [+] AWS::Lambda::Function Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F [~] AWS::S3::Bucket MyFirstBucket MyFirstBucketB8884501 ├─ [~] DeletionPolicy │ ├─ [-] Retain │ └─ [+] Delete └─ [~] UpdateReplacePolicy ├─ [-] Retain └─ [+] Delete
To compare your app's stacks with the existing deployment:
cdk diff MyStack
To compare your app's stacks with a saved CloudFormation template:
cdk diff --template ~/stacks/MyStack.old MyStack
Import existing resources into a stack
You can use the cdk import
command to bring resources under the management of CloudFormation for a
particular AWS CDK stack. This is useful if you are migrating to AWS CDK, or are moving resources between stacks or
changing their logical id. cdk import
uses CloudFormation resource imports. See the list of resources that can be imported here.
To import an existing resource into a AWS CDK stack, follow the following steps:
-
Make sure the resource is not currently being managed by any other CloudFormation stack. If it is, first set the removal policy to
RemovalPolicy.RETAIN
in the stack the resource is currently in and perform a deployment. Then, remove the resource from the stack and perform another deployment. This process will make sure that the resource is no longer managed by CloudFormation but does not delete it. -
Run a
cdk diff
to make sure there are no pending changes to the AWS CDK stack you want to import resources into. The only changes allowed in an "import" operation are the addition of new resources which you want to import. -
Add constructs for the resources you want to import to your stack. For example, if you want to import an Amazon S3 bucket, add something like
new s3.Bucket(this, 'ImportedS3Bucket', {});
. Do not make any modifications to any other resource.You must also make sure to exactly model the state that the resource currently has into the definition. For the example of the bucket, be sure to include AWS KMS keys, life cycle policies, and anything else that's relevant about the bucket. If you do not, subsequent update operations may not do what you expect.
You can choose whether or not to include the physical bucket name. We usually recommend to not include resource names into your AWS CDK resource definitions so that it becomes easier to deploy your resources multiple times.
-
Run
cdk import
.STACKNAME
-
If the resource names are not in your model, the CLI will prompt you to pass in the actual names of the resources you are importing. After this, the import starts.
-
When
cdk import
reports success, the resource is now managed by AWS CDK and CloudFormation. Any subsequent changes you make to the resource properties in your AWS CDK app the construct configuration will be applied on the next deployment. -
To confirm that the resource definition in your AWS CDK app matches the current state of the resource, you can start an CloudFormation drift detection operation.
This feature currently does not support importing resources into nested stacks.
Configuration (cdk.json
)
Default values for many CDK CLI command line flags can be stored in a project's
cdk.json
file or in the .cdk.json
file in your user directory. Following is
an alphabetical reference to the supported configuration settings.
Key | Notes | CDK CLI option |
---|---|---|
app |
The command that executes the CDK application. | --app |
assetMetadata |
If false , CDK does not add metadata to resources that use assets. |
--no-asset-metadata |
bootstrapKmsKeyId |
Overrides the ID of the AWS KMS key used to encrypt the Amazon S3 deployment bucket. | --bootstrap-kms-key-id |
build |
The command that compiles or builds the CDK application before synthesis. Not permitted in
~/.cdk.json . |
--build |
browser |
The command for launching a Web browser for the cdk docs subcommand. |
--browser |
context |
See Context values and the AWS CDK. Context values in a configuration file will not be erased by cdk
context --clear. (The CDK CLI places cached context values in
cdk.context.json .) |
--context |
debug |
If true , CDK CLI emits more detailed information useful for debugging. |
--debug |
language |
The language to be used for initializing new projects. | --language |
lookups |
If false , no context lookups are permitted. Synthesis will fail if any context lookups need
to be performed. |
--no-lookups |
notices |
If false , suppresses the display of messages about security vulnerabilities, regressions, and
unsupported versions. |
--no-notices |
output |
The name of the directory into which the synthesized cloud assembly will be emitted (default
"cdk.out" ). |
--output |
outputsFile |
The file to which AWS CloudFormation outputs from deployed stacks will be written (in JSON format). | --outputs-file |
pathMetadata |
If false , CDK path metadata is not added to synthesized templates. |
--no-path-metadata |
plugin |
JSON array specifying the package names or local paths of packages that extend the CDK | --plugin |
profile |
Name of the default AWS profile used for specifying Region and account credentials. | --profile |
progress |
If set to "events" , the CDK CLI displays all AWS CloudFormation events during deployment, rather
than a progress bar. |
--progress |
requireApproval |
Default approval level for security changes. See Approve security-related changes | --require-approval |
rollback |
If false , failed deployments are not rolled back. |
--no-rollback |
staging |
If false , assets are not copied to the output directory (use for local debugging of the
source files with AWS SAM). |
--no-staging |
tags |
JSON object containing tags (key-value pairs) for the stack. | --tags |
toolkitBucketName |
The name of the Amazon S3 bucket used for deploying assets such as Lambda functions and container images (see Bootstrap your AWS environment. | --toolkit-bucket-name |
toolkitStackName |
The name of the bootstrap stack (see Bootstrap your AWS environment. | --toolkit-stack-name |
versionReporting |
If false , opts out of version reporting. |
--no-version-reporting |
watch |
JSON object containing "include" and "exclude" keys that indicate which files
should (or should not) trigger a rebuild of the project when changed. See Watch mode. |
--watch |