Sub topic 2
How the CDK turns code into CloudFormation
This chapter assumes you know what S3, Lambda and IAM do, can read TypeScript or Python, and have Node.js installed. It also assumes you know the idea of CloudFormation templates. The CDK does not replace CloudFormation. It generates CloudFormation templates for you, so understanding that hand-off explains most CDK behavior, including its surprises.
The CDK is a template generator
A CDK app is an ordinary program. When it runs, it creates objects in memory and then writes files to disk. Those files are CloudFormation templates plus supporting data. The CDK never calls the S3 or Lambda APIs to create your bucket. CloudFormation does that, using the template your program produced.
This gives you three practical consequences:
- Your TypeScript or Python runs on your machine (or CI runner), never in AWS.
- Deployment features such as rollback, change sets and drift detection are CloudFormation's.
- Anything CloudFormation cannot do, the CDK cannot do either.
The pipeline from code to deployment
The workflow has four stages.
- Run. The CDK CLI reads the
appcommand fromcdk.jsonand runs it as a subprocess. For a TypeScript project this is typicallynpx ts-node --prefer-ts-exts bin/my-app.ts. - Build the construct tree. Your code instantiates an
App, one or moreStackobjects, and resources inside them. Every object is a construct with a parent. Together they form a tree. - Synthesize. When the program finishes (or when you call
app.synth()), the CDK walks the tree and writes a cloud assembly to thecdk.outdirectory. - Deploy. The CLI reads the cloud assembly, uploads assets, and asks CloudFormation to create or update each stack.
A minimal app
This app defines one versioned bucket.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
export class AppStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new s3.Bucket(this, 'UploadsBucket', {
versioned: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
}
}
const app = new cdk.App();
new AppStack(app, 'AppStack');Running cdk synth prints the template for AppStack. It looks like this, with the hash in the logical ID varying:
{
"Resources": {
"UploadsBucket5E5E9EB6": {
"Type": "AWS::S3::Bucket",
"Properties": {
"VersioningConfiguration": { "Status": "Enabled" }
},
"UpdateReplacePolicy": "Retain",
"DeletionPolicy": "Retain"
}
}
}Five lines of code produced a resource with the right Type, the versioning property and both retention policies. The mapping from removalPolicy to DeletionPolicy and UpdateReplacePolicy is the kind of detail the CDK fills in for you.
What is in the cloud assembly
After cdk synth, inspect the output directory.
cdk synth
ls cdk.outYou will typically see these items:
| File or directory | Purpose |
|---|---|
| `AppStack.template.json` | The CloudFormation template for one stack |
| `manifest.json` | Lists the stacks, their target environments, dependencies and assets |
| `tree.json` | A dump of the construct tree, useful for debugging |
| `asset.<hash>` | Staged files or folders, such as Lambda code, to upload at deploy time |
The manifest is what the CLI reads. It is also the contract between the "build" half and the "deploy" half. Tools such as CDK Pipelines rely on this: they synthesize once and deploy the same assembly in later stages.
One construct, one or more resources
Every CloudFormation resource in the template comes from a construct. High-level constructs such as s3.Bucket usually create one underlying low-level resource named Resource as a child, and some create more. A lambda.Function creates the function and an IAM role. The next chapters cover the construct levels in detail. For now, notice that one line of CDK code can produce several template entries.
Logical IDs and why renaming is dangerous
CloudFormation identifies each resource by its logical ID. The CDK computes it from the construct's path in the tree: the path components are joined, and an eight-character hash of the path is appended. For UploadsBucket inside AppStack, the path is UploadsBucket/Resource, and the redundant Resource segment is dropped, which gives UploadsBucket5E5E9EB6.
CloudFormation treats a changed logical ID as a different resource. It creates the new one and deletes the old one. Several edits can change the ID without you noticing:
- Changing the construct
idstring, for example'UploadsBucket'to'Uploads'. - Moving the construct under a different parent.
- Wrapping the construct in a new custom construct.
For a stateless resource this is fine. For a database or a bucket with data, it can mean replacement and data loss. The defense is simple: run cdk diff before every deploy and read it for unexpected replacements.
cdk diffA resource marked [-] and another marked [+] with similar types is the signature of an accidental rename.
What the CLI adds beyond CloudFormation
Plain CloudFormation templates cannot upload a local folder to S3. The CDK handles this with assets. During synthesis, local files such as Lambda code are staged in cdk.out. During deployment, the CLI uploads them to a bucket created by bootstrapping and rewrites the template references. The template that CloudFormation receives points at those uploaded locations.
This is also why a synthesized template is not always a complete deployable artifact on its own. Some values are placeholders until deploy time. They are resolved by the CLI or by CloudFormation itself, a topic the chapter on tokens covers.
Common errors at this stage
- Nothing happens after a code change. For TypeScript, a stale compiled
.jsfile may be running. Check thatcdk.jsonpoints at the file you are editing. --app is requiredor "no app found". You ran the CLI outside the project directory, orcdk.jsonis missing itsappentry.- Template size or resource limits. CloudFormation allows at most 500 resources per stack. A single
synthcan succeed and the deploy still fail. Split the app into more stacks when you approach the limit. - Treating synth as a validator.
cdk synthchecks your code and some construct rules. It does not check IAM permissions or whether names already exist. Those errors appear at deploy time.
Exercise
You rename the construct id of a stateful bucket from 'UploadsBucket' to 'Uploads' without changing anything else, and deploy. What does CloudFormation do, and which command would have warned you?
Show answer
The logical ID changes, so CloudFormation sees a new resource. It creates a new bucket and then removes the old one, which is retained or deleted depending on the removal policy. Running cdk diff before deploying would have shown a [+] entry for the new bucket and a [-] entry for the old one.
Exercise
Name the directory the CDK writes during synthesis, and name the file inside it that the CLI reads to learn which stacks, environments and assets to deploy.
Show answer
The directory is cdk.out, and the file is manifest.json.