4.1.4. AWS CDK: Constructs, Apps, and Synthesis
š” First Principle: CloudFormation templates are powerful but verbose. A simple three-tier web application might require 500+ lines of YAML. AWS CDK lets you define the same infrastructure in 50 lines of TypeScript, Python, or Java ā using real programming language features (loops, conditionals, functions, classes) that YAML simply can't express. CDK is not a replacement for CloudFormation; it synthesizes CloudFormation templates. CloudFormation does the actual provisioning.
CDK Construct Levels:
| Level | Description | Abstraction |
|---|---|---|
| L1 (Cfn constructs) | Direct 1:1 mapping to CloudFormation resources (e.g., CfnBucket) | Low ā matches CF exactly |
| L2 (AWS constructs) | Curated, opinionated wrappers with sensible defaults (e.g., Bucket) | Medium ā simplifies common patterns |
| L3 (Patterns) | Multi-resource patterns for common architectures (e.g., ApplicationLoadBalancedFargateService) | High ā entire subsystems |
CDK Workflow:
Key CDK Commands:
| Command | What It Does |
|---|---|
cdk init | Create a new CDK project from template |
cdk synth | Synthesize CloudFormation template (doesn't deploy) |
cdk diff | Compare current stack to deployed stack |
cdk deploy | Synthesize and deploy to AWS |
cdk destroy | Delete the stack and its resources |
cdk bootstrap | Create the CDK Toolkit stack (S3 bucket, ECR repo) in the account/region |
CDK Bootstrap: Before you can deploy CDK applications, you must bootstrap the target account/region. cdk bootstrap creates the CDKToolkit CloudFormation stack, which includes an S3 bucket for storing CDK assets (Lambda code, Docker images) and an ECR repository. In multi-account deployments, you bootstrap each target account.
CDK Context: Key-value pairs stored in cdk.context.json that capture environment-specific values (e.g., "what AZs are available in this account?"). CDK queries AWS APIs on first use and caches the results so future synths are deterministic.
ā ļø Exam Trap: CDK synthesizes to CloudFormation, so all CloudFormation limits apply. The maximum template size is 1MB (S3) or 51KB (direct upload). Large CDK applications may require nested stacks to stay within limits. CDK handles this automatically when using the NestedStack construct ā but it's a constraint to be aware of for the exam.
Reflection Question: Your team uses Python and wants to define a three-tier web application with an ALB, Auto Scaling Group, and RDS instance using CDK. A new developer asks "does CDK replace CloudFormation?" How do you explain the relationship between CDK and CloudFormation, and what CDK command would they run first to preview what will be deployed?