Define AWS infrastructure with CloudFormation or CDK
Deploy a stack with one IaC tool, preview changes before applying them, and compare CloudFormation, CDK and Terraform.
By Invicly Tech, , in AWS Cloud Engineering. About 13 minutes to read.
In short
Infrastructure as code means you describe your buckets, queues, functions and roles in files, and a tool creates and updates them for you. AWS CloudFormation deploys templates as stacks, and the AWS CDK lets you write the same thing in a programming language that it turns into a CloudFormation template. Pick one primary tool, always preview a change before applying it, and let failed updates roll back on their own.
Think of it like this: A template is a recipe and a stack is the meal: change the recipe, preview what will be different, then cook again instead of adding ingredients by hand.
Explained simply
So far you may have built the file service by clicking in the console. That works once, but nobody can repeat it exactly, review it or undo it. Infrastructure as code, IaC for short, fixes this. You write down every bucket, queue, function and role in files, keep them in Git, and a tool makes AWS match the files.
AWS CloudFormation is the built-in IaC service. You give it a template in YAML or JSON, and it creates all the resources as one group called a stack. When you change the template, CloudFormation works out the difference and updates only what changed. If something fails during an update, it puts the stack back the way it was.
The AWS CDK, short for Cloud Development Kit, lets you write the same infrastructure in TypeScript, Python, Java, C# or Go. You get loops, functions and helpful defaults. The CDK then writes a CloudFormation template for you, a step called synthesis, and CloudFormation still does the real deploying. Terraform is a popular third-party tool that talks to AWS APIs directly and tracks resources in its own state file.
In this path we use the CDK as the primary tool, but the habits are the same in all three: keep one tool in charge of each resource, preview every change before applying it, pass differences between dev and prod as parameters, and keep a teardown command for lab stacks.
Cost note: CloudFormation and the CDK have no charge for AWS resources they manage; you pay for the resources. The lab stack in this module (S3, SQS, Lambda, DynamoDB on demand) costs very little at lab volume. Always run cdk destroy afterwards and check that buckets with data were emptied or deliberately kept.
Press Play on a diagram to walk through it one step at a time.
- 1Edit code
Add a DLQ to the file-processing queue
- 2cdk synth
Produces a CloudFormation template
- 3cdk diff
Shows resources added, changed or replaced
- 4cdk deploy
CloudFormation creates a change set and runs it
- 5Check stack events
UPDATE_COMPLETE or automatic rollback
- YAML or JSON templates
- State kept by AWS as a stack
- Change sets preview updates
- Automatic rollback on failure
- TypeScript, Python, Java, C# or Go
- Synthesises CloudFormation
- cdk diff previews updates
- Needs a one-time cdk bootstrap
- HCL files, many providers
- State file you store and lock
- terraform plan previews updates
- No automatic rollback; re-apply a fix
- 1Your CDK app
TypeScript or Python constructs and props
- 2Synthesised template
cdk.out/FileServiceDev.template.json
- 3Bootstrap resources
Asset bucket, ECR repo and deploy roles
- 4CloudFormation stack
Change set, events, rollback
- 5AWS resources
S3, SQS, Lambda, DynamoDB, IAM
In depth
Templates, parameters and environments
A CloudFormation template has Parameters (values supplied at deploy time), Resources (the only required section), Outputs (values you print or export) and optionally Conditions and Mappings. Each resource has a logical ID, the name in the template, and a physical ID, the real name in AWS. To deploy the same stack to dev and prod, pass a parameter like EnvName and use it for names, sizes and alarm thresholds. In the CDK, the usual pattern is one stack class instantiated twice with different props, or values read from context with -c env=dev. Do not copy the template per environment: copies drift apart and a fix reaches one but not the other. Keep secrets out of parameters; reference Secrets Manager or SSM Parameter Store instead.
- Resources is the only required section
- Logical ID: name in the template; physical ID: name in AWS
- One stack definition, several parameter sets
- Reference secrets, never paste them in
Previewing changes: change sets, cdk diff and terraform plan
Before an update, CloudFormation can build a change set: a list of each resource action, Add, Modify or Remove, and for modifications whether the resource will be replaced. Replacement matters because some properties cannot change in place, for example a DynamoDB table's key schema or a resource's explicit name. CloudFormation then creates a new resource and deletes the old one, which for a table means data loss unless you planned for it. cdk diff shows the same kind of preview, plus IAM and security group changes in a separate table, and cdk deploy asks for approval when security-sensitive changes appear (controlled by --require-approval). terraform plan is the Terraform equivalent. Make the preview part of code review: paste it into the pull request.
- Add
- New DLQ queue
- New alarm
- Modify, no replacement
- Lambda memory 256 to 512
- Queue redrive policy
- Modify, replacement True
- Table key schema change
- Stop and plan a migration
- Remove
- Old test topic
- Check nothing still uses it
Rollback, failure states and protecting data
If a stack update fails, CloudFormation rolls back to the previous template and the stack ends in UPDATE_ROLLBACK_COMPLETE. You can also add rollback triggers: CloudWatch alarms that CloudFormation watches during the update and for a monitoring period afterwards; if an alarm fires, it rolls back. For debugging you can deploy with --disable-rollback, which keeps the successful parts so you can inspect the failure, then fix forward or call rollback-stack. A rare state, UPDATE_ROLLBACK_FAILED, needs continue-update-rollback, sometimes skipping a resource. Protect data with DeletionPolicy and UpdateReplacePolicy set to Retain or Snapshot on buckets, tables and databases, and turn on termination protection for long-lived stacks. In the CDK, use removalPolicy: RemovalPolicy.RETAIN for real data and DESTROY only for lab resources.
- Default: automatic rollback on failure
- Rollback triggers: alarms watched during update
- DeletionPolicy Retain or Snapshot for stateful resources
- Termination protection blocks accidental stack deletes
Stacks versus Terraform state, and drift
CloudFormation stores state for you: the stack is the record of what it manages, and you cannot lose it. Terraform keeps state in a file you must store safely, usually an S3 bucket with versioning and encryption, with locking so two runs cannot write at once (recent Terraform versions support native S3 locking with use_lockfile; older setups use a DynamoDB table). Losing or corrupting state means Terraform no longer knows what it owns. Both tools suffer from drift when someone edits a resource by hand. CloudFormation drift detection compares live resources with the template; terraform plan shows drift as unexpected changes. The cure is the same: make the change in code, or import the hand-made resource so the tool owns it.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Write a template or CDK app~50m
- 2Pass parameters per environment~50m
- 3Preview with a change set or cdk diff~50m
- 4Watch a failed update roll back~50m
- 5Compare stacks with Terraform state~50m
Key points
- Choose one primary IaC tool per workload; mixing tools on the same resources causes drift and fights.
- Preview every change: a change set, cdk diff or terraform plan, and look hard at any Replacement.
- Pass environment differences as parameters or context, never as copies of the template.
- CloudFormation rolls a failed update back to the last working state by default.
- Manual console edits create drift; detect it and fold the change back into code.
Key terms
Tap a card to flip it. 0/6 known
Examples
npx cdk bootstrap aws://111122223333/eu-west-1 # once per account and Region
npx cdk synth # write the template to cdk.out/
npx cdk diff FileServiceDev # preview against the deployed stack
npx cdk deploy FileServiceDev -c env=dev
npx cdk destroy FileServiceDev # lab cleanupThe everyday CDK loop for the lab stack, ending with cleanup.
Define the file-processing stack in CDK (TypeScript)
Prerequisites: Node.js, the CDK CLI via npx, an SSO profile for the sandbox and a one-time cdk bootstrap. Step 1: create the stack below. Step 2: run cdk diff and confirm four main resources plus IAM. Step 3: cdk deploy. Evidence: the stack shows CREATE_COMPLETE and an upload to the bucket creates a message on the queue. Cleanup: cdk destroy; the DESTROY removal policy and autoDeleteObjects make lab teardown clean, which you would not use for real data.
export class FileServiceStack extends Stack {
constructor(scope: Construct, id: string, props: StackProps & { env: string }) {
super(scope, id, props);
const dlq = new sqs.Queue(this, "Dlq");
const queue = new sqs.Queue(this, "Jobs", {
visibilityTimeout: Duration.seconds(60),
deadLetterQueue: { queue: dlq, maxReceiveCount: 3 },
});
const bucket = new s3.Bucket(this, "Uploads", {
removalPolicy: RemovalPolicy.DESTROY, autoDeleteObjects: true,
});
bucket.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.SqsDestination(queue));
}
}Preview and apply a CloudFormation update with a change set
You change Lambda memory in template.yaml. Step 1: create a change set instead of updating directly. Step 2: describe it and check the Replacement column. Step 3: execute only if nothing important is replaced. Step 4: watch stack events. Evidence: status UPDATE_COMPLETE, or UPDATE_ROLLBACK_COMPLETE if it failed, with the reason in the events. Rollback is automatic; to abandon the change before running it, delete the change set.
aws cloudformation create-change-set \
--stack-name file-service-dev --change-set-name mem-512 \
--template-body file://template.yaml \
--parameters ParameterKey=EnvName,ParameterValue=dev \
--capabilities CAPABILITY_IAM
aws cloudformation describe-change-set \
--stack-name file-service-dev --change-set-name mem-512 \
--query 'Changes[].ResourceChange.[Action,LogicalResourceId,Replacement]'
aws cloudformation execute-change-set \
--stack-name file-service-dev --change-set-name mem-512
aws cloudformation describe-stack-events --stack-name file-service-dev --max-items 10Quick reference
- cdk bootstrap once per account and Region, then cdk synth, cdk diff, cdk deploy, cdk destroy.
- Change set columns to read: Action, LogicalResourceId and Replacement.
- Replacement True on a stateful resource means plan a migration first.
- Set DeletionPolicy and UpdateReplacePolicy to Retain or Snapshot for data stores.
- Failed updates roll back by default; --disable-rollback keeps resources for debugging.
- Detect hand edits with CloudFormation drift detection or terraform plan.
- Terraform state: S3 bucket with versioning, encryption and locking.
Common mistakes
- Renaming a resource's logical ID, which makes CloudFormation replace it and can delete data.
- Fixing something by hand in the console and then having the next deploy undo it.
- Deleting a stack that owns a bucket or table with real data and no retention policy set.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a new CDK app, synthesise it and find the template file without deploying anything.
- Exercise 2medium
Add an EnvName parameter to a CloudFormation template, deploy dev and test stacks from the same file, and prove they are separate.
- Exercise 3hard
Make a stack update fail on purpose and observe the rollback, then add a rollback trigger on an alarm.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I learn CloudFormation, CDK or Terraform first?
- Learn one well. If you only use AWS, the CDK or CloudFormation gives you managed state and automatic rollback; if your team uses several clouds, Terraform is common. Reading CloudFormation templates helps either way, because the CDK produces them.
- Is the CDK free?
- Yes. The CDK and CloudFormation have no charge for AWS resource types; you pay for the resources they create and the small bootstrap bucket.
- Why does cdk deploy ask me to confirm?
- By default it asks when a change widens security, such as new IAM permissions or security group rules. Review those changes, or set --require-approval never only in CI after a reviewed diff.