By the end you'll know
- What CloudFormation and the CDK are, and how they relate to each other and to Terraform
- How a change set previews a change, and why it lists more than will really change
- What CloudFormation does when an update fails part-way, and what Terraform does instead
- Why CloudFormation can detect drift but won't fix it by redeploying
- What the CDK writes for you, including IAM policies and choices you didn't make
- How to choose between the three for a team
Before you start
- You need: the
juniper-ryeprofile, signed in, Lesson 20's virtual environment, Node.js for the CDK (brew install node), and Terraform for the comparison. - This lesson compares against two others. Lesson 28 built a service with Terraform, and the Terraform track covers plans and state. The pipeline itself, a topic feeding a queue feeding a function, is Lesson 23's.
- The lab:
lesson-30in the practice folder:lab.py, the template incfn, the CDK app incdk, and the Terraform version interraform. Everything is namedjr-lesson30-*and taggedlesson=30. - Where you run things: your own machine, labeled (Your machine).
- Every output below is from a real run on November 15, 2026, with CDK library 2.277.0 and CLI 2.1148.1.
Deleting a stack doesn't always delete everything
Resources marked Retain survive their stack, and keep billing. The CDK marks every S3 bucket Retain unless you say otherwise, and Lambda makes its log groups outside the stack. In this lab both buckets and both log groups were still there after their stacks were deleted, until delete removed them. Everything here is inside the free allowances, but in a real account, leftovers like these are where the next unused-resource report comes from.
The short version
- CloudFormation is AWS's own infrastructure-as-code service: you hand it a template, and AWS keeps the state.
- The CDK is code that writes CloudFormation templates, with sensible defaults and permissions filled in.
- A change set is the preview. It's cautious: it lists anything that might change.
- A failed update rolls the whole stack back by itself; Terraform leaves things where they stopped.
- Drift is detected but not fixed by redeploying, because CloudFormation compares templates, not reality.
What this lesson costs
| Part | Cost, in us-east-2 |
|---|---|
| CloudFormation and the CDK | Nothing for AWS's own resource types |
| Two topics, four queues, two functions, two buckets | Inside the free allowances at this size |
| This lesson | Nothing |
Three ways to write the same thing
Terraform, from Lesson 28, is one way to write infrastructure as code. AWS has its own: CloudFormation, a service that takes a template, a YAML or JSON file listing resources, and builds it as a stack that AWS tracks for you. The CDK (Cloud Development Kit) sits on top: you write ordinary code, in TypeScript, Python, Java or others, and it writes the CloudFormation template.
| CloudFormation | CDK | Terraform | |
|---|---|---|---|
| You write | YAML or JSON | TypeScript, Python, Java, C#, Go | HCL |
| State kept by | AWS, in the stack | AWS, in the stack | You, in a bucket you set up |
| Preview | Change set | cdk diff, then a change set | terraform plan |
| A failed update | Rolls the whole stack back | Rolls the whole stack back | Stops where it failed |
| Drift | Detects it; a redeploy won't fix it | The same | Every plan finds it; apply puts it back |
| Beyond AWS | No | No | Yes: thousands of providers |
| Cost | Free for AWS's own types | Free | Free; HCP Terraform for teams is paid beyond a free tier |
The template
Part of cfn/orders.yaml, the 132 lines written by hand. Every resource is spelled out, and references between them use functions like !Ref and !GetAtt:
Parameters:
QueueName:
Type: String
Default: orders
VisibilityTimeout:
Type: Number
Default: 30
MemorySize:
Type: Number
Default: 128
Resources:
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
QueueName: !Sub "${AWS::StackName}-${QueueName}"
VisibilityTimeout: !Ref VisibilityTimeout
RedrivePolicy:
deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn
maxReceiveCount: 3
Archive:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
(Your machine)
cd ~/Apps/aws-practice/lesson-30
source ../lesson-20/.venv/bin/activate
python lab.py fence
python lab.py cfn-plan
== Tools on your machine
node v20.19.0
npm 11.5.2
terraform Terraform v1.11.3
== Can this account use CloudFormation in us-east-2?
yes; existing stacks in this Region: 0
== What it costs
CloudFormation itself: nothing for AWS's own resource types
the topic, queues, function and bucket: inside the free allowances at this size
== Validating cfn/orders.yaml (132 lines)
valid; parameters: MemorySize=128, VisibilityTimeout=30, QueueName=orders; needs: CAPABILITY_IAM
== A change set for jr-lesson30-cfn: what CloudFormation would do
change set create-4db0ce: create_complete, 9 changes
Action Logical ID Type Replacement
Add Archive AWS::S3::Bucket -
Add DeadLetterQueue AWS::SQS::Queue -
Add HandlerQueueMapping AWS::Lambda::EventSourceMapping -
Add HandlerRole AWS::IAM::Role -
Add Handler AWS::Lambda::Function -
Add OrdersQueuePolicy AWS::SQS::QueuePolicy -
Add OrdersQueue AWS::SQS::Queue -
Add OrdersSubscription AWS::SNS::Subscription -
Add OrdersTopic AWS::SNS::Topic -
== Nothing exists yet. Run python lab.py cfn-apply to carry it out.
needs: CAPABILITY_IAM is CloudFormation asking you to say yes out loud. A template that creates IAM roles can grant permissions, so CloudFormation won't run it unless the caller acknowledges that, here in the Capabilities argument. It's a speed bump, not a security control, but it makes "this creates permissions" impossible to miss.
The change set is CloudFormation's terraform plan: a saved preview, with a name, that you then execute or delete. The 9 logical IDs are the names from the template; what they'll be called in AWS isn't known yet.
Apply: a stack
python lab.py cfn-apply
python lab.py send cfn
== Running change set create-4db0ce
22:49:35 jr-lesson30-cfn CREATE_IN_PROGRESS User Initiated
22:49:37 OrdersTopic CREATE_IN_PROGRESS
22:49:37 Archive CREATE_IN_PROGRESS
22:49:37 DeadLetterQueue CREATE_IN_PROGRESS
22:49:37 OrdersTopic CREATE_IN_PROGRESS Resource creation Initiated
22:49:38 DeadLetterQueue CREATE_IN_PROGRESS Resource creation Initiated
22:49:38 Archive CREATE_IN_PROGRESS Resource creation Initiated
22:49:38 OrdersTopic CREATE_COMPLETE
22:49:38 DeadLetterQueue CREATE_IN_PROGRESS Eventual consistency check initiated
22:49:38 OrdersQueue CREATE_IN_PROGRESS
22:49:39 OrdersQueue CREATE_IN_PROGRESS Resource creation Initiated
22:49:39 OrdersQueue CREATE_IN_PROGRESS Eventual consistency check initiated
22:49:40 OrdersSubscription CREATE_IN_PROGRESS
22:49:40 OrdersQueuePolicy CREATE_IN_PROGRESS
22:49:40 OrdersQueuePolicy CREATE_IN_PROGRESS Resource creation Initiated
22:49:41 OrdersSubscription CREATE_IN_PROGRESS Resource creation Initiated
22:49:41 OrdersSubscription CREATE_COMPLETE
22:49:51 Archive CREATE_COMPLETE
22:50:11 OrdersQueuePolicy CREATE_COMPLETE
22:50:39 DeadLetterQueue CREATE_COMPLETE
22:50:41 OrdersQueue CREATE_COMPLETE
22:50:41 HandlerRole CREATE_IN_PROGRESS
22:50:42 HandlerRole CREATE_IN_PROGRESS Resource creation Initiated
22:50:58 HandlerRole CREATE_COMPLETE
22:50:59 Handler CREATE_IN_PROGRESS
22:51:00 Handler CREATE_IN_PROGRESS Resource creation Initiated
22:51:01 Handler CREATE_IN_PROGRESS Eventual consistency check initiated
22:51:01 HandlerQueueMapping CREATE_IN_PROGRESS
22:51:02 HandlerQueueMapping CREATE_IN_PROGRESS Resource creation Initiated
22:51:06 Handler CREATE_COMPLETE
22:51:13 HandlerQueueMapping CREATE_COMPLETE
22:51:14 jr-lesson30-cfn CREATE_COMPLETE
== jr-lesson30-cfn: CREATE_COMPLETE after 100 seconds
FunctionName jr-lesson30-cfn-Handler-LWGSYvjqzqf1
TopicArn jr-lesson30-cfn-orders
ArchiveBucket jr-lesson30-cfn-archive-clyx34dfecej
QueueUrl jr-lesson30-cfn-orders
== Published order-1d3635 to the topic; waiting for the function to log it
after 11 seconds the function logged: {"order": "order-1d3635", "items": 3}
topic -> queue -> function, all from jr-lesson30-cfn
The events are the stack's own log, and they're the first place to look when anything goes wrong. CloudFormation worked out the order from the references, like Terraform: the topic and queues first, the role once the queue's ARN was known, the function once its role existed, the mapping last. The queues each spent about a minute on "Eventual consistency check": CloudFormation now waits until a new resource is visible everywhere in AWS before building anything that depends on it, which costs time but avoids the "role not found yet" retries earlier lessons had to write by hand.
Resources without a name in the template got one made up: jr-lesson30-cfn-Handler-LWGSYvjqzqf1, the stack, the logical ID and a random suffix.
Reading a change set
Two possible changes, both previewed, only the first run:
python lab.py cfn-change
== Change 1: the queue's visibility timeout, 30 -> 60 seconds
change set timeout-24d891: create_complete, 6 changes
Action Logical ID Type Replacement
Modify HandlerQueueMapping AWS::Lambda::EventSourceMapping Conditional
because EventSourceArn changed: replaces it
Modify HandlerRole AWS::IAM::Role False
because Policies changed: in place
Modify Handler AWS::Lambda::Function False
because Role changed: in place
Modify OrdersQueuePolicy AWS::SQS::QueuePolicy False
because PolicyDocument changed: in place
Modify OrdersQueue AWS::SQS::Queue False
because VisibilityTimeout changed: in place
Modify OrdersSubscription AWS::SNS::Subscription Conditional
because Endpoint changed: replaces it
== Change 2: the queue's name, orders -> orders-v2
change set rename-9e3a9b: create_complete, 7 changes
Action Logical ID Type Replacement
Modify DeadLetterQueue AWS::SQS::Queue True
because QueueName changed: replaces it
Modify HandlerQueueMapping AWS::Lambda::EventSourceMapping True
because EventSourceArn changed: replaces it
Modify HandlerRole AWS::IAM::Role False
because Policies changed: in place
Modify Handler AWS::Lambda::Function False
because Role changed: in place
Modify OrdersQueuePolicy AWS::SQS::QueuePolicy False
because PolicyDocument changed: in place
because Queues changed: in place
Modify OrdersQueue AWS::SQS::Queue True
because QueueName changed: replaces it
because RedrivePolicy changed: in place
Modify OrdersSubscription AWS::SNS::Subscription True
because Endpoint changed: replaces it
== Running change 1, deleting change 2 unrun
22:51:41 jr-lesson30-cfn UPDATE_IN_PROGRESS User Initiated
22:51:44 OrdersQueue UPDATE_IN_PROGRESS
22:52:45 OrdersQueue UPDATE_COMPLETE
22:52:46 jr-lesson30-cfn UPDATE_COMPLETE_CLEANUP_IN_PROGRESS
22:52:47 jr-lesson30-cfn UPDATE_COMPLETE
== jr-lesson30-cfn: UPDATE_COMPLETE after 68 seconds
the queue's visibility timeout is now 60 seconds
Change 1 listed 6 resources, two of them possibly replaced. Running it touched one: the queue. A change set is worked out before anything runs, so it can't always know whether a value will change. The role, the function, the subscription and the mapping all refer to the queue's ARN, so CloudFormation listed them in case the ARN changed; Conditional means "replaced only if the value it depends on really changes". It didn't, and only OrdersQueue appears in the events.
Change 2 is the one to stop at. Renaming a queue can't be done in place: True beside both queues, the subscription and the mapping means each would be deleted and made again, and any messages waiting in the old queues would go with them. The same reading habit as Lesson 28's plans applies: find the Trues before you run anything.
| Replacement | Means | Terraform's word for it |
|---|---|---|
False | Changed in place | ~ update in-place |
Conditional | Replaced only if a value it depends on really changes | No exact match: Terraform usually knows by plan time |
True | Deleted and made again, with a new ID | -/+ must be replaced |
When an update fails part-way
One update with two changes: the function's memory, which is fine, and the queues renamed to orders.v2, which isn't, because queue names can't contain dots.
python lab.py cfn-break
== One update, two changes: the function's memory 128 -> 256 MB (fine), and the queues renamed to
orders.v2 (not allowed: queue names can't contain dots)
change set break-a345e1: create_complete, 7 changes
Action Logical ID Type Replacement
Modify DeadLetterQueue AWS::SQS::Queue True
because QueueName changed: replaces it
Modify HandlerQueueMapping AWS::Lambda::EventSourceMapping True
because EventSourceArn changed: replaces it
Modify HandlerRole AWS::IAM::Role False
because Policies changed: in place
Modify Handler AWS::Lambda::Function False
because Role changed: in place
because MemorySize changed: in place
Modify OrdersQueuePolicy AWS::SQS::QueuePolicy False
because PolicyDocument changed: in place
because Queues changed: in place
Modify OrdersQueue AWS::SQS::Queue True
because QueueName changed: replaces it
because RedrivePolicy changed: in place
Modify OrdersSubscription AWS::SNS::Subscription True
because Endpoint changed: replaces it
22:52:58 jr-lesson30-cfn UPDATE_IN_PROGRESS User Initiated
22:53:00 DeadLetterQueue UPDATE_IN_PROGRESS Requested update requires the creation of a new physical resource; hence creating one.
22:53:01 DeadLetterQueue UPDATE_FAILED Resource handler returned message: "Can only include alphanumeric characters, hyphens, or underscores. 1 to 80
22:53:01 jr-lesson30-cfn UPDATE_ROLLBACK_IN_PROGRESS The following resource(s) failed to update: [DeadLetterQueue].
22:53:03 DeadLetterQueue UPDATE_COMPLETE
22:53:04 jr-lesson30-cfn UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS
22:53:05 DeadLetterQueue DELETE_COMPLETE
22:53:05 jr-lesson30-cfn UPDATE_ROLLBACK_COMPLETE
== jr-lesson30-cfn: UPDATE_ROLLBACK_COMPLETE after 9 seconds
== The function's memory now: 128 MB (256 was applied, then rolled back)
The change set couldn't catch it; the update did, on its very first step. The dead-letter queue is the first thing the update tried to make, and AWS refused its new name. CloudFormation stopped there, marked the stack UPDATE_ROLLBACK_IN_PROGRESS, and in 9 seconds had put every resource back to where it was before the update started. The stack ended UPDATE_ROLLBACK_COMPLETE: working, and exactly as before.
Read the events, not the script's last line. The script assumed the memory change had been made and undone. The events show otherwise: there's no Handler line at all, because the update stopped before it reached the function. The memory was 128 MB because it was never changed. The script now just reports the memory. It's a small example of the habit that matters: the stack's events are the record of what happened; everything else is a summary.
This is the biggest practical difference from Terraform. Terraform applies changes until one fails, then stops, and leaves the resources that changed as they are, with the state recording exactly that. You fix the code and apply again. CloudFormation treats the update as all or nothing. Both are reasonable; the difference matters when you're the one cleaning up at 2am.
Drift: detected, not fixed
python lab.py cfn-drift
== By hand, outside CloudFormation: the queue's visibility timeout -> 45 seconds
== Asking CloudFormation to detect drift
DRIFTED after 3 seconds: 1 resources drifted
OrdersQueue (AWS::SQS::Queue): MODIFIED
/VisibilityTimeout: expected 60, actually 45
== Redeploying the same template and parameters, to put it back
change set redeploy-dcf827: failed, 0 changes
reason: The submitted information didn't contain changes. Submit different information to create a change set.
the queue's visibility timeout is still 45 seconds
CloudFormation found the drift in 3 seconds, then refused to fix it. Drift detection compares the stack's last template with what's really there. Change sets compare a new template with the last template, not with what's really there. The template hadn't changed, so as far as the change set was concerned there was nothing to do, and the queue stayed at 45 seconds.
That's the reverse of Lesson 28, where every terraform plan read the real resources and the next apply put the drift back. On CloudFormation, the ways out are to change it back by hand, or to change the template to the value you want so that a real change exists. Drift detection is something you run, or schedule; it doesn't happen on every deploy.
The CDK: code that writes the template
The same pipeline in cdk/app.js. One line, handler.addEventSource(...), does what the event source mapping and the role's queue policy did in the template:
const deadLetters = new sqs.Queue(this, "DeadLetterQueue", { retentionPeriod: cdk.Duration.days(14) });
const queue = new sqs.Queue(this, "OrdersQueue", {
visibilityTimeout: cdk.Duration.seconds(30),
deadLetterQueue: { queue: deadLetters, maxReceiveCount: 3 },
});
const topic = new sns.Topic(this, "OrdersTopic");
topic.addSubscription(new SqsSubscription(queue, { rawMessageDelivery: true }));
const handler = new lambda.Function(this, "Handler", {
runtime: lambda.Runtime.PYTHON_3_13,
architecture: lambda.Architecture.ARM_64,
handler: "index.handler",
timeout: cdk.Duration.seconds(10),
code: lambda.Code.fromInline(HANDLER),
});
handler.addEventSource(new SqsEventSource(queue, { batchSize: 10 }));
const archive = new s3.Bucket(this, "Archive", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
enforceSSL: true,
});
python lab.py cdk-synth
== Installing the CDK into cdk/node_modules (once)
added 6 packages in 8s
== CDK versions: aws-cdk-lib@2.277.0, aws-cdk@2.1148.1
== npx cdk synth: running app.js to write a CloudFormation template
59 lines of JavaScript became 375 lines of CloudFormation in 5 seconds
== What's in it
1 AWS::IAM::Policy
1 AWS::IAM::Role
1 AWS::Lambda::EventSourceMapping
1 AWS::Lambda::Function
1 AWS::S3::Bucket
1 AWS::S3::BucketPolicy
1 AWS::SNS::Subscription
1 AWS::SNS::Topic
2 AWS::SQS::Queue
1 AWS::SQS::QueuePolicy
== Logical IDs the CDK chose (a readable name plus a hash of where it sits in the app)
DeadLetterQueue9F481546
OrdersQueue3DFA1D51
OrdersQueuePolicy060934B1
OrdersQueuejrlesson30cdkOrdersTopic035A18174C45A08A
OrdersTopic47790A41
HandlerServiceRoleFCDC14AE
== The IAM policy the CDK wrote for the function, from one line: handler.addEventSource(...)
Allow sqs:ReceiveMessage, sqs:ChangeMessageVisibility, sqs:GetQueueUrl, sqs:DeleteMessage, sqs:GetQueueAttributes on {"Fn::GetAtt": ["OrdersQueue3DFA1D51", "Arn"]}
== What the CDK decided for the bucket, without being asked
ArchiveDA4CB258: DeletionPolicy Retain, UpdateReplacePolicy Retain
bucket policy: Deny s3:* when {"Bool": {"aws:SecureTransport": "false"}}
| The CDK wrote | From | Worth knowing |
|---|---|---|
| The function's IAM policy | addEventSource | Five SQS actions on this one queue: the four written by hand, plus GetQueueUrl |
| The queue policy and subscription | addSubscription | Including the condition that only this topic may send |
| A bucket policy denying plain HTTP | enforceSSL: true | One property became a whole resource |
| DeletionPolicy Retain on the bucket | Nothing: it's the default | Deleting the stack leaves the bucket, and its contents, behind |
| Logical IDs with hashes | Each construct's place in the app | Rename or move a construct and its ID changes: CloudFormation sees a new resource and replaces it |
The CDK's real value is the IAM. Writing least-privilege policies by hand is slow and easy to get wrong: the four actions in the template had to be looked up, one by one. The CDK's grant methods and integrations like addEventSource write the policy for exactly what you connected, scoped to exactly that resource.
Its biggest trap is the logical IDs. In a template you name OrdersQueue yourself; in the CDK, the ID comes from the code's structure. Rename the construct, or move it into another construct, and the next deploy replaces the resource. For a queue that loses messages; for a database it loses data.
python lab.py cdk-plan
python lab.py cdk-apply
python lab.py send cdk
== A change set for jr-lesson30-cdk, from the template the CDK wrote
change set create-b41b9b: create_complete, 11 changes
Action Logical ID Type Replacement
Add ArchiveDA4CB258 AWS::S3::Bucket -
Add ArchivePolicyC780D5C8 AWS::S3::BucketPolicy -
Add DeadLetterQueue9F481546 AWS::SQS::Queue -
Add Handler886CB40B AWS::Lambda::Function -
Add HandlerServiceRoleDefaultP AWS::IAM::Policy -
Add HandlerServiceRoleFCDC14AE AWS::IAM::Role -
Add HandlerSqsEventSourcejrles AWS::Lambda::EventSourceMapping -
Add OrdersQueue3DFA1D51 AWS::SQS::Queue -
Add OrdersQueuePolicy060934B1 AWS::SQS::QueuePolicy -
Add OrdersQueuejrlesson30cdkOr AWS::SNS::Subscription -
Add OrdersTopic47790A41 AWS::SNS::Topic -
== jr-lesson30-cdk: CREATE_COMPLETE after 88 seconds
FunctionName jr-lesson30-cdk-Handler886CB40B-6zSbHHm71tmf
TopicArn jr-lesson30-cdk-OrdersTopic47790A41-ibUqy4WnFrO8
ArchiveBucket jr-lesson30-cdk-archiveda4cb258-c40hvjirxnja
QueueUrl jr-lesson30-cdk-OrdersQueue3DFA1D51-GK47L7ZTxLLd
== Published order-9ea46a to the topic; waiting for the function to log it
after 4 seconds the function logged: {"order": "order-9ea46a", "items": 3}
topic -> queue -> function, all from jr-lesson30-cdk
The same pipeline, from the same kind of change set and stack, working the same way. Normally you'd run cdk deploy, which makes and runs the change set for you. This lab deploys the CDK's template through the same steps as the hand-written one, to show they're the same thing underneath. It also skips cdk bootstrap, a one-time setup per account and Region that makes a bucket, a container repository and roles the CDK uses to upload files; this app has no files to upload. Real CDK apps with Lambda code in folders or Docker images need it.
Line by line
python lab.py compare
== The same pipeline, as written by hand
CloudFormation template 132 lines cfn/orders.yaml
CDK app 59 lines cdk/app.js
what the CDK generated 375 lines cdk/cdk.out/jr-lesson30-cdk.template.json
Terraform 132 lines terraform/main.tf
== Checking the Terraform version is valid, without touching AWS (init -backend=false, validate)
Success! The configuration is valid.
The CDK is the shortest to write by far, and the longest to read when something goes wrong, because what's deployed is the 375 lines, not the 59. CloudFormation and Terraform came out at the same length here, each spelling out every resource; Terraform needed an extra provider just to zip the function's code.
Take it down
python lab.py delete
== Deleting stack jr-lesson30-cfn
22:55:31 jr-lesson30-cfn DELETE_IN_PROGRESS User Initiated
22:55:33 OrdersQueuePolicy DELETE_IN_PROGRESS
22:55:33 HandlerQueueMapping DELETE_IN_PROGRESS
22:55:33 OrdersSubscription DELETE_IN_PROGRESS
22:55:33 Archive DELETE_SKIPPED
22:55:33 OrdersSubscription DELETE_COMPLETE
22:55:49 HandlerQueueMapping DELETE_COMPLETE
22:55:50 Handler DELETE_IN_PROGRESS
22:55:53 Handler DELETE_COMPLETE
22:55:54 HandlerRole DELETE_IN_PROGRESS
22:56:03 OrdersQueuePolicy DELETE_COMPLETE
22:56:04 OrdersTopic DELETE_IN_PROGRESS
22:56:07 HandlerRole DELETE_COMPLETE
22:56:07 OrdersQueue DELETE_IN_PROGRESS
22:56:50 OrdersTopic DELETE_COMPLETE
22:57:08 OrdersQueue DELETE_COMPLETE
22:57:09 DeadLetterQueue DELETE_IN_PROGRESS
DELETE_COMPLETE after 160 seconds
== Bucket jr-lesson30-cfn-archive-clyx34dfecej outlived its stack (DeletionPolicy Retain); deleting it now
== Log group /aws/lambda/jr-lesson30-cfn-Handler-LWGSYvjqzqf1 was made by Lambda, not the stack; deleting it now
== Bucket jr-lesson30-cdk-archiveda4cb258-c40hvjirxnja outlived its stack (DeletionPolicy Retain); deleting it now
== Log group /aws/lambda/jr-lesson30-cdk-Handler886CB40B-6zSbHHm71tmf was made by Lambda, not the stack; deleting it now
== Anything left from Lesson 30
nothing: all clear
DELETE_SKIPPED is Retain at work. Both stacks were deleted, and both buckets weren't: the hand-written one because the template said Retain, the CDK's because Retain is the CDK's default for buckets. That protects data from a deleted stack, which is right for anything holding records. It also means "delete the stack" isn't "delete everything", in either tool.
The log groups were never in the stacks at all. Lambda made them the first time each function wrote a log. The fix in real templates is to declare the log group as a resource, with a retention, so the stack owns it. The CDK's logRetention and logGroup options do that for you.
By hand: the AWS CLI and the CDK CLI
(Your machine) A change set, previewed and then run, and the stack's events:
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2
cd ~/Apps/aws-practice/lesson-30
aws cloudformation create-change-set --stack-name jr-lesson30-cfn --change-set-name first \
--change-set-type CREATE --template-body file://cfn/orders.yaml --capabilities CAPABILITY_IAM
aws cloudformation wait change-set-create-complete --stack-name jr-lesson30-cfn --change-set-name first
aws cloudformation describe-change-set --stack-name jr-lesson30-cfn --change-set-name first \
--query "Changes[].ResourceChange.[Action,LogicalResourceId,ResourceType,Replacement]" --output table
aws cloudformation execute-change-set --stack-name jr-lesson30-cfn --change-set-name first
aws cloudformation wait stack-create-complete --stack-name jr-lesson30-cfn
aws cloudformation describe-stack-events --stack-name jr-lesson30-cfn \
--query "StackEvents[:10].[Timestamp,LogicalResourceId,ResourceStatus]" --output table
aws cloudformation deploy does all of that in one command, for scripts. Drift:
DRIFT=$(aws cloudformation detect-stack-drift --stack-name jr-lesson30-cfn --query StackDriftDetectionId --output text)
aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id $DRIFT
aws cloudformation describe-stack-resource-drifts --stack-name jr-lesson30-cfn --stack-resource-drift-status-filters MODIFIED
The usual CDK commands, for an app that's been bootstrapped once:
cd cdk
npx cdk bootstrap
npx cdk diff
npx cdk deploy
npx cdk destroy
Which one?
Choosing for a team
- Already using Terraform, or using more than AWS: Terraform. One tool, one way of working, for every cloud and service.
- AWS only, and the team writes TypeScript or Python every day: the CDK. Least-privilege permissions written for you, and real code for loops and logic.
- AWS only, and you want no extra tools at all: CloudFormation. Nothing to install, state kept by AWS, and many AWS examples and Marketplace products are published as templates.
- Whatever you choose, choose one per system. Two tools managing the same resources fight each other's drift.
Two things decide it more than features do: what the team already knows, and whether everything lives in AWS. Terraform's advantage is that it isn't tied to AWS; CloudFormation's is that AWS keeps the state and rolls back for you; the CDK's is that permissions and wiring come from code instead of copy and paste.
In real systems
- Every change goes through a change set or a
cdk diffin review, and a pipeline runs it (Lesson 31), never a laptop. - Stacks have termination protection on, so a stack can't be deleted without first turning it off.
- Stateful resources have Retain, and stateful stacks are kept apart from stateless ones, so a stateless stack can be replaced freely.
- Drift detection runs on a schedule, or AWS Config's rule for it does, with alerts.
- StackSets deploy one template to many accounts and Regions, for guardrails like logging and alarms in every account (Lesson 36).
- CDK apps pin construct IDs for stateful resources, and check
cdk difffor any "replace" before merging. - Old CDK habits to avoid: physical names everywhere, which stop CloudFormation replacing a resource cleanly, and hand-edited generated templates.
Spot the problem
Work out what's wrong before you read the explanation.
"We tidied up the code and the database came back empty." A team moves its CDK database construct into a new DataLayer construct, to organize the app. The pull request is only a move, the tests pass, and cdk deploy runs from the pipeline. Afterwards, the database is a new, empty one, and the old one is gone. What's wrong? Moving the construct changed its logical ID, so CloudFormation saw one database removed and a different one added, and replaced it. The fix: keep stateful constructs where they are, or pin their IDs with overrideLogicalId; set RemovalPolicy.RETAIN and deletion protection on databases; and fail the pipeline if cdk diff shows a replacement of a stateful resource. Then check: move a test construct in a branch and run cdk diff; does it show the resource being destroyed and created, and does the pipeline stop?
Keep this
| Remember | Why |
|---|---|
| The CDK writes CloudFormation | 59 lines became 375; the 375 is what runs |
| Change sets over-report | 6 listed, 1 changed |
Find the Trues first | A rename replaced both queues, losing their messages |
| Failed updates roll back whole | Back to before in 9 seconds |
| The events are the record | They showed the function was never touched |
| Redeploying won't fix drift | "didn't contain changes" |
| Retain outlives the stack | Both buckets were DELETE_SKIPPED |
| CDK grants write tight IAM | Five actions, on one queue, from one line |
| CDK IDs come from the code's shape | Move a construct, replace a resource |
Where you are now
You've built the same pipeline with CloudFormation by hand and with the CDK, and compared both with Terraform: change sets that list more than changes, a failed update that put the whole stack back in 9 seconds, drift that a redeploy wouldn't touch, a CDK that wrote the permissions for you, and buckets kept on purpose after their stacks were gone. Next, Lesson 31 takes the tool out of your hands: a pipeline that deploys on every merge, signing in to AWS with OIDC and no stored keys.
Check yourself
What does the CDK produce when you run cdk synth?
Change 1 listed 6 resources. Why did only the queue change?
After the failed rename, what state was the stack in?
Why didn't redeploying the same template fix the drifted queue?
Why were both buckets still there after their stacks were deleted?
Which CDK habit can quietly replace a database?
When is Terraform the clearer choice over CloudFormation or the CDK?
Key terms
- CloudFormation: AWS's service that builds and tracks resources from a template.
- Template: a YAML or JSON file listing resources, parameters and outputs.
- Stack: the set of resources CloudFormation made from one template, tracked together.
- Change set: a saved preview of what a template change would do to a stack.
- Logical ID: a resource's name inside a template; AWS gives it a physical ID when it's made.
- Rollback: undoing a failed update, so the stack returns to how it was before.
- Drift detection: comparing a stack's resources with its last template.
- DeletionPolicy: what happens to a resource when its stack is deleted; Retain keeps it.
- Capabilities: an acknowledgement that a template creates IAM resources.
- CDK (Cloud Development Kit): a library for writing CloudFormation templates in ordinary code.
- Construct: a CDK building block, from a single resource to a whole pattern.
- Synth: running a CDK app to write its CloudFormation template.
- Bootstrap: the one-time setup per account and Region that CDK apps with files to upload need.
Go deeper
- Terraform track: Reading a plan and State, to compare with change sets and stacks.
- AWS: change sets (opens in a new tab), drift detection (opens in a new tab), and DeletionPolicy (opens in a new tab).
- AWS: the CDK Developer Guide (opens in a new tab), including best practices on logical IDs and stateful resources.
- Try: in
cdk/app.js, addremovalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: trueto the bucket, runcdk-synth, and see what the CDK adds to delete objects for you. Then rename"OrdersQueue"to"Orders", synth again, and compare the logical IDs. Rundeleteandcheckwhen you're done.