TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท infrastructure as code ยท devops ยท cdk

AWS CloudFormation and CDK

Infrastructure as code on AWS. A CloudFormation template declares resources, parameters and outputs; CloudFormation creates them as one stack in dependency order, previews updates as change sets, rolls back on failure and detects drift. The CDK generates those templates from TypeScript, Java, Python and other languages.

14 min6 animations

๐Ÿ“š Builds on๐Ÿญ CI/CD

๐Ÿ–จ๏ธ Cheat sheet

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:

SectionHolds
ResourcesThe only required section: each resource has a logical ID, a Type such as AWS::S3::Bucket, and Properties
ParametersInputs supplied at deploy time, such as Env
OutputsValues the stack exposes after deploying, such as an endpoint or ARN, optionally exported for other stacks
Mappings, ConditionsLookup tables, and switches that include resources or properties only in some cases
1AWSTemplateFormatVersion: "2010-09-09"2Parameters:3  Env:4    Type: String5    AllowedValues: [dev, prod]6Resources:7  InvoicesBucket:8    Type: AWS::S3::Bucket9    Properties:10      Tags:11        - Key: env12          Value: !Ref Env13Outputs:14  InvoicesBucketArn:15    Value: !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.

๐Ÿ”ง Going deeper

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.

From template to stack4 steps
๐Ÿ—„๏ธ Plan drawer๐Ÿง‘You๐Ÿ‘ทForeman
Press play and watch it happen!

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 !Ref or !GetAtt (or !Sub with a reference) on another, the referenced resource is created first, and deleted last.
  • Explicit dependencies: DependsOn forces an order when there is no reference, for example a route to an internet gateway, which needs the gateway's VPCGatewayAttachment to 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.

Ordering by dependencies5 steps
๐Ÿ‘ทForeman๐ŸŒฑPlot๐ŸงฑFoundation๐Ÿ”‘Door lock๐Ÿ”Strongroom๐Ÿ”จWorkshop
Press play and watch it happen!

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.
๐Ÿ”ง Going deeper

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.

Previewing an update6 steps
๐Ÿก The house๐Ÿง‘You๐Ÿ‘ทForeman๐Ÿ›–Shed๐Ÿ”Strongroom
Press play and watch it happen!

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_COMPLETE and 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_COMPLETE and 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.

๐Ÿ”ง Going deeper

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.

Rolling back a failed update4 steps
๐Ÿก The house๐Ÿง‘You๐Ÿ‘ทForeman๐Ÿ›–Shed
Press play and watch it happen!

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.

Detecting drift4 steps
๐Ÿก The house๐Ÿง‘You๐Ÿง‘โ€๐Ÿ”งHelper๐Ÿ‘ทForeman๐Ÿ›–Shed๐Ÿ”Strongroom
Press play and watch it happen!

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 as grantRead, 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;9 10public class ShopStack extends Stack {11    public ShopStack(final Construct scope, final String id, final StackProps props) {12        super(scope, id, props);13 14        Bucket invoices = Bucket.Builder.create(this, "Invoices")15                .versioned(true)16                .encryption(BucketEncryption.S3_MANAGED)17                .removalPolicy(RemovalPolicy.RETAIN)18                .build();19 20        CfnOutput.Builder.create(this, "InvoicesBucketName")21                .value(invoices.getBucketName())22                .build();23    }24 25    public static void main(final String[] args) {26        App app = new App();27        new ShopStack(app, "ShopStack", StackProps.builder().build());28        app.synth();29    }30}

The CDK CLI drives the workflow:

CommandDoes
cdk bootstrapOnce per account and region: creates the CDKToolkit stack that holds assets and deploy roles
cdk synthRuns the app and writes the templates to cdk.out
cdk diffCompares the synthesized template with the deployed stack
cdk deployUploads 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 destroyDeletes 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.

From CDK code to a stack3 steps
๐Ÿก The houseโœ๏ธ Your description๐Ÿง‘โ€๐ŸŽจDraughtsman๐Ÿ‘ทForeman
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about AWS CloudFormation and CDK, told the same way as the story.
  1. The plan says the workshop needs to know where the strongroom is. What does the foreman do?
  2. The change list says the strongroom would be knocked down and rebuilt. Why does that matter?
  3. Halfway through a job, the new workshop's walls won't go up. What do you end up with?
  4. A helper takes out the strongroom's alarm by hand. What does the foreman's check do about it?
  5. You describe a safe shed in your own words with the kit. Who actually builds it?
Answer every question to check.Passing marks AWS CloudFormation and CDK as done.
Got the hang of AWS CloudFormation and CDK? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜๏ธ AWS from zeroStep 12 of 12

โ† Previous on the path๐Ÿ›Ž๏ธ Amazon API GatewayLast step ๐ŸŽ‰Back to the path