Sub topic 1
Why infrastructure as code, and where CloudFormation fits
Prerequisites
This chapter assumes you can do the following:
- You know what S3 buckets, Lambda functions and IAM roles are.
- You can read YAML and basic TypeScript or Python.
- You have a terminal with the AWS CLI installed and credentials configured for a sandbox account.
You don't need any CDK knowledge yet. This chapter explains the layer underneath the CDK, so the rest of the tutorial makes sense.
The problem with clicking and scripting
You can build AWS resources by hand in the console. That works for one experiment. It breaks down once a team needs the same setup in several places.
- No record. Nobody can say exactly which settings were chosen, or why.
- No repeatability. A staging environment built by hand drifts away from production.
- No review. A teammate cannot comment on a console click before it happens.
- No safe undo. Rolling back means remembering what you changed.
A shell script that calls the AWS CLI fixes some of this. But a script is imperative. It lists steps ("create this, then that"). It does not know what already exists. Running it twice either fails or creates duplicates, and removing a resource means writing a separate cleanup script.
Infrastructure as code
Infrastructure as code (IaC) means you describe your resources in files and let a tool make the cloud match them. Those files live in version control with the rest of your code. This gives you:
- Pull-request review of infrastructure changes.
- A history of who changed what.
- The same definition deployed to many accounts and regions.
- Disposable environments you can create and delete on demand.
Most IaC tools are declarative. You state the desired end result, and the tool works out the steps to get there from the current state. That is what makes a second run safe: if nothing changed, nothing happens.
Where CloudFormation fits
AWS CloudFormation is the native IaC service of AWS. You give it a template, which is a JSON or YAML document listing resources and their properties. CloudFormation creates, updates and deletes those resources for you.
Four terms matter:
| Term | Meaning |
|---|---|
| Template | The JSON or YAML document that describes the desired resources. |
| Stack | One deployed instance of a template. CloudFormation manages all its resources as a unit. |
| Change set | A preview of what an update would add, modify or replace. |
| Drift | A difference between the template and the real resource, usually caused by manual edits. |
Here is a complete template for a versioned S3 bucket:
AWSTemplateFormatVersion: "2010-09-09"
Description: A versioned uploads bucket
Resources:
UploadsBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
VersioningConfiguration:
Status: Enabled
Outputs:
BucketName:
Value: !Ref UploadsBucketEach entry under Resources has a logical ID (UploadsBucket) and a Type. The logical ID is the name inside the template. The physical ID is the real name AWS assigns, and here CloudFormation generates it because the template does not set a bucket name. !Ref returns that physical name, so Outputs can report it.
The lifecycle of a stack
Save the template as bucket.yaml and deploy it:
aws cloudformation deploy \
--template-file bucket.yaml \
--stack-name uploads-demo
aws cloudformation describe-stacks --stack-name uploads-demo \
--query "Stacks[0].Outputs"The deploy command creates a change set and runs it. To review a change without applying it, add --no-execute-changeset. Then inspect the change set in the console or with aws cloudformation describe-change-set.
During an update, CloudFormation compares the new template with the stack's current state. For each resource it chooses one of three outcomes:
- No interruption. The property changes in place.
- Some interruption. The resource restarts or is briefly unavailable.
- Replacement. CloudFormation creates a new resource and deletes the old one.
Replacement is the one to watch. Changing an immutable property, such as a fixed bucket name or a DynamoDB table's key schema, replaces the resource and its data with it. Reading the change set before you execute it is how you catch this.
Failure modes you will meet
- Rollback on create. If a stack fails during its first creation, it ends in
ROLLBACK_COMPLETE. You cannot update it. Delete the stack and create it again. - Rollback on update. A failed update returns to the last good state. If the rollback itself fails, the stack enters
UPDATE_ROLLBACK_FAILED. You then continue the rollback, usually skipping the resource that cannot be restored. - Name collisions. Hard-coded physical names such as a bucket name must be globally unique, and they block replacement because the old and new resource would share a name. Letting CloudFormation generate names avoids this.
- Retained resources. A
DeletionPolicy: Retainresource survives stack deletion. That protects data, and it also leaves an orphan you must remove yourself. - Drift. A manual console edit is invisible to the template until you run drift detection, and the next update may overwrite it.
- Size limits. A stack can hold at most 500 resources. A template passed inline is limited to 51,200 bytes, and one uploaded to S3 to 1 MB.
What raw templates cost you
CloudFormation does the hard part: ordering, dependency tracking, rollback. The cost is in authoring. Templates are declarative documents with no real loops, functions or types. They also grow quickly. A Lambda function that can read a bucket needs the function, an IAM role, a policy with correct ARNs, and wiring between them, all written out by hand. Reusing a pattern means copying text or learning nested stacks and macros.
The AWS Cloud Development Kit (CDK) addresses this. You write ordinary TypeScript or Python, with classes, loops and imports. The CDK turns that code into a CloudFormation template, and CloudFormation still does the deployment. The CDK does not replace CloudFormation. It sits on top of it, so everything in this chapter still applies: stacks, change sets, rollbacks, drift and limits. The next chapter shows how the code becomes a template.
Exercise
You change a template so that a bucket's hard-coded BucketName property has a new value, then deploy it. What does CloudFormation do, and how could you have spotted this before deploying?
Show answer
Bucket names cannot be changed in place, so CloudFormation replaces the resource. It creates a new bucket with the new name and then deletes the old one. If the old bucket had DeletionPolicy: Retain it stays behind, but its data is not copied to the new bucket. A change set (--no-execute-changeset) would have shown the bucket with a replacement action before anything ran.
Exercise
A new stack fails during its first creation and shows ROLLBACK_COMPLETE. You fix the template and run deploy again, but it is rejected. Why, and what do you do?
Show answer
A stack that failed on creation and rolled back cannot be updated. Delete the stack, then deploy the fixed template again to create it fresh.