What it is
AWS CDK CLI is a command-line interface for defining cloud infrastructure as code using familiar programming languages, enabling automated provisioning and management of AWS resources.
Installation
Linux/macOS
npm install -g aws-cdk
Windows
npm install -g aws-cdk
Core Concepts
Stacks
A Stack is the fundamental deployment construct in AWS CDK. It represents a collection of AWS resources that you can deploy and manage as a single unit. You define your infrastructure within one or more Stacks.
Apps
An App is the root construct of a CDK application. It synthesizes deployment artifacts (CloudFormation templates) from your Stacks. Typically, you’ll have one App object in your bin/<your-app-name>.ts file.
Constructs
Constructs are the basic building blocks of AWS CDK applications. They represent a cloud component, such as a Lambda function, an S3 bucket, or an entire VPC. Constructs can be simple (like a single resource) or complex (like a complete application architecture).
Synthesis
Synthesis is the process by which the AWS CDK CLI translates your programming language code into AWS CloudFormation templates. These templates are then used by CloudFormation to provision and manage your AWS resources.
Asset Management
CDK handles the deployment of "assets," which are files or directories that need to be uploaded to AWS for your infrastructure to use. This commonly includes Lambda function code, Docker images, or static website content. CDK automatically uploads these assets to an S3 bucket or ECR repository during deployment.
Commands / Usage
App Management
cdk init
Initializes a new CDK project in the current directory.
# Initialize a TypeScript project
cdk init app --language typescript
# Initialize a Python project
cdk init app --language python
cdk synth
Synthesizes and prints the CloudFormation template for the specified stack(s) to standard output.
# Synthesize all stacks in the app
cdk synth
# Synthesize a specific stack
cdk synth MyStack
# Synthesize a specific stack and output to a file
cdk synth MyStack > template.yaml
cdk deploy
Deploys the CDK application to your AWS account. This command synthesizes the CloudFormation templates and then initiates a CloudFormation stack creation or update.
# Deploy all stacks in the app to the default environment
cdk deploy
# Deploy a specific stack to a specific environment
cdk deploy MyStack --profile personal-aws-profile --region us-east-1
# Deploy without confirmation prompt
cdk deploy --require-approval never
# Deploy changes and output stack outputs
cdk deploy --outputs-file cdk-outputs.json
cdk diff
Compares the deployed stack in your AWS account with the current state of your CDK app, showing you what CloudFormation changes will be made.
# Show differences for all stacks
cdk diff
# Show differences for a specific stack
cdk diff MyStack
# Show differences and include a specific asset
cdk diff MyStack --asset-hash-detection file
cdk destroy
Destroys the specified stack(s) in your AWS account, removing all provisioned resources.
# Destroy all stacks in the app
cdk destroy
# Destroy a specific stack
cdk destroy MyStack --profile personal-aws-profile
# Destroy without confirmation prompt
cdk destroy --require-approval never
Stack and Environment Management
cdk list
Lists the names of all stacks in the app.
cdk list
cdk context
Manages the context values used by CDK. Context can be used to pass values from the CLI to your CDK app (e.g., account/region IDs).
# View all context values
cdk context
# View context for a specific stack
cdk context MyStack
# Add a context value
cdk context --json '{"myAccountId": "123456789012"}'
# Remove a context value
cdk context --clear myAccountId
Asset Management
cdk assets
Lists and manages assets used by your CDK application.
# List all assets
cdk assets
# List assets for a specific stack
cdk assets MyStack
# List assets and show their status (e.g., whether they've been uploaded)
cdk assets --format json
AWS Account and Region Configuration
CDK typically uses the configured AWS credentials and region from your environment (e.g., ~/.aws/credentials, ~/.aws/config, environment variables). You can explicitly specify these during deployment or configuration.
--profile
Specifies the AWS profile to use.
cdk deploy --profile development
--region
Specifies the AWS region to deploy to.
cdk deploy --region eu-west-1
--account
Specifies the AWS account ID to deploy to.
cdk deploy --account 987654321098
CloudFormation Integration
cdk bootstrap
Deploys the necessary infrastructure (S3 buckets, IAM roles) that the CDK CLI needs to manage your stacks in a specific environment (account/region). This is usually required before deploying your first stack to a new environment.
# Bootstrap the current environment
cdk bootstrap
# Bootstrap a specific environment
cdk bootstrap aws://123456789012/us-west-2 --profile my-admin-profile
cdk cloudformation deploy
Deploys a CloudFormation template directly. This is useful if you have a pre-existing CloudFormation template or one generated by cdk synth.
cdk cloudformation deploy --template-file template.yaml --stack-name MyCloudFormationStack
cdk cloudformation remove-stacks
Removes CloudFormation stacks that were deployed using cdk cloudformation deploy.
cdk cloudformation remove-stacks --stack-names MyCloudFormationStack1 MyCloudFormationStack2
Common Patterns
Deploying to a specific account and region
cdk deploy --account 111122223333 --region us-east-1
Continuously synthesizing and deploying on changes (using watch)
# In one terminal:
cdk watch --watch-includes 'lib/**/*.ts' --watch-excludes 'node_modules/**'
# In another terminal:
cdk deploy --watch
Note: cdk watch is experimental and may not always be available or stable.
Deploying only specific stacks
cdk deploy StackA StackB
Viewing the CloudFormation template for a specific stack before deployment
cdk synth MyStack
Checking for potential drift in deployed resources
cdk diff MyStack
Automating deployments in CI/CD pipelines
# Example for a GitHub Actions workflow snippet:
# - name: Deploy CDK App
# uses: aws-actions/configure-aws-credentials@v1
# with:
{% raw %}
# aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
{% endraw %}
{% raw %}
# aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
{% endraw %}
# aws-region: us-east-1
# - name: Install dependencies
# run: npm install
# - name: Deploy CDK
# run: npx cdk deploy --require-approval never --account 111122223333 --region us-east-1
Deploying Lambda functions with local code
CDK automatically handles packaging and uploading Lambda code. Ensure your lambda.Code.fromAsset('./path/to/lambda/code') is correctly configured.
# Example in CDK code:
# import * as lambda from 'aws-cdk-lib/aws-lambda';
# new lambda.Function(this, 'MyLambda', {
# runtime: lambda.Runtime.NODEJS_18_X,
# handler: 'index.handler',
# code: lambda.Code.fromAsset('./lambda-code'),
# });
# Then deploy:
cdk deploy
Gotchas
Bootstrap is Required
You must run cdk bootstrap in an AWS account and region before you can deploy CDK stacks to it. This sets up necessary S3 buckets and IAM roles for asset handling and CloudFormation deployments.
Asset Hash Mismatch
If you modify your Lambda code or other assets but forget to update the CDK code that references them, CDK might not detect the change if the asset path hasn’t changed. Explicitly changing a parameter or using lambda.Code.fromAsset(..., { assetHash: ... }) can force a re-upload. The --asset-hash-detection flag in cdk diff can help diagnose this.
require-approval behavior
The --require-approval flag (e.g., never, broadening, any) controls whether CDK prompts for confirmation before deploying changes. never should be used with extreme caution, especially in production environments, as it bypasses manual review of CloudFormation changes.
Environment Configuration
CDK relies on your AWS credentials and default region. If you have multiple AWS profiles configured, ensure you’re using the correct --profile and --region flags, or that your environment variables (AWS_PROFILE, AWS_REGION) are set correctly.
Stack Naming Collisions
If you deploy multiple stacks with the same name to the same account/region, you’ll encounter errors. CDK uses the stack name to create CloudFormation stack names.
CDK Version Compatibility
Ensure that the CDK version used for installation and deployment is consistent. Major version upgrades can sometimes introduce breaking changes.
CloudFormation Limits
CDK synthesizes CloudFormation templates. You are still subject to AWS CloudFormation quotas and limits (e.g., maximum number of resources per stack, maximum template size).