# AWS CDK Toolkit CLI
<!--BEGIN STABILITY BANNER-->

---

![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)

---

<!--END STABILITY BANNER-->

The AWS CDK Toolkit provides the `cdk` command-line interface that can be used to work with AWS CDK applications. This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.

| Command                                     | Description                                                                       |
| ------------------------------------------- | --------------------------------------------------------------------------------- |
| [`cdk docs`](#cdk-docs)                     | Access the online documentation                                                   |
| [`cdk init`](#cdk-init)                     | Start a new CDK project (app or library)                                          |
| [`cdk list`](#cdk-list)                     | List stacks and their dependencies in an application                              |
| [`cdk synth`](#cdk-synth)                   | Synthesize a CDK app to CloudFormation template(s)                                |
| [`cdk diff`](#cdk-diff)                     | Diff stacks against current state                                                 |
| [`cdk deploy`](#cdk-deploy)                 | Deploy a stack into an AWS account                                                |
| [`cdk publish-assets`](#cdk-publish-assets) | Publish assets for stack(s) without deploying                                     |
| [`cdk rollback`](#cdk-rollback)             | Roll back a failed deployment                                                     |
| [`cdk import`](#cdk-import)                 | Import existing AWS resources into a CDK stack                                    |
| [`cdk migrate`](#cdk-migrate)               | Migrate AWS resources, CloudFormation stacks, and CloudFormation templates to CDK |
| [`cdk watch`](#cdk-watch)                   | Watches a CDK app for deployable and hotswappable changes                         |
| [`cdk destroy`](#cdk-destroy)               | Deletes a stack from an AWS account                                               |
| [`cdk bootstrap`](#cdk-bootstrap)           | Deploy a toolkit stack to support deploying large stacks & artifacts              |
| [`cdk gc`](#cdk-gc)                         | Garbage collect assets associated with the bootstrapped stack                     |
| [`cdk doctor`](#cdk-doctor)                 | Inspect the environment and produce information useful for troubleshooting        |
| [`cdk acknowledge`](#cdk-acknowledge)       | Acknowledge (and hide) a notice by issue number                                   |
| [`cdk notices`](#cdk-notices)               | List all relevant notices for the application                                     |
| [`cdk refactor`](#cdk-refactor)             | Moves resources between stacks or within the same stack                           |
| [`cdk drift`](#cdk-drift)                   | Detect drifts in the given CloudFormation stack(s)                                |
| [`cdk cli-telemetry`](#cdk-cli-telemetry)   | Enable or disable cli telemetry collection                                        |
| [`cdk flags`](#cdk-flags)                   | View and modify your feature flag configurations                                  |

## Common topics

- Usage
  - [Asset bundling](#bundling)
  - [Preview features](#unstable)
- Authentication
  - [MFA Support](#mfa-support)
  - [SSO Support](#sso-support)
- [Configuration](#configuration)
  - [Running in CI](#running-in-ci)

## Requirements

You need [Node.js](https://nodejs.org/en/download) or another JavaScript runtime to use the AWS CDK Toolkit CLI. We recommend using the [Node.js version in Active LTS](https://nodejs.org/en/about/previous-releases).
The minimal supported version is **Node.js v18**.
See our [Support Policy](https://docs.aws.amazon.com/cdk/v2/guide/node-versions.html) for full details.

## Commands

### `cdk docs`

Outputs the URL to the documentation for the current toolkit version, and attempts to open a browser to that URL.

```console
$ # Open the documentation in the default browser (using 'open')
$ cdk docs
https://docs.aws.amazon.com/cdk/api/latest/

$ # Open the documentation in Chrome.
$ cdk docs --browser='chrome %u'
https://docs.aws.amazon.com/cdk/api/latest/
```

### `cdk init`

Creates a new CDK project.

```console
$ # List the available template types & languages
$ cdk init --list
Available templates:
* app: Template for a CDK Application
   └─ cdk init app --language=[csharp|cs|fsharp|fs|java|javascript|js|python|py|typescript|ts]
* 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|cs|fsharp|fs|java|javascript|js|python|py|typescript|ts]

$ # Create a new library application in typescript
$ cdk init lib --language=typescript
```

### `cdk list`

Lists the stacks and their dependencies modeled in the CDK app.

```console
$ # List all stacks in the CDK app 'node bin/main.js'
$ cdk list --app='node bin/main.js'
Foo
Bar
Baz

$ # List all stack including all details (add --json to output JSON instead of YAML)
$ cdk list --app='node bin/main.js' --long
-
    name: Foo
    environment:
        name: 000000000000/bermuda-triangle-1
        account: '000000000000'
        region: bermuda-triangle-1
-
    name: Bar
    environment:
        name: 111111111111/bermuda-triangle-2
        account: '111111111111'
        region: bermuda-triangle-2
-
    name: Baz
    environment:
        name: 333333333333/bermuda-triangle-3
        account: '333333333333'
        region: bermuda-triangle-3
```

### `cdk synth`

Synthesizes the CDK app and produces a cloud assembly to a designated output (defaults to `cdk.out`)

Typically you don't interact directly with cloud assemblies. They are files that include everything
needed to deploy your app to a cloud environment. For example, it includes an AWS CloudFormation
template for each stack in your app, and a copy of any file assets or Docker images that you reference
in your app.

If your app contains a single stack or a stack is supplied as an argument to `cdk synth`, the CloudFormation template will also be displayed in the standard output (STDOUT) as `YAML`.

If there are multiple stacks in your application, `cdk synth` will synthesize the cloud assembly to `cdk.out`.

```console
$ # Synthesize cloud assembly for StackName and output the CloudFormation template to STDOUT
$ cdk synth MyStackName

$ # Synthesize cloud assembly for all the stacks and save them into cdk.out/
$ cdk synth

$ # Synthesize cloud assembly for StackName, but don't include dependencies
$ cdk synth MyStackName --exclusively

$ # Synthesize cloud assembly for StackName, but don't write CloudFormation template output to STDOUT
$ cdk synth MyStackName --quiet
```

The `quiet` option can be set in the `cdk.json` file.

```json
{
  "quiet": true
}
```

See the [AWS Documentation](https://docs.aws.amazon.com/cdk/latest/guide/apps.html#apps_cloud_assembly) to learn more about cloud assemblies.
See the [CDK reference documentation](https://docs.aws.amazon.com/cdk/api/latest/docs/cloud-assembly-schema-readme.html) for details on the cloud assembly specification


### `cdk diff`

Computes differences between the infrastructure specified in the current state of the CDK app and the currently
deployed application (or a user-specified CloudFormation template). If you need the command to return a non-zero if any differences are
found you need to use the `--fail` command line option.

```console
$ # Diff against the currently deployed stack
$ cdk diff --app='node bin/main.js' MyStackName

$ # Diff against a specific template document
$ cdk diff --app='node bin/main.js' MyStackName --template=path/to/template.yml
```

The `quiet` flag can also be passed to the `cdk diff` command. Assuming there are no differences detected the output to the console will **not** contain strings such as the *Stack* `MyStackName` and `There were no differences`.

```console
$ # Diff against the currently deployed stack with quiet parameter enabled
$ cdk diff --quiet --app='node bin/main.js' MyStackName
```

Note that the CDK::Metadata resource and the `CheckBootstrapVersion` Rule are excluded from `cdk diff` by default. You can force `cdk diff` to display them by passing the `--strict` flag.

The `--method` flag controls how the diff is created:

- `--method=auto` (default): Create a change set for accurate resource replacement info if possible, but fall back to a template-only diff if the change set cannot be created (e.g. due to missing permissions).
- `--method=change-set`: Always uses a change set and fails if it cannot be created. Use this when you need guaranteed accuracy. Uses the deploy role.
- `--method=template`: Compares templates directly using the lookup role. Faster, but has known inaccuracies. E.g. any change to a property that requires replacement will always be reported as a replacement, even if the change is purely cosmetic and might not actually be replaced.

The deprecated `--change-set` / `--no-change-set` flags map to `--method=auto` and `--method=template` respectively.

The `--import-existing-resources` option will make `diff` create a change set and compare it using
the CloudFormation resource import mechanism. This allows CDK to detect changes and show report of resources that
will be imported rather added. Use this flag when preparing to import existing resources into a CDK stack to
ensure and validate the changes are correctly reflected by showing 'import'.

```console
$ cdk diff
[+] AWS::DynamoDB::GlobalTable MyGlobalTable MyGlobalTable5DC12DB4

$ cdk diff --import-existing-resources
[←] AWS::DynamoDB::GlobalTable MyGlobalTable MyGlobalTable5DC12DB4 import
```

In the output above:
[+] indicates a new resource that would be created.
[←] indicates a resource that would be imported into the stack instead.

### `cdk deploy`

Deploys a stack of your CDK app to its environment. During the deployment, the toolkit will output progress
indications, similar to what can be observed in the AWS CloudFormation Console. If the environment was never
bootstrapped (using `cdk bootstrap`), only stacks that are not using assets and synthesize to a template that is under
51,200 bytes will successfully deploy.

```console
$ cdk deploy --app='node bin/main.js' MyStackName
```

Before creating a change set, `cdk deploy` will compare the template and tags of the
currently deployed stack to the template and tags that are about to be deployed and
will skip deployment if they are identical. Use `--force` to override this behavior
and always deploy the stack.

#### Disabling Rollback

If a resource fails to be created or updated, the deployment will *roll back* before the CLI returns. All changes made
up to that point will be undone (resources that were created will be deleted, updates that were made will be changed
back) in order to leave the stack in a consistent state at the end of the operation. If you are using the CDK CLI
to iterate on a development stack in your personal account, you might not require CloudFormation to leave your
stack in a consistent state, but instead would prefer to update your CDK application and try again.

To disable the rollback feature, specify `--no-rollback` (`-R` for short):

```console
$ cdk deploy --no-rollback
$ cdk deploy -R
```

If a deployment fails you can update your code and immediately retry the
deployment from the point of failure. If you would like to explicitly roll back
a failed, paused deployment, use `cdk rollback`.

`--no-rollback` deployments cannot contain resource replacements. If the CLI
detects that a resource is being replaced, it will prompt you to perform
a regular replacement instead. If the stack rollback is currently paused
and you are trying to perform an deployment that contains a replacement, you
will be prompted to roll back first.

#### Deploying multiple stacks

You can have multiple stacks in a cdk app. An example can be found in [how to create multiple stacks](https://docs.aws.amazon.com/cdk/latest/guide/stack_how_to_create_multiple_stacks.html).

In order to deploy them, you can list the stacks you want to deploy. If your application contains pipeline stacks, the `cdk list` command will show stack names as paths, showing where they are in the pipeline hierarchy (e.g., `PipelineStack`, `PipelineStack/Prod`, `PipelineStack/Prod/MyService` etc).

If you want to deploy all of them, you can use the flag `--all` or the wildcard `*` to deploy all stacks in an app. Please note that, if you have a hierarchy of stacks as described above, `--all` and `*` will only match the stacks on the top level. If you want to match all the stacks in the hierarchy, use `**`. You can also combine these patterns. For example, if you want to deploy all stacks in the `Prod` stage, you can use `cdk deploy PipelineStack/Prod/**`.

`--concurrency N` allows deploying multiple stacks in parallel while respecting inter-stack dependencies to speed up deployments. It does not protect against CloudFormation and other AWS account rate limiting.

#### Parameters

Pass parameters to your template during deployment by using `--parameters
(STACK:KEY=VALUE)`. This will apply the value `VALUE` to the key `KEY` for stack `STACK`.

Example of providing an attribute value for an SNS Topic through a parameter in TypeScript:

Usage of parameter in CDK Stack:

```ts
new sns.Topic(this, 'TopicParameter', {
    topicName: new cdk.CfnParameter(this, 'TopicNameParam').value.toString()
});
```

Parameter values as a part of `cdk deploy`

```console
$ cdk deploy --parameters "MyStackName:TopicNameParam=parameterized"
```

Parameter values can be overwritten by supplying the `--force` flag.
Example of overwriting the topic name from a previous deployment.

```console
$ cdk deploy --parameters "ParametersStack:TopicNameParam=blahagain" --force
```

⚠️ Parameters will be applied to all stacks if a stack name is not specified or `*` is provided.
Parameters provided to Stacks that do not make use of the parameter will not successfully deploy.

⚠️ Parameters do not propagate to NestedStacks. These must be sent with the constructor.
See Nested Stack [documentation](https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.NestedStack.html)

#### Outputs

Write stack outputs from deployments into a file. When your stack finishes deploying, all stack outputs
will be written to the output file as JSON.

Usage of output in a CDK stack

```ts
const fn = new lambda.Function(this, "fn", {
  handler: "index.handler",
  code: lambda.Code.fromInline(`exports.handler = \${handler.toString()}`),
  runtime: lambda.Runtime.NODEJS_LATEST
});

new cdk.CfnOutput(this, 'FunctionArn', {
  value: fn.functionArn,
});
```

Specify an outputs file to write to by supplying the `--outputs-file` parameter

```console
$ cdk deploy --outputs-file outputs.json
```

Alternatively, the `outputsFile` key can be specified in the project config (`cdk.json`).

The following shows a sample `cdk.json` where the `outputsFile` key is set to *outputs.json*.

```json
{
  "app": "npx ts-node bin/myproject.ts",
  "context": {
    "@aws-cdk/core:enableStackNameDuplicates": "true",
    "aws-cdk:enableDiffNoFail": "true",
    "@aws-cdk/core:stackRelativeExports": "true"
  },
  "outputsFile": "outputs.json"
}
```

The `outputsFile` key can also be specified as a user setting (`~/.cdk.json`)

When the stack finishes deployment, `outputs.json` would look like this:

```json
{
  "MyStack": {
    "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:MyStack-fn5FF616E3-G632ITHSP5HK"
  }
}
```

⚠️ The `key` of the outputs corresponds to the logical ID of the `CfnOutput`.
Read more about identifiers in the CDK [here](https://docs.aws.amazon.com/cdk/latest/guide/identifiers.html)

If multiple stacks are being deployed or the wild card `*` is used to deploy all stacks, all outputs
are written to the same output file where each stack artifact ID is a key in the JSON file


```console
$ cdk deploy '**' --outputs-file "/Users/code/myproject/outputs.json"
```

Example `outputs.json` after deployment of multiple stacks

```json
{
  "MyStack": {
    "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:MyStack-fn5FF616E3-G632ITHSP5HK"
  },
  "AnotherStack": {
    "VPCId": "vpc-z0mg270fee16693f"
  }
}
```

#### Deployment Progress

By default, stack deployment events are displayed as a progress bar with the events for the resource
currently being deployed.

Set the `--progress` flag to request the complete history which includes all CloudFormation events

```console
$ cdk deploy --progress events
```

Alternatively, the `progress` key can be specified in the project config (`cdk.json`).

The following shows a sample `cdk.json` where the `progress` key is set to *events*.
When `cdk deploy` is executed, deployment events will include the complete history.

```json
{
  "app": "npx ts-node bin/myproject.ts",
  "context": {
    "@aws-cdk/core:enableStackNameDuplicates": "true",
    "aws-cdk:enableDiffNoFail": "true",
    "@aws-cdk/core:stackRelativeExports": "true"
  },
  "progress": "events"
}
```

The `progress` key can also be specified as a user setting (`~/.cdk.json`)

#### CloudFormation Change Sets vs direct stack updates

By default, CDK creates a CloudFormation change set with the changes that will
be deployed and then executes it. This behavior can be controlled with the
`--method` parameter:

- `--method=change-set` (default): create and execute the change set.
- `--method=prepare-change-set`: create the change set but don't execute it.
  This is useful if you have external tools that will inspect the change set or
  you have an approval process for change sets.
- `--method=direct`: do not create a change set but apply the change immediately.
  This is typically a bit faster than creating a change set, but it loses
  the progress information.

To deploy faster without using change sets:

```console
$ cdk deploy --method=direct
```

If a change set is created, it will be called *cdk-deploy-change-set*, and a
previous change set with that name will be overwritten. The change set will
always be created, even if it is empty. A name can also be given to the change
set to make it easier to later execute:

```console
$ cdk deploy --method=prepare-change-set --change-set-name MyChangeSetName
```

For more control over when stack changes are deployed, the CDK can generate a
CloudFormation change set but not execute it.

#### Import existing resources

You can utilize the AWS CloudFormation
[feature](https://aws.amazon.com/about-aws/whats-new/2023/11/aws-cloudformation-import-parameter-changesets/)
that automatically imports resources in your template that already exist in your account.
To do so, pass the `--import-existing-resources` flag to the `deploy` command:

```console
$ cdk deploy --import-existing-resources
```

This automatically imports resources in your CDK application that represent
unmanaged resources in your account. It reduces the manual effort of import operations and
avoids deployment failures due to naming conflicts with unmanaged resources in your account.

Use the `--method=prepare-change-set` flag to review which resources are imported or not before deploying a change set.
You can inspect the change set created by CDK from the management console or other external tools.

```console
$ cdk deploy --import-existing-resources --method=prepare-change-set
```

Use the `--exclusively` flag to enable this feature for a specific stack.

```console
$ cdk deploy --import-existing-resources --exclusively StackName
```

Only resources that have custom names can be imported using `--import-existing-resources`.
For more information, see [name type](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-name.html). 
To import resources that do not accept custom names, such as EC2 instances,
use the `cdk import` instead. 
Visit [Bringing existing resources into CloudFormation management](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html)
for more details.

#### Ignore No Stacks

You may have an app with multiple environments, e.g., dev and prod. When starting
development, your prod app may not have any resources or the resources are commented
out. In this scenario, you will receive an error message stating that the app has no
stacks.

To bypass this error messages, you can pass the `--ignore-no-stacks` flag to the
`deploy` command:

```console
$ cdk deploy --ignore-no-stacks
```

#### Hotswap deployments for faster development

You can pass the `--hotswap` flag to the `deploy` command:

```console
$ cdk deploy --hotswap [StackNames]
```

This will attempt to perform a faster, short-circuit deployment if possible
(for example, if you changed the code of a Lambda function in your CDK app),
skipping CloudFormation, and updating the affected resources directly;
this includes changes to resources in nested stacks.
If the tool detects that the change does not support hotswapping,
it will ignore it and display that ignored change.
To have hotswap fall back and perform a full CloudFormation deployment,
exactly like `cdk deploy` does without the `--hotswap` flag,
specify `--hotswap-fallback`, like so:

```console
$ cdk deploy --hotswap-fallback [StackNames]
```

Passing either option to `cdk deploy` will make it use your current AWS credentials to perform the API calls -
it will not assume the Roles from your bootstrap stack,
even if the `@aws-cdk/core:newStyleStackSynthesis` feature flag is set to `true`
(as those Roles do not have the necessary permissions to update AWS resources directly, without using CloudFormation).
For that reason, make sure that your credentials are for the same AWS account that the Stack(s)
you are performing the hotswap deployment for belong to,
and that you have the necessary IAM permissions to update the resources that are being deployed.

Hotswapping is currently supported for the following changes
(additional changes will be supported in the future):

- Code asset (including Docker image and inline code), tag changes, and configuration changes (only
  description and environment variables are supported) of AWS Lambda functions.
- AWS Lambda Versions and Aliases changes.
- Definition changes of AWS Step Functions State Machines.
- Container asset changes of AWS ECS Services.
- Website asset changes of AWS S3 Bucket Deployments.
- Source and Environment changes of AWS CodeBuild Projects.
- VTL mapping template changes for AppSync Resolvers and Functions.
- Schema changes for AppSync GraphQL Apis.
- Code files (S3-based) and container image (ECR-based) changes, along with environment variable
  and description changes of Amazon Bedrock AgentCore Runtimes.
  - **Note**: For S3-based code changes to be detected, use `AgentRuntimeArtifact.fromCodeAsset()`:

    ```typescript
    // ✅ Recommended (hotswap works)
    const agentRuntimeArtifact = AgentRuntimeArtifact.fromCodeAsset({
      path: path.join(__dirname, 'agent-code'),
      runtime: AgentCoreRuntime.PYTHON_3_13,
      entrypoint: ['app.py'],
    });
    new Runtime(this, 'Runtime', {
      runtimeName: 'runtime',
      agentRuntimeArtifact,
    });
    ```

  - Do not use `AgentRuntimeArtifact.fromS3()` with `Source.asset()` and `BucketDeployment`, as the generated object key is a token resolved at deployment time and does not change in the CloudFormation template (hotswap will not work):

    ```typescript
    // ❌ Not recommended (hotswap doesn't work)
    const deployment = new aws_s3_deployment.BucketDeployment(this, 'Deploy', {
      sources: [aws_s3_deployment.Source.asset(path.join(__dirname, 'agent-code'))],
      destinationBucket: bucket,
      extract: false,
    });

    const agentRuntimeArtifact = AgentRuntimeArtifact.fromS3(
      {
        bucketName: bucket.bucketName,
        objectKey: cdk.Fn.select(0, deployment.objectKeys), // Token, resolved at deployment time
      },
      AgentCoreRuntime.PYTHON_3_13,
      ['app.py'],
    );
    ```

You can optionally configure the behavior of your hotswap deployments. Currently you can only configure ECS hotswap behavior:

| Property                    | Description                                                                                                                                                 | Default                            |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |
| minimumHealthyPercent       | Lower limit on the number of your service's tasks that must remain in the RUNNING state during a deployment, as a percentage of the desiredCount            | **REPLICA:** 100, **DAEMON:** 0    |
| maximumHealthyPercent       | Upper limit on the number of your service's tasks that are allowed in the RUNNING or PENDING state during a deployment, as a percentage of the desiredCount | **REPLICA:** 200, **DAEMON:**: N/A |
| stabilizationTimeoutSeconds | Number of seconds to wait for a single service to reach stable state, where the desiredCount is equal to the runningCount                                   | 600                                |

##### cdk.json

```json
{
"hotswap": {
    "ecs": {
      "minimumHealthyPercent": 100,
      "maximumHealthyPercent": 250,
      "stabilizationTimeoutSeconds": 300,
    }
  }
}
```

##### cli arguments

```console
cdk deploy --hotswap --hotswap-ecs-minimum-healthy-percent 100 --hotswap-ecs-maximum-healthy-percent 250 --hotswap-ecs-stabilization-timeout-seconds 300
```

**⚠ Note #1**: This command deliberately introduces drift in CloudFormation stacks in order to speed up deployments.
For this reason, only use it for development purposes.
**Never use this flag for your production deployments**!

**⚠ Note #2**: This command is considered experimental,
and might have breaking changes in the future.

**⚠ Note #3**: Expected defaults for certain parameters may be different with the hotswap parameter. For example, an ECS service's minimum healthy percentage will currently be set to 0. Please review the source accordingly if this occurs.

**⚠ Note #4**: Only usage of certain [CloudFormation intrinsic functions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html) are supported as part of a hotswapped deployment. At time of writing, these are:

- `Ref`
- `Fn::GetAtt` *
- `Fn::ImportValue`
- `Fn::Join`
- `Fn::Select`
- `Fn::Split`
- `Fn::Sub`

> *: `Fn::GetAtt` is only partially supported. Refer to [this implementation](https://github.com/aws/aws-cdk-cli/blob/main/packages/aws-cdk/lib/api/cloudformation/evaluate-cloudformation-template.ts#L256-L266) for supported resources and attributes.


##### Deploy flowchart

This flowchart provides a high-level overview of the deployment process.
For technical implementation details (function calls, file locations), see [docs/deploy-architecture.md](./docs/deploy-architecture.md).

![Deploy flowchart](./images/deploy-flowchart.png)

### `cdk publish-assets`

Publishes assets for the specified stack(s) without performing a deployment.

> [!CAUTION]
> `cdk publish-assets` is under development and therefore must be opted in via the
> `--unstable` flag: `cdk publish-assets --unstable=publish-assets`. `--unstable` indicates that the scope and
> API of feature might still change. Otherwise the feature is generally production
> ready and fully supported.

Publishes assets (such as Docker images and file assets) for the specified stack(s) to their respective destinations (ECR repositories, S3 buckets) without performing a deployment.

This is useful in CI/CD pipelines where you want to separate the asset build/publish phase from the deployment phase.

```console
$ # Publish assets for a single stack
$ cdk publish-assets MyStack --unstable=publish-assets

$ # Publish assets for all stacks
$ cdk publish-assets --all --unstable=publish-assets

$ # Force re-publish even if assets already exist
$ cdk publish-assets MyStack --unstable=publish-assets --force
```

### `cdk rollback`

If a deployment performed using `cdk deploy --no-rollback` fails, your
deployment will be left in a failed, paused state. From this state you can
update your code and try the deployment again, or roll the deployment back to
the last stable state.

To roll the deployment back, use `cdk rollback`. This will initiate a rollback
to the last stable state of your stack.

Some resources may fail to roll back. If they do, you can try again by calling
`cdk rollback --orphan <LogicalId>` (can be specified multiple times). Or, run
`cdk rollback --force` to have the CDK CLI automatically orphan all failing
resources.

(`cdk rollback` requires version 23 of the bootstrap stack, since it depends on
new permissions necessary to call the appropriate CloudFormation APIs)

### `cdk watch`

The `watch` command is similar to `deploy`,
but instead of being a one-shot operation,
the command continuously monitors the files of the project,
and triggers a deployment whenever it detects any changes:

```console
$ cdk watch DevelopmentStack
Detected change to 'lambda-code/index.js' (type: change). Triggering 'cdk deploy'
DevelopmentStack: deploying...

 ✅  DevelopmentStack

^C
```

To end a `cdk watch` session, interrupt the process by pressing Ctrl+C.

What files are observed is determined by the `"watch"` setting in your `cdk.json` file.
It has two sub-keys, `"include"` and `"exclude"`, each of which can be either a single string, or an array of strings.
Each entry is interpreted as a path relative to the location of the `cdk.json` file.
Globs, both `*` and `**`, are allowed to be used.
Example:

```json
{
  "app": "mvn -e -q compile exec:java",
  "watch": {
    "include": "src/main/**",
    "exclude": "target/*"
  }
}
```

The default for `"include"` is `"**/*"`
(which means all files and directories in the root of the project),
and `"exclude"` is optional
(note that we always ignore files and directories starting with `.`,
the CDK output directory, and the `node_modules` directory),
so the minimal settings to enable `watch` are `"watch": {}`.

If either your CDK code, or application code, needs a build step before being deployed,
`watch` works with the `"build"` key in the `cdk.json` file,
for example:

```json
{
  "app": "mvn -e -q exec:java",
  "build": "mvn package",
  "watch": {
    "include": "src/main/**",
    "exclude": "target/*"
  }
}
```

Note that `watch` by default uses hotswap deployments (see above for details) --
to turn them off, pass the `--no-hotswap` option when invoking it.

By default `watch` will also monitor all CloudWatch Log Groups in your application and stream the log events
locally to your terminal. To disable this feature you can pass the `--no-logs` option when invoking it:

```console
$ cdk watch --no-logs
```

You can increase the concurrency by which `watch` will deploy and hotswap
your stacks by specifying `--concurrency N`. `--concurrency` for `watch`
acts the same as `--concurrency` for `deploy`, in that it will deploy or
hotswap your stacks while respecting inter-stack dependencies.

```console
$ cdk watch --concurrency 5
```

**Note**: The same limitations apply to to `watch` deployments as do to `--hotswap` deployments.
It is not recommended to use `watch` for production deployments. See the
*Hotswap deployments for faster development* section for more information.

### `cdk import`

Sometimes you want to import AWS resources that were created using other means
into a CDK stack. For some resources (like Roles, Lambda Functions, Event Rules,
...), it's feasible to create new versions in CDK and then delete the old
versions. For other resources, this is not possible: stateful resources like S3
Buckets, DynamoDB tables, etc., cannot be easily deleted without impact on the
service.

`cdk import`, which uses [CloudFormation resource
imports](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html),
makes it possible to bring an existing resource under CDK/CloudFormation's
management. See the [list of resources that can be imported here](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-supported-resources.html).

To import an existing resource to a CDK stack, follow the following steps:

1. Run a `cdk diff` to make sure there are no pending changes to the 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.
2. Add constructs for the resources you want to import to your Stack (for example,
   for an S3 bucket, add something like `new s3.Bucket(this, 'ImportedS3Bucket', {});`).
   **Do not add any other changes!** You must also make sure to exactly model the state
   that the resource currently has. For the example of the Bucket, be sure to
   include 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.
3. Run the `cdk import` - if there are multiple stacks in the CDK app, pass a specific
   stack name as an argument.
4. The CLI will prompt you to pass in the actual names of the resources you are
   importing. After you supply it, the import starts.
5. When `cdk import` reports success, the resource is managed by CDK. Any subsequent
   changes in the construct configuration will be reflected on the resource.

NOTE: You can also import existing resources by passing `--import-existing-resources` to `cdk deploy`.
This parameter only works for resources that support custom physical names,
such as S3 Buckets, DynamoDB Tables, etc...
For more information, see [Request Parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateChangeSet.html#API_CreateChangeSet_RequestParameters).

#### Limitations

This feature currently has the following limitations:

- Importing resources into nested stacks is not possible.
- There is no check on whether the properties you specify are correct and complete
  for the imported resource. Try starting a drift detection operation after importing.
- Resources that depend on other resources must all be imported together, or one-by-one
  in the right order. If you do not, the CloudFormation deployment will fail
  with unresolved references.
- Uses the deploy role credentials (necessary to read the encrypted staging
  bucket). Requires version 12 of the bootstrap stack, for the added
  IAM permissions to the `deploy-role`.


### `cdk migrate`

⚠️**CAUTION**⚠️: CDK Migrate is currently experimental and may have breaking changes in the future.

CDK Migrate generates a CDK app from deployed AWS resources using `--from-scan`, deployed AWS CloudFormation stacks using `--from-stack`, and local AWS CloudFormation templates using `--from-path`.

To learn more about the CDK Migrate feature, see [Migrate to AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/migrate.html). For more information on `cdk migrate` command options, see [cdk migrate command reference](https://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cdk-migrate.html).

The new CDK app will be initialized in the current working directory and will include a single stack that is named with the value you provide using `--stack-name`. The new stack, app, and directory will all use this name. To specify a different output directory, use `--output-path`. You can create the new CDK app in any CDK supported programming language using `--language`.

#### Migrate from an AWS CloudFormation stack

Migrate from a deployed AWS CloudFormation stack in a specific AWS account and AWS Region using `--from-stack`. Provide `--stack-name` to identify the name of your stack. Account and Region information are retrieved from default CDK CLI sources. Use `--account` and `--region` options to provide other values. The following is an example that migrates **myCloudFormationStack** to a new CDK app using TypeScript:

```console
$ cdk migrate --language typescript --from-stack --stack-name 'myCloudFormationStack'
```

#### Migrate from a local AWS CloudFormation template

Migrate from a local `YAML` or `JSON` AWS CloudFormation template using `--from-path`. Provide a name for the stack that will be created in your new CDK app using `--stack-name`. Account and Region information are retrieved from default CDK CLI sources. Use `--account` and `--region` options to provide other values. The following is an example that creates a new CDK app using TypeScript that includes a **myCloudFormationStack** stack from a local `template.json` file:

```console
$ cdk migrate --language typescript --from-path "./template.json" --stack-name "myCloudFormationStack"
```

#### Migrate from deployed AWS resources

Migrate from deployed AWS resources in a specific AWS account and Region that are not associated with an AWS CloudFormation stack using `--from-scan`. These would be resources that were provisioned outside of an IaC tool. CDK Migrate utilizes the IaC generator service to scan for resources and generate a template. Then, the CDK CLI references the template to create a new CDK app. To learn more about IaC generator, see [Generating templates for existing resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html).

Account and Region information are retrieved from default CDK CLI sources. Use `--account` and `--region` options to provide other values. The following is an example that creates a new CDK app using TypeScript that includes a new **myCloudFormationStack** stack from deployed resources:

```console
$ cdk migrate --language typescript --from-scan --stack-name "myCloudFormationStack"
```

Since CDK Migrate relies on the IaC generator service, any limitations of IaC generator will apply to CDK Migrate. For general limitations, see [Considerations](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html#generate-template-considerations).

IaC generator limitations with discovering resource and property values will also apply here. As a result, CDK Migrate will only migrate resources supported by IaC generator. Some of your resources may not be supported and some property values may not be accessible. For more information, see [Iac generator and write-only properties](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC-write-only-properties.html) and [Supported resource types](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC-supported-resources.html).

You can specify filters using `--filter` to specify which resources to migrate. This is a good option to use if you are over the IaC generator total resource limit.

After migration, you must resolve any write-only properties that were detected by IaC generator from your deployed resources. To learn more, see [Resolve write-only properties](https://docs.aws.amazon.com/cdk/v2/guide/migrate.html#migrate-resources-writeonly).

#### Examples

##### Generate a TypeScript CDK app from a local AWS CloudFormation template.json file

```console
$ # template.json is a valid cloudformation template in the local directory
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-path MyTemplate.json
```

This command generates a new directory named `MyAwesomeApplication` within your current working directory, and
then initializes a new CDK application within that directory. The CDK app contains a `MyAwesomeApplication` stack with resources configured to match those in your local CloudFormation template.

This results in a CDK application with the following structure, where the lib directory contains a stack definition
with the same resource configuration as the provided template.json.

```console
├── README.md
├── bin
│   └── my_awesome_application.ts
├── cdk.json
├── jest.config.js
├── lib
│   └── my_awesome_application-stack.ts
├── package.json
├── tsconfig.json
```

##### Generate a Python CDK app from a deployed stack

If you already have a CloudFormation stack deployed in your account and would like to manage it with CDK, you can migrate the deployed stack to a new CDK app. The value provided with `--stack-name` must match the name of the deployed stack.

```console
$ # generate a Python application from MyDeployedStack in your account
$ cdk migrate --stack-name MyDeployedStack --language python --from-stack
```

This will generate a Python CDK app which will synthesize the same configuration of resources as the deployed stack.

##### Generate a TypeScript CDK app from deployed AWS resources that are not associated with a stack

If you have resources in your account that were provisioned outside AWS IaC tools and would like to manage them with the CDK, you can use the `--from-scan` option to generate the application.

In this example, we use the `--filter` option to specify which resources to migrate.  You can filter resources to limit the number of resources migrated to only those specified by the `--filter` option, including any resources they depend on, or resources that depend on them (for example A filter which specifies a single Lambda Function, will find that specific table and any alarms that may monitor it). The `--filter` argument offers both AND as well as OR filtering.

OR filtering can be specified by passing multiple `--filter` options, and AND filtering can be specified by passing a single `--filter` option with multiple comma separated key/value pairs as seen below (see below for examples). It is recommended to use the `--filter` option to limit the number of resources returned as some resource types provide sample resources by default in all accounts which can add to the resource limits.

`--from-scan` takes 3 potential arguments: `--new`, `most-recent`, and undefined. If `--new` is passed, CDK Migrate will initiate a new scan of the account and use that new scan to discover resources. If `--most-recent` is passed, CDK Migrate will use the most recent scan of the account to discover resources. If neither `--new` nor `--most-recent` are passed, CDK Migrate will take the most recent scan of the account to discover resources, unless there is no recent scan, in which case it will initiate a new scan.

```console
# Filtering options
identifier|id|resource-identifier=<resource-specific-resource-identifier-value>
type|resource-type-prefix=<resource-type-prefix>
tag-key=<tag-key>
tag-value=<tag-value>
```

##### Additional examples of migrating from deployed resources

```console
$ # Generate a typescript application from all un-managed resources in your account
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-scan

$ # Generate a typescript application from all un-managed resources in your account with the tag key "Environment" AND the tag value "Production"
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-scan --filter tag-key=Environment,tag-value=Production

$ # Generate a python application from any dynamoDB resources with the tag-key "dev" AND the tag-value "true" OR any SQS::Queue
$ cdk migrate --stack-name MyAwesomeApplication --language python --from-scan --filter type=AWS::DynamoDb::,tag-key=dev,tag-value=true --filter type=SQS::Queue

$ # Generate a typescript application from a specific lambda function by providing it's specific resource identifier
$ cdk migrate --stack-name MyAwesomeApplication --language typescript --from-scan --filter identifier=myAwesomeLambdaFunction
```

#### **CDK Migrate Limitations**

- CDK Migrate does not currently support nested stacks, custom resources, or the `Fn::ForEach` intrinsic function.

- CDK Migrate will only generate L1 constructs and does not currently support any higher level abstractions.

- CDK Migrate successfully generating an application does *not* guarantee the application is immediately deployable.
It simply generates a CDK application which will synthesize a template that has identical resource configurations
to the provided template.

  - CDK Migrate does not interact with the CloudFormation service to verify the template
provided can deploy on its own. Although by default any CDK app generated using the `--from-scan` option exclude
CloudFormation managed resources, CDK Migrate will not verify prior to deployment that any resources scanned, or in the provided
template are already managed in other CloudFormation templates, nor will it verify that the resources in the provided
template are available in the desired regions, which may impact ADC or Opt-In regions.

  - If the provided template has parameters without default values, those will need to be provided
before deploying the generated application.

In practice this is how CDK Migrate generated applications will operate in the following scenarios:

| Situation                                                                                         | Result                                                                                                                        |
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| Provided template + stack-name is from a deployed stack in the account/region                     | The CDK application will deploy as a change set to the existing stack                                                         |
| Provided template has no overlap with resources already in the account/region                     | The CDK application will deploy a new stack successfully                                                                      |
| Provided template has overlap with Cloudformation managed resources already in the account/region | The CDK application will not be deployable unless those resources are removed                                                 |
| Provided template has overlap with un-managed resources already in the account/region             | The CDK application will not be deployable until those resources are adopted with [`cdk import`](#cdk-import)                 |
| No template has been provided and resources exist in the region the scan is done                  | The CDK application will be immediatly deployable and will import those resources into a new cloudformation stack upon deploy |

##### **The provided template is already deployed to CloudFormation in the account/region**

If the provided template came directly from a deployed CloudFormation stack, and that stack has not experienced any drift,
then the generated application will be immediately deployable, and will not cause any changes to the deployed resources.
Drift might occur if a resource in your template was modified outside of CloudFormation, namely via the AWS Console or AWS CLI.

##### **The provided template is not deployed to CloudFormation in the account/region, and there *is not* overlap with existing resources in the account/region**

If the provided template represents a set of resources that have no overlap with resources already deployed in the account/region,
then the generated application will be immediately deployable. This could be because the stack has never been deployed, or
the application was generated from a stack deployed in another account/region.

In practice this means for any resource in the provided template, for example,

```Json
    "S3Bucket": {
      "Type": "AWS::S3::Bucket",
      "Properties": {
        "BucketName": "amzn-s3-demo-bucket",
        "AccessControl": "PublicRead",
      },
      "DeletionPolicy": "Retain"
    }
```

There must not exist a resource of that type with the same identifier in the desired region. In this example that identfier
would be "amzn-s3-demo-bucket"

##### **The provided template is not deployed to CloudFormation in the account/region, and there *is* overlap with existing resources in the account/region**

If the provided template represents a set of resources that overlap with resources already deployed in the account/region,
then the generated application will not be immediately deployable. If those overlapped resources are already managed by
another CloudFormation stack in that account/region, then those resources will need to be manually removed from the provided
template. Otherwise, if the overlapped resources are not managed by another CloudFormation stack, then first remove those
resources from your CDK Application Stack, deploy the cdk application successfully, then re-add them and run `cdk import`
to import them into your deployed stack.

### `cdk destroy`

Deletes a stack from it's environment. This will cause the resources in the stack to be destroyed (unless they were
configured with a `DeletionPolicy` of `Retain`). During the stack destruction, the command will output progress
information similar to what `cdk deploy` provides.

```console
$ cdk destroy --app='node bin/main.js' MyStackName
```

### `cdk bootstrap`

Deploys a `CDKToolkit` CloudFormation stack into the specified environment(s), that provides an S3 bucket
and ECR repository that `cdk deploy` will use to store synthesized templates and the related assets, before
triggering a CloudFormation stack update. The name of the deployed stack can be configured using the
`--toolkit-stack-name` argument. The S3 Bucket Public Access Block Configuration can be configured using
the `--public-access-block-configuration` argument. ECR uses immutable tags for images.

```console
$ # Deploys to all environments
$ cdk bootstrap --app='node bin/main.js'

$ # Deploys only to environments foo and bar
$ cdk bootstrap --app='node bin/main.js' foo bar
```

By default, bootstrap stack will be protected from stack termination. This can be disabled using
`--termination-protection` argument.

If you have specific prerequisites not met by the example template, you can
[customize it](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-customizing)
to fit your requirements, by exporting the provided one to a file and either deploying it yourself
using CloudFormation directly, or by telling the CLI to use a custom template. That looks as follows:

```console
# Dump the built-in template to a file
$ cdk bootstrap --show-template > bootstrap-template.yaml

# Edit 'bootstrap-template.yaml' to your liking

# Tell CDK to use the customized template
$ cdk bootstrap --template bootstrap-template.yaml
```

Out of the box customization options are also available as arguments. To use a permissions boundary:

- `--example-permissions-boundary` indicates the example permissions boundary, supplied by CDK
- `--custom-permissions-boundary` specifies, by name a predefined, customer maintained, boundary

A few notes to add at this point. The CDK supplied permissions boundary policy should be regarded as
an example. Edit the content and reference the example policy if you're testing out the feature, turn
it into a new policy for actual deployments (if one does not already exist). The concern here is drift
as, most likely, a permissions boundary is maintained and has dedicated conventions, naming included.

For more information on configuring permissions, including using permissions
boundaries see the [Security And Safety Dev Guide](https://github.com/aws/aws-cdk/wiki/Security-And-Safety-Dev-Guide)

Once a bootstrap template has been deployed with a set of parameters, you must
use the `--no-previous-parameters` CLI flag to change any of these parameters on
future deployments.

> **Note** Please note that when you use this flag, you must resupply
>*all* previously supplied parameters.

For example if you bootstrap with a custom permissions boundary

```console
cdk bootstrap --custom-permissions-boundary my-permissions-boundary
```

In order to remove that permissions boundary you have to specify the
`--no-previous-parameters` option.

```console
cdk bootstrap --no-previous-parameters
```

### `cdk gc`

CDK Garbage Collection.

> [!CAUTION]
> CDK Garbage Collection is under development and therefore must be opted in via the 
>`--unstable` flag: `cdk gc --unstable=gc`. `--unstable` indicates that the scope and 
> API of feature might still change. Otherwise the feature is generally production 
> ready and fully supported.

`cdk gc` garbage collects unused assets from your bootstrap bucket via the following mechanism:

- for each object in the bootstrap S3 Bucket, check to see if it is referenced in any existing CloudFormation templates
- if not, it is treated as unused and gc will either tag it or delete it, depending on your configuration.

The high-level mechanism works identically for unused assets in bootstrapped ECR Repositories.

The most basic usage looks like this:

```console
cdk gc --unstable=gc
```

This will garbage collect all unused assets in all environments of the existing CDK App.

To specify one type of asset, use the `type` option (options are `all`, `s3`, `ecr`):

```console
cdk gc --unstable=gc --type=s3
```

Otherwise `cdk gc` defaults to collecting assets in both the bootstrapped S3 Bucket and ECR Repository.

`cdk gc` will garbage collect S3 and ECR assets from the current bootstrapped environment(s) and immediately delete them. Note that, since the default bootstrap S3 Bucket is versioned, object deletion will be handled by the lifecycle
policy on the bucket.

Before we begin to delete your assets, you will be prompted:

```console
cdk gc --unstable=gc

Found X objects to delete based off of the following criteria:
- objects have been isolated for > 0 days
- objects were created > 1 days ago

Delete this batch (yes/no/delete-all)?
```

Since it's quite possible that the bootstrap bucket has many objects, we work in batches of 1000 objects or 100 images.
To skip the prompt either reply with `delete-all`, or use the `--confirm=false` option.

```console
cdk gc --unstable=gc --confirm=false
```

If you are concerned about deleting assets too aggressively, there are multiple levers you can configure:

- rollback-buffer-days: this is the amount of days an asset has to be marked as isolated before it is elligible for deletion.
- created-buffer-days: this is the amount of days an asset must live before it is elligible for deletion.

When using `rollback-buffer-days`, instead of deleting unused objects, `cdk gc` will tag them with
today's date instead. It will also check if any objects have been tagged by previous runs of `cdk gc`
and delete them if they have been tagged for longer than the buffer days.

When using `created-buffer-days`, we simply filter out any assets that have not persisted that number
of days.

```console
cdk gc --unstable=gc --rollback-buffer-days=30 --created-buffer-days=1
```

You can also configure the scope that `cdk gc` performs via the `--action` option. By default, all actions
are performed, but you can specify `print`, `tag`, or `delete-tagged`.

- `print` performs no changes to your AWS account, but finds and prints the number of unused assets.
- `tag` tags any newly unused assets, but does not delete any unused assets.
- `delete-tagged` deletes assets that have been tagged for longer than the buffer days, but does not tag newly unused assets.

```console
cdk gc --unstable=gc --action=delete-tagged --rollback-buffer-days=30
```

This will delete assets that have been unused for >30 days, but will not tag additional assets.

Here is a diagram that shows the algorithm of garbage collection:

![Diagram of Garbage Collection algorithm](images/garbage-collection.png)

#### Theoretical Race Condition with `REVIEW_IN_PROGRESS` stacks

When gathering stack templates, we are currently ignoring `REVIEW_IN_PROGRESS` stacks as no template
is available during the time the stack is in that state. However, stacks in `REVIEW_IN_PROGRESS` have already
passed through the asset uploading step, where it either uploads new assets or ensures that the asset exists.
Therefore it is possible the assets it references are marked as isolated and garbage collected before the stack
template is available.

Our recommendation is to not deploy stacks and run garbage collection at the same time. If that is unavoidable,
setting `--created-buffer-days` will help as garbage collection will avoid deleting assets that are recently
created. Finally, if you do result in a failed deployment, the mitigation is to redeploy, as the asset upload step
will be able to reupload the missing asset.

In practice, this race condition is only for a specific edge case and unlikely to happen but please open an
issue if you think that this has happened to your stack.

### `cdk doctor`

Inspect the current command-line environment and configurations, and collect information that can be useful for
troubleshooting problems. It is usually a good idea to include the information provided by this command when submitting
a bug report.

```console
$ cdk doctor
ℹ️ CDK Version: 1.0.0 (build e64993a)
ℹ️ AWS environment variables:
  - AWS_EC2_METADATA_DISABLED = 1
  - AWS_SDK_LOAD_CONFIG = 1
```

### `cdk refactor`

⚠️**CAUTION**⚠️: CDK Refactor is currently experimental and may have 
breaking changes in the future. Make sure to use the `--unstable=refactor` flag 
when using this command.

Compares the infrastructure specified in the current state of the CDK app with 
the currently deployed application, to determine if any resource was moved 
(to a different stack or to a different logical ID, or both). In keeping with
the CloudFormation API, you are not allowed to modify the set of resources
as part of a refactor. In other words, adding, deleting or updating resources
is considered an error.

The CLI will show the correspondence between the old and new locations in a table:

```
$ cdk refactor --unstable=refactor --dry-run

The following resources were moved or renamed:

┌───────────────────────────────┬───────────────────────────────┬───────────────────────────────────┐
│ Resource Type                 │ Old Construct Path            │ New Construct Path                │
├───────────────────────────────┼───────────────────────────────┼───────────────────────────────────┤
│ AWS::S3::Bucket               │ MyStack/Bucket/Resource       │ Web/Website/Origin/Resource       │
├───────────────────────────────┼───────────────────────────────┼───────────────────────────────────┤
│ AWS::CloudFront::Distribution │ MyStack/Distribution/Resource │ Web/Website/Distribution/Resource │
├───────────────────────────────┼───────────────────────────────┼───────────────────────────────────┤
│ AWS::Lambda::Function         │ MyStack/Function/Resource     │ Service/Function/Resource         │
└───────────────────────────────┴───────────────────────────────┴───────────────────────────────────┘
```

Note the use of the `--dry-run` flag. When this flag is used, the CLI will 
show this table and exit. Eventually, the CLI will also be able to automatically  
apply the refactor on your CloudFormation stacks. But for now, only the dry-run 
mode is supported.

If your application has more than one stack, and you want the `refactor`
command to consider only a subset of them, you can specify the stacks you
want, both local and deployed:

```shell
$ cdk refactor Test* ProdStack --unstable=refactor --dry-run 
```

This is useful if, for example, you have more than one CDK application deployed
to a given environment, and you want to only include the deployed stacks that
belong to the application that you are refactoring.

The pattern language is the same as the one used in the `cdk deploy` command.
However, unlike `cdk deploy`, in the absence of this parameter, all stacks are
considered.

The CLI's default behavior is to include in the comparison only the deployed
stacks that have a counterpart (stack with the same name) locally. If you want
to include additional deployed stacks in the comparison, pass their names using
the `--additional-stack-name` option:

```shell
$ cdk refactor --unstable=refactor --dry-run --additional-stack-name=Foo --additional-stack-name=Bar
```

In case of ambiguities, the CLI will display a table like this:

```
Detected ambiguities:
┌───┬──────────────────────┐
│   │ Resource             │
├───┼──────────────────────┤
│ - │ Stack2/DLQ/Resource  │
│   │ Stack2/DLQ2/Resource │
├───┼──────────────────────┤
│ + │ Stack1/DLQ/Resource  │
│   │ Stack1/DLQ2/Resource │
└───┴──────────────────────┘
```

You can resolve this ambiguity manually, by passing an override file via the
`--override-file=<path>` CLI option. This file should contain a JSON object 
with the following structure: 

```json
{
  "mappings": [
    {
      "account": "123456789012",
      "region": "us-east-1",
      "resources": {
        "Stack2.OldName": "Stack2.NewName"
      }
    }
  ]
}
```

where `resources` is a mapping of resources from source to destination
locations for a given environment. Resource locations are in the format
`StackName.LogicalId`.The source must refer to a location where there is a
resource currently deployed, while the destination must refer to a location
that is not already occupied by any resource.

#### How resources are compared

To determine if a resource was moved or renamed, the CLI computes a digest
for each resource, both in the deployed stacks and in the local stacks, and
then compares the digests. 

Conceptually, the digest is computed as:

```
digest(resource) = hash(type + properties + dependencies.map(d))
```

where hash is a cryptographic hash function. In other words, the digest of a 
resource is computed from its type, its own properties (that is, excluding 
properties that refer to other resources), and the digests of each of its 
dependencies. The digest of a resource, defined recursively this way, remains 
stable even if one or more of its dependencies gets renamed. Since the 
resources in a CloudFormation template form a directed acyclic graph, this 
function is well-defined.

Resources that have the same digest, but different locations, are considered to be
the same resource, and therefore to have been moved or renamed.

#### Limitations
- A refactor cannot leave a stack empty. This is a CloudFormation API limitation, 
  that also applies to deployments.
- Creation of new stacks during a refactor is not supported. If you need to
  create a new stack, do it in a separate deployment, previous to refactoring.

### `cdk drift`

Checks if there is any drift in your stack or stacks. If you need the command
to return a non-zero if any differences are found, you need to use the `--fail`
command line option.

```console
$ # Detect drift against the currently-deployed stack
$ cdk drift

$ # Detect drift against a specific stack
$ cdk drift MyStackName
```

Note that there are some resources that do not support drift detection. You can
see which of these resources were left unchecked with the `--verbose` command line
option.

```console
$ # Detect drift against the currently-deployed stack with the verbose flag enabled
$ cdk drift --verbose 
```

### `cdk cli-telemetry`

Enables or disables cli telemetry collection for your local CDK App. Records your
choice in `cdk.context.json`. You can also set your preference manually under the `context` key in your
`~/.cdk.json` file or `<app-root>/cdk.json` file.

```bash
$ # Disable telemetry
$ cdk cli-telemetry --disable

$ # Enable telemetry
$ cdk cli-telemetry --enable
```

You can also check the current status on whether your CDK App is opted in or out of
cli telemetry collection. Note that this takes into account all methods of disabling
cli telemetry, including environment variables and
[context values](https://docs.aws.amazon.com/cdk/v2/guide/context.html)
that can be set in many different ways (such as `~/.cdk.json`).

```bash
$ # Check the current status of telemetry
$ cdk cli-telemetry --status
```
### `cdk flags` 

View and modify your feature flag configurations.

Run `cdk flags` to see a report of your feature flag configurations that differ from our recommended states. Unconfigured flags will be labelled with `<unset>` to show that flag currently has no value. The flags are displayed to you in the following order:

1. flags whose states do not match our recommended values
2. flags that are not configured at all

```shell
$ cdk flags --unstable=flags
    Feature Flag                              Recommended                  User
  * @aws-cdk/...                              true                         false
  * @aws-cdk/...                              true                         false
  * @aws-cdk/...                              true                         <unset>
```

Alternatively, you can also run `cdk flags --all` to see a report of all feature flags in the following order:

1. flags whose states match our recommended values
2. flags whose states do not match our recommended values
3. flags that are not configured at all

```shell
$ cdk flags --unstable=flags --all 
    Feature Flag                              Recommended                  User
    @aws-cdk/...                              true                         true
  * @aws-cdk/...                              true                         false
  * @aws-cdk/...                              true                         false
  * @aws-cdk/...                              true                         <unset>
```

### Modifying your feature flag values

To modify your feature flags interactively, you can run `cdk flags --interactive`  (or `cdk flags -i`) to view a list of menu options.

 To change every single feature flag to our recommended value and potentially overwrite existing configured values, run `cdk flags --set --recommended --all`. To keep feature flag configuration up-to-date with the latest CDK feature flag configurations, use this command.

```shell
$ cdk flags --unstable=flags --set --recommended --all
    Feature Flag                              Recommended Value            User Value
  * @aws-cdk/...                              true                         false
  * @aws-cdk/...                              true                         false
  * @aws-cdk/...                              true                         <unset>
  Synthesizing...
    Resources
    [~] AWS::S3::Bucket MyBucket
    └─ [~] Properties
        └─ [~] Encryption
                ... 
    Number of stacks with differences: 2
  Do you want to accept these changes? (y/n) y
  Resynthesizing...
```

If you would prefer your existing configured flags untouched, this option only changes the unconfigured feature flags to our recommended values, run `cdk flags --set --recommended --unconfigured`. This only changes the unconfigured feature flags to our recommended values.

```shell
$ cdk flags --unstable=flags --set --recommended --unconfigured
    Feature Flag                              Recommended Value            User Value
  * @aws-cdk/...                              true                         <unset>
  * @aws-cdk/...                              true                         <unset>
  Synthesizing...
    Resources
    [~] AWS::S3::Bucket MyBucket
    └─ [~] Properties
        └─ [~] Encryption
            ├─ [-] None
            └─ [+] ServerSideEncryptionConfiguration:
                    - ...
            ...
    Number of stacks with differences: 2
  Do you want to accept these changes? (y/n) y
  Resynthesizing...
```

If you want to ensure the unconfigured flags do not interfere with your application, `cdk flags --set --default --unconfigured` changes the unconfigured feature flags to its default values. For example, if `@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021` is unconfigured, it leads to the notification appearing after running `cdk synth`. However, if you set the flag to its default state (false), it will be configured, turned off, and have no impact on your application whatsoever.

```shell
$ cdk flags --unstable=flags --set --default --unconfigured
    Feature Flag                              Recommended Value            User Value
  * @aws-cdk/...                              true                         <unset>
  * @aws-cdk/...                              true                         <unset>
  Synthesizing...
  
  Do you want to accept these changes? (y/n) y
  Resynthesizing...
```

### Inspect a specific feature flag

#### View more information about a flag

Besides running `cdk flags` and `cdk flags --all` to view your feature flag configuration, you can also utilize `cdk flags "#FLAGNAME#"` to inspect a specific feature flag and find out what a specific flag does. This can be helpful in cases where you want to understand a particular flag and its impact on your application. 

```shell
$ cdk flags --unstable=flags "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021"
    Description: Enable this feature flag to have cloudfront distributions use the security policy TLSv1.2_2021 by default.
    Recommended Value: true
    User Value: true
```

#### Filter flags by substring

You can also run `cdk flags #substring#` to view all matching feature flags. If there is only one feature flag that matches that substring, specific details will be displayed. 

```shell
$ cdk flags --unstable=flags ebs
@aws-cdk/aws-ec2:ebsDefaultGp3Volume
    Description: When enabled, the default volume type of the EBS volume will be GP3
    Recommended Value: true
    User Value: true
```

If there are multiple flags matching the substring, a table with all matching flags will be displayed. If you enter multiple substrings, all matching flags
that contain any of those substrings will be returned.

```shell
$ cdk flags --unstable=flags s3 lambda
    Feature Flag                              Recommended                  User
  * @aws-cdk/s3...                            true                         false
  * @aws-cdk/lambda...                        true                         false
  * @aws-cdk/lambda...                        true                         <unset>
```

#### Modify a particular flag

If you need to modify the value of this flag and want to make sure you’re setting it to a correct and supported state, run `cdk flags --set "#FLAGNAME#" --value="#state#"`.

```shell
$ cdk flags --unstable=flags--set "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021" --value="true"
  Synthesizing...
    Resources
    [~] AWS::CloudFront::Distribution MyDistribution
    └─ [~] Properties
        └─ [~] DefaultSecurityPolicy
            ├─ [-] TLSv1.0
            └─ [+] TLSv1.2_2021
                    - ...
    Number of stacks with differences: 2
  Do you want to accept these changes? (y/n) y
  Resynthesizing...   
```

## Global Options

### `unstable`

The `--unstable` flag indicates that the scope and API of a feature might still change.
Otherwise the feature is generally production ready and fully supported. For example,
`cdk gc` is gated behind an `--unstable` flag:

```bash
cdk gc --unstable=gc
```

The command will fail if `--unstable=gc` is not passed in, which acknowledges that the user
is aware of the caveats in place for the feature.

### `telemetry-file`

Send your telemetry data to a local file (note that `--telemetry-file` is unstable, and must
be passed in conjunction with `--unstable=telemetry`).

```bash
cdk list --telemetry-file=my/file/path --unstable=telemetry
```

The supplied path must be a non existing file. If the file exists, it will fail to log telemetry
data but the command itself will continue uninterrupted.

> Note: The file will be written to regardless of your opt-out status.

## Notices

CDK Notices are important messages regarding security vulnerabilities, regressions, and usage of unsupported
versions. Relevant notices appear on every command by default. For example,

```console
$ cdk deploy

... # Normal output of the command

NOTICES

22090   cli: cdk init produces EACCES: permission denied and does not fill the directory

        Overview: The CLI is unable to initialize new apps if CDK is
                  installed globally in a directory owned by root

        Affected versions: cli: 2.42.0.

        More information at: https://github.com/aws/aws-cdk/issues/22090


27547   Incorrect action in policy of Bucket `grantRead` method

        Overview: Using the `grantRead` method on `aws-cdk-lib/aws-s3.Bucket`
                  results in an invalid action attached to the resource policy
                  which can cause unexpected failures when interacting
                  with the bucket.

        Affected versions: aws-cdk-lib.aws_s3.Bucket: 2.101.0.

        More information at: https://github.com/aws/aws-cdk/issues/27547


If you don’t want to see a notice anymore, use "cdk acknowledge ID". For example, "cdk acknowledge 16603".
```

There are several types of notices you may encounter, differentiated by the affected component:

- **cli**: notifies you about issues related to your CLI version.
- **framework**: notifies you about issues related to your version of core constructs (e.g `Stack`).
- **aws-cdk-lib.{module}.{construct}**: notifies you about issue related to your version of a specific construct (e.g `aws-cdk-lib.aws_s3.Bucket`)
- **bootstrap**: notifies you about issues related to your version of the bootstrap stack. Note that these types of notices are only shown during the `cdk deploy` command.

You can suppress notices in a variety of ways:

- per individual execution:

  `cdk deploy --no-notices`

- disable all notices indefinitely through context in `cdk.json`:

  ```json
  {
    "notices": false,
    "context": {
      ...
    }
  }
  ```

- acknowledging individual notices via `cdk acknowledge` (see below).

### `cdk acknowledge`

To hide a particular notice that has been addressed or does not apply, call `cdk acknowledge` with the ID of
the notice:

```console
$cdk acknowledge 16603
```

> Please note that the acknowledgements are made project by project. If you acknowledge an notice in one CDK
> project, it will still appear on other projects when you run any CDK commands, unless you have suppressed
> or disabled notices.


### `cdk notices`

List the notices that are relevant to the current CDK repository, regardless of context flags or notices that
have been acknowledged:

```console
$ cdk notices

NOTICES

16603   Toggling off auto_delete_objects for Bucket empties the bucket

        Overview: if a stack is deployed with an S3 bucket with
                  auto_delete_objects=True, and then re-deployed with
                  auto_delete_objects=False, all the objects in the bucket
                  will be deleted.

        Affected versions: framework: <=2.15.0 >=2.10.0

        More information at: https://github.com/aws/aws-cdk/issues/16603


If you don’t want to see a notice anymore, use "cdk acknowledge <id>". For example, "cdk acknowledge 16603".
```

List the unacknowledged notices:

```console
$ cdk notices --unacknowledged

NOTICES         (What's this? https://github.com/aws/aws-cdk/wiki/CLI-Notices)

29483	(cli): Upgrading to v2.132.0 or v2.132.1 breaks cdk diff functionality

	Overview: cdk diff functionality used to rely on assuming lookup-role.
	          With a recent change present in v2.132.0 and v2.132.1, it is
	          now trying to assume deploy-role with the lookup-role. This
	          leads to an authorization error if permissions were not
	          defined to assume deploy-role.

	Affected versions: cli: >=2.132.0 <=2.132.1

	More information at: https://github.com/aws/aws-cdk/issues/29483


If you don’t want to see a notice anymore, use "cdk acknowledge <id>". For example, "cdk acknowledge 29483".

There are 1 unacknowledged notice(s).
```

### Bundling

By default asset bundling is skipped for `cdk list` and `cdk destroy`. For `cdk deploy`, `cdk diff`
and `cdk synthesize` the default is to bundle assets for all stacks unless `exclusively` is specified.
In this case, only the listed stacks will have their assets bundled.

## MFA support

If `mfa_serial` is found in the active profile of the shared ini file AWS CDK
will ask for token defined in the `mfa_serial`. This token will be provided to STS assume role call.

Example profile in `~/.aws/config` where `mfa_serial` is used to assume role:

```ini
[profile my_assume_role_profile]
source_profile=my_source_role
role_arn=arn:aws:iam::123456789123:role/role_to_be_assumed
mfa_serial=arn:aws:iam::123456789123:mfa/my_user
```

## SSO support

If you create an SSO profile with `aws configure sso` and run `aws sso login`, the CDK can use those credentials
if you set the profile name as the value of `AWS_PROFILE` or pass it to `--profile`.

## Configuration

On top of passing configuration through command-line arguments, it is possible to use JSON configuration files. The
configuration's order of precedence is:

1. Command-line arguments
2. Project configuration (`./cdk.json`)
3. User configuration (`~/.cdk.json`)

### JSON Configuration files

Some of the interesting keys that can be used in the JSON configuration files:

```json5
{
    "app": "node bin/main.js",                  // Command to start the CDK app      (--app='node bin/main.js')
    "build": "mvn package",                     // Specify pre-synth build           (--build='mvn package')
    "context": {                                // Context entries                   (--context=key=value)
        "key": "value"
    },
    "toolkitStackName": "foo",                  // Customize 'bootstrap' stack name  (--toolkit-stack-name=foo)
    "toolkitBucket": {
        "bucketName": "amzn-s3-demo-bucket",    // Customize 'bootstrap' bucket name (--toolkit-bucket-name=amzn-s3-demo-bucket)
        "kmsKeyId": "fooKMSKey"                 // Customize 'bootstrap' KMS key id  (--bootstrap-kms-key-id=fooKMSKey)
    },
    "versionReporting": false,                  // Opt-out of version reporting      (--no-version-reporting)
}
```

If specified, the command in the `build` key will be executed immediately before synthesis.
This can be used to build Lambda Functions, CDK Application code, or other assets.
`build` cannot be specified on the command line or in the User configuration,
and must be specified in the Project configuration. The command specified
in `build` will be executed by the "watch" process before deployment.

### Environment

The following environment variables affect aws-cdk:

- `CDK_DISABLE_VERSION_CHECK`: If set, disable automatic check for newer versions.
- `CDK_NEW_BOOTSTRAP`: use the modern bootstrapping stack.

### Running in CI

The CLI will attempt to detect whether it is being run in CI by looking for the presence of an
environment variable `CI=true`. This can be forced by passing the `--ci` flag. By default the CLI
sends most of its logs to `stderr`, but when `ci=true` it will send the logs to `stdout` instead.

### Changing the default TypeScript transpiler

The ts-node package used to synthesize and deploy CDK apps supports an alternate transpiler that might improve transpile times. The SWC transpiler is written in Rust and has no type checking. The SWC transpiler should be enabled by experienced TypeScript developers.

To enable the SWC transpiler, install the package in the CDK app.

```sh
npm i -D @swc/core @swc/helpers regenerator-runtime
```

And, update the `tsconfig.json` file to add the `ts-node` property.

```json
{
  "ts-node": {
    "swc": true
  }
}
```

The documentation may be found at <https://typestrong.org/ts-node/docs/swc/>
