Build from a written plan
Imagine building a house by phoning builders one at a time: "put a wall here", "now a shed over there". Nobody could build the same house twice, and nobody would remember why the shed is where it is.
So instead you draw a template: one written plan of the whole house, listing every part (a shed, a strongroom) and leaving a few blanks to fill in each time, like whether it's a practice house or the real one. You keep the plan in a drawer, where friends can check it before anything is built and where every old version is kept.
You hand the plan to a foreman, who builds every part on it and treats them as one house. When the house is finished, the foreman hands back a few facts you'll need, like the address and where the key is. Want a second, identical house for practice? Hand over the same plan with a different blank filled in.
Infrastructure as code and templates
Infrastructure as code means describing servers, networks, databases and permissions in files instead of clicking them together in a console. The files are repeatable (the same file builds the same environment, for dev, staging and prod), reviewable (changes go through pull requests like application code) and versioned (Git shows who changed what, and lets you go back).
AWS CloudFormation is the AWS service that reads such a file, a template in YAML or JSON, and creates what it declares. Its main sections:
| Section | Holds |
|---|---|
Resources | The only required section: each resource has a logical ID, a Type such as AWS::S3::Bucket, and Properties |
Parameters | Inputs supplied at deploy time, such as Env |
Outputs | Values the stack exposes after deploying, such as an endpoint or ARN, optionally exported for other stacks |
Mappings, Conditions | Lookup tables, and switches that include resources or properties only in some cases |
1AWSTemplateFormatVersion: "2010-09-09"2Parameters:3Env:4Type: String5AllowedValues: [dev, prod]6Resources:7InvoicesBucket:8Type: AWS::S3::Bucket9Properties:10Tags:11- Key: env12Value: !Ref Env13Outputs:14InvoicesBucketArn:15Value: !GetAtt InvoicesBucket.Arn
Deploying a template creates a stack: the set of resources CloudFormation manages together as one unit. You create,
update and delete the stack, never its resources one by one, and deleting the stack deletes everything in it, unless a
resource sets DeletionPolicy: Retain (kept) or Snapshot (deleted after a final snapshot). The same template with different parameters gives you separate
stacks, such as shop-dev and shop-prod. In a CI/CD pipeline, the template lives in the same
repository as the code and is deployed by the pipeline, not by hand.
Limits worth knowing
A template can declare up to 500 resources, 200 parameters and 200 outputs. A template body passed directly in the API
call can be at most 51,200 bytes; a template stored in S3 can be up to 1 MB. Bigger systems are split into several
stacks, or into nested stacks (AWS::CloudFormation::Stack), which also keeps each one's blast radius smaller.
What gets built first
You don't tell the foreman what order to build things in. The plan says the strongroom sits on the foundation and has a door lock, and both of those need the plot, so the foreman works it out: plot first, then foundation and lock, then strongroom. The workshop comes last, because it needs to know where the strongroom is. These "needs that first" links are called dependencies.
The foundation and the door lock both need only the plot, so different builders do them at the same time, and the job finishes sooner. And if two parts each need the other to be built first, the foreman refuses the plan, because there is no way to start.
Dependencies and ordering
CloudFormation builds a dependency graph from the template and creates resources in that order:
- Implicit dependencies: when a resource uses
!Refor!GetAtt(or!Subwith a reference) on another, the referenced resource is created first, and deleted last. - Explicit dependencies:
DependsOnforces an order when there is no reference, for example a route to an internet gateway, which needs the gateway'sVPCGatewayAttachmentto exist first.
Resources with no path between them are created in parallel, which is why a large stack doesn't take as long as the
sum of its parts. Deletion runs the graph backwards. A cycle (two security groups that reference each other in their
rules) fails validation with a circular dependency error; the usual fix is to move one side into a separate resource,
such as an AWS::EC2::SecurityGroupIngress.
A list of changes before any work starts
Months later you want two changes: paint the shed green, and move the strongroom to the other side of the house. Before touching a brick, you ask the foreman for a change set: a list of exactly what they would do.
The list says the shed just gets a coat of paint, so it stays standing. But a strongroom can't be slid across the house: it would be knocked down and a new one built, and anything inside the old one would go with it. Seeing that on paper, before anyone picks up a hammer, is the whole point. Only when you say "go ahead" does work start.
Change sets and update behaviour
Updating a stack means giving CloudFormation a new template or new parameters. A change set previews the update
without applying it: for each resource it lists the Action (Add, Modify, Remove) and, for modifications,
whether Replacement is True, False or Conditional.
1aws cloudformation create-change-set --stack-name shop-prod --change-set-name v2 \2--template-body file://template.yaml --parameters ParameterKey=Env,ParameterValue=prod3aws cloudformation describe-change-set --stack-name shop-prod --change-set-name v24aws cloudformation execute-change-set --stack-name shop-prod --change-set-name v2
How a property change is applied is documented per property, as one of three update behaviours:
- No interruption: modified in place, same physical ID (most tag changes).
- Some interruption: modified in place with a brief outage, such as an EC2 instance restarting to change its type.
- Replacement: CloudFormation creates a new resource with a new physical ID, points dependent resources at it, then deletes the old one. For a database, that means a new, empty database unless you restore from a snapshot.
Protecting data from replacement
UpdateReplacePolicy: Retain or Snapshot keeps or snapshots the old resource when it is replaced; DeletionPolicy
does the same when the resource or stack is deleted. A stack policy can deny updates to critical resources
altogether. Giving a resource a fixed physical name (BucketName, DBInstanceIdentifier) blocks updates that need
replacement, because two resources can't have the same name during the swap.
If a job goes wrong, undo it
Halfway through a job, something fails: the new workshop's walls won't go up. The foreman doesn't leave you with half a house. They undo everything from this job, so the shed goes back to its old colour and the half-built workshop is cleared away. That's called a rollback.
You end up with the house exactly as it was before the job, plus a note saying what went wrong, so you can fix the plan and try again.
Automatic rollback
Stack operations are all or nothing by default. If any resource fails to create or update (a quota is exceeded, a property is invalid, permissions are missing), CloudFormation rolls back:
- A failed create deletes what was created; the stack ends in
ROLLBACK_COMPLETEand has to be deleted before the name can be reused. - A failed update returns every resource to its previous configuration; the stack ends in
UPDATE_ROLLBACK_COMPLETEand keeps serving the old version.
The stack's events record each resource's status and the reason it failed. You can opt out of rollback and preserve
the resources that succeeded (--disable-rollback, or OnStackFailure: DO_NOTHING on a change set) to debug faster in
test environments. Rollback triggers can also roll a create or update back when a CloudWatch alarm fires during it
or within a monitoring period (up to 180 minutes) after it.
When the rollback itself fails
A rollback can fail too, typically because someone changed or deleted a resource outside CloudFormation. The stack is
then UPDATE_ROLLBACK_FAILED and accepts no updates until you fix the cause and run continue-update-rollback,
optionally skipping resources that can't be restored.
Spotting changes nobody wrote down
One weekend, a helper takes out the strongroom's alarm by hand, without changing the plan. Now the house and the plan disagree, and the next person to read the plan gets the wrong idea. That gap is called drift.
When you ask, the foreman walks round the house with the plan and marks every part that no longer matches. The foreman only reports it. Fixing it is up to you: put the change back, or write it into the plan so the plan tells the truth again.
Drift detection
Changes made outside CloudFormation, in the console, the CLI or another tool, are drift. CloudFormation doesn't see them on its own: a standard update compares the new template with the last deployed template, not with what's really there.
Drift detection (aws cloudformation detect-stack-drift, then describe-stack-resource-drifts) compares each
supported resource's actual properties with the template's expected values. Resources come back IN_SYNC, MODIFIED
or DELETED, and the stack is DRIFTED if any resource has drifted. Only properties set in the template are compared,
and not every resource type supports detection.
Detection reports; it doesn't repair. Either undo the manual change, make the template say the same and update the
stack, or create a drift-aware change set (--deployment-mode REVERT_DRIFT), which previews and then overwrites the
drift to match the template. The lasting fix is a process one: changes go through the template and the pipeline, and console write access to
production is kept narrow.
Describe it in your own words
Drawing every nail of a plan by hand is slow, and you'd draw the same fiddly parts again and again. So you get a CDK: a kit of ready-made designs, like "a safe shed with a lock and a spare key", so you can describe the house in your own words.
A draughtsman turns your description into the full, detailed plan the foreman expects. Before anything is built, they compare the new plan with the last plan the foreman built from, and tell you what would change. Then they hand the plan to the same foreman as before. The foreman never knows the difference.
The AWS CDK
The AWS Cloud Development Kit lets you define infrastructure in a programming language (TypeScript, Java, Python, C#, Go) and synthesizes it into a CloudFormation template. CloudFormation still does the deploying: change sets, ordering and rollback all work as above.
Code is built from constructs: an App contains Stacks, which contain constructs.
- L1 constructs (
CfnBucket) map one-to-one to CloudFormation resource types. - L2 constructs (
Bucket) add sensible defaults and helpers such asgrantRead, which writes the IAM policy for you. - L3 constructs, or patterns, combine several resources into one architecture.
1import software.amazon.awscdk.App;2import software.amazon.awscdk.CfnOutput;3import software.amazon.awscdk.RemovalPolicy;4import software.amazon.awscdk.Stack;5import software.amazon.awscdk.StackProps;6import software.amazon.awscdk.services.s3.Bucket;7import software.amazon.awscdk.services.s3.BucketEncryption;8import software.constructs.Construct;910public class ShopStack extends Stack {11public ShopStack(final Construct scope, final String id, final StackProps props) {12super(scope, id, props);1314Bucket invoices = Bucket.Builder.create(this, "Invoices")15.versioned(true)16.encryption(BucketEncryption.S3_MANAGED)17.removalPolicy(RemovalPolicy.RETAIN)18.build();1920CfnOutput.Builder.create(this, "InvoicesBucketName")21.value(invoices.getBucketName())22.build();23}2425public static void main(final String[] args) {26App app = new App();27new ShopStack(app, "ShopStack", StackProps.builder().build());28app.synth();29}30}
The CDK CLI drives the workflow:
| Command | Does |
|---|---|
cdk bootstrap | Once per account and region: creates the CDKToolkit stack that holds assets and deploy roles |
cdk synth | Runs the app and writes the templates to cdk.out |
cdk diff | Compares the synthesized template with the deployed stack |
cdk deploy | Uploads assets and deploys the stack through CloudFormation; by default (--require-approval broadening) it asks for approval of changes that widen IAM permissions or security group rules, and fails in CI unless approved |
cdk destroy | Deletes the stack |
Loops, conditionals, classes and unit tests make large setups less repetitive than raw YAML. The catch: the template is
the real contract, so review cdk diff, and remember that renaming a construct's ID changes its logical ID, which
CloudFormation treats as removing one resource and adding another.