Filter concepts by levelShowing all levels.

AWS · Infrastructure as Code

Infrastructure as Code

The principle, CloudFormation fundamentals, CDK and Terraform, and picking one tool deeply

  • The code is the artifacta hand-made change is drift, not a fix
  • Read the Replacement columna rename can be a delete plus a create
  • CDK generates CloudFormationreview the synthesized diff, not just the code
  • Terraform state is yours to protectremote backend, locking, encryption

1.Reproducible and Reviewable Infrastructure

Infrastructure as code means the definition of your infrastructure lives in version control, and changes reach production by changing that definition. Two properties follow. Reproducible: you can rebuild the environment from the file, in another Region or another account. Reviewable: a change is a diff someone can read before it happens, not an action someone took in a console.

Key features

  • The artifact is the code, not the running resource — a resource changed by hand no longer matches its definition, which is drift
  • Reproducibility is what makes a second environment cheap: staging is the same template with different parameters, not a hand-rebuilt copy
  • Reviewability moves the safety check before the change: a diff and a change set are read while the production resource is still untouched
  • CloudFormation compares the modified template against the original and generates a change set listing the proposed changes
  • A change set does not tell you the update will succeed — it will not catch a quota you are about to exceed, an unsupported update, or missing permissions
  • IaC also produces an audit trail for free: who proposed the change, who approved it, and what exactly it altered are all in the version history
Two ways to change production

Console change

  • Reviewed after the fact, if at all
  • Reproducible only from memory
  • Rollback means remembering the old value
  • Environments drift apart silently

Infrastructure as code

  • Reviewed as a diff before it applies
  • Rebuildable in another account or Region
  • Rollback is reverting a commit
  • Drift is detectable, because there is a definition to compare against
  • Console change
    • Reviewed after the fact, if at all
    • Reproducible only from memory
    • Rollback means remembering the old value
    • Environments drift apart silently
  • Infrastructure as code
    • Reviewed as a diff before it applies
    • Rebuildable in another account or Region
    • Rollback is reverting a commit
    • Drift is detectable, because there is a definition to compare against

Signature

definition in version control → reviewed diff → applied → reality matches definition (else: drift)

Infrastructure as code buys two things: reproducibility (rebuild it elsewhere from the file) and reviewability (read the diff before it applies). Both depend on the code being the only path to production — otherwise the definition drifts into fiction.

2.CloudFormation Fundamentals

A CloudFormation template is a YAML or JSON file describing the AWS resources you want. A stack is what you get when you deploy one: the related resources managed as a single unit, created, updated, and deleted together. To change a running stack you submit a modified template, and a change set shows you what CloudFormation intends to do before it does it.

Key features

  • A template is a YAML or JSON text file CloudFormation uses as a blueprint; a stack is the collection of resources it provisions, managed as one unit
  • Parameters supply values at deploy time (instance class, environment name); Mappings are static lookup tables (AMI id per Region); Outputs export values other stacks can import
  • Intrinsic functions build values at deploy time — `!Ref` for a resource or parameter, `!GetAtt` for an attribute, `!Sub` for string interpolation, `!If` with Conditions
  • A change set is a summary of proposed changes, and its most important column is whether a resource will be replaced rather than modified in place
  • A change set does not predict success — it will not catch an account quota, a resource that does not support the update, or missing IAM permissions
  • Nested stacks compose a large system out of templates; stack policies protect named resources during an update; drift detection reports resources whose live configuration no longer matches the template

Template sections and what each is for

Template sections and what each is for
SectionPurposeTypical content
ParametersValues supplied at deploy timeEnvironment name, instance class, VPC id
MappingsStatic lookup tables resolved at deploy timeAMI id per Region, CIDR per environment
ConditionsWhether a resource or property applies`IsProd: !Equals [!Ref Env, prod]`
ResourcesThe only required section`AWS::EC2::Instance`, `AWS::RDS::DBInstance`
OutputsValues to show, or export for other stacksALB DNS name, database endpoint
Updating a stack safely

Edit the template

The change is a reviewable diff in version control

Create a change set

CloudFormation compares modified against original

Read the Replacement column

"True" on a database means data loss unless handled

Execute, or discard and try again

You can create as many change sets as you need

On failure, CloudFormation rolls back

It restores the last known working state

  1. Edit the template — The change is a reviewable diff in version control
  2. Create a change set — CloudFormation compares modified against original
  3. Read the Replacement column — "True" on a database means data loss unless handled
  4. Execute, or discard and try again — You can create as many change sets as you need
  5. On failure, CloudFormation rolls back — It restores the last known working state

Signature

template { Parameters, Mappings, Conditions, Resources, Outputs } → stack · change set before update

Template (YAML/JSON blueprint) → stack (resources managed as one unit). Parameters vary per deploy, Mappings are static lookups, Outputs cross stack boundaries. Always create a change set for production, and read the Replacement column. Split stacks by how often the resources change.

3.AWS CDK Concepts

The AWS CDK lets you define infrastructure in a general-purpose programming language instead of YAML. You compose constructs — objects representing one or more AWS resources — into stacks, and stacks into an app. Running `cdk synth` turns all of that into a CloudFormation template, which is what actually gets deployed. CDK is a generator; CloudFormation is still the engine.

Key features

  • Constructs come in three layers: L1 maps one-to-one onto CloudFormation resources, L2 wraps those with sensible defaults, L3 (patterns) composes several resources into one architectural shape
  • An app is the root construct and contains one or more stacks; a CDK stack maps onto a CloudFormation stack
  • `cdk synth` performs synthesis — turning the code into a CloudFormation template — and `cdk deploy` deploys that template
  • Assets are local files or Docker images bundled with the app and uploaded to S3 or ECR as part of deployment
  • Context is key-value data used to look up environment information or pass configuration into constructs, and is cached so synthesis stays deterministic
  • A stack's environment is its target account and Region — without an explicit `env` it is environment-agnostic and cannot use account-specific lookups — and a construct you write and share is the reuse mechanism that copying template fragments never gave you

The three construct layers

The three construct layers
LayerWhat it isReach for it when
L1 (Cfn*)A direct, generated mapping of a CloudFormation resourceA property is not yet exposed by a higher layer
L2A curated wrapper with defaults, helper methods, and IAM grantsAlmost always — this is the intended level
L3 (patterns)Several resources composed into one architectural shapeThe pattern matches what you actually want, exactly

Command

javascript
// An L2 construct: sensible defaults, still one CloudFormation stack underneath
const queue = new sqs.Queue(this, 'OrderJobs', {
  visibilityTimeout: Duration.seconds(300),
  encryption: sqs.QueueEncryption.KMS_MANAGED,
});

// Environment: account + Region, needed for account-specific lookups
new ApiStack(app, 'ApiProd', {
  env: { account: '111122223333', region: 'eu-west-1' },
});

CDK generates CloudFormation. Constructs (L1 raw, L2 curated, L3 patterns) compose into stacks, stacks into an app, and `cdk synth` produces the template that is actually deployed — so `cdk diff` and the change set, not the code diff, are what you review before production.

4.Terraform Concepts

Terraform is a cloud-agnostic IaC tool. A provider teaches it how to talk to a platform (the AWS provider, for example); resources describe what you want; modules package a set of resources for reuse. The piece with no CloudFormation equivalent is state: a file Terraform keeps that maps your configuration to the real objects it created, and which you have to store and protect deliberately.

Key features

  • State stores the bindings between objects in a remote system and the resource instances declared in your configuration, and Terraform uses it to decide which changes to make
  • By default state is a local `terraform.tfstate` file; HashiCorp recommends a remote backend or HCP Terraform for team use
  • HashiCorp explicitly warns against storing state in a version control system or anything else without state locking and secure access control
  • State can contain secrets, so the backend holding it needs the same access control as any other sensitive store — on AWS, an S3 bucket with encryption and a locking mechanism
  • `terraform plan` produces the proposed change list (the counterpart of a CloudFormation change set); `terraform apply` executes it
  • A refresh before planning is how Terraform notices drift, and workspaces give one configuration several independent states — which suits per-developer or per-branch environments better than separating staging from production

Terraform and CloudFormation, term by term

Terraform and CloudFormation, term by term
TerraformCloudFormationNote
Configuration (`.tf` files)TemplateBoth declarative
`terraform plan`Change setBoth show intent before applying
`terraform apply`Create/update stackTerraform has no automatic rollback on partial failure
ModuleNested stackModules are the more ergonomic of the two
State file (yours to store)Managed by CloudFormationThe main operational difference
ProviderBuilt in to the serviceOne Terraform configuration can span AWS plus other platforms

Command

text
# The everyday loop
terraform init      # download providers, configure the backend
terraform plan      # what would change, and why
terraform apply     # make it so

Providers + resources + modules describe the infrastructure; `plan` then `apply` changes it. The distinctive part is state — Terraform's record of what it created, which you must store in a locked, encrypted remote backend, because concurrent applies corrupt it and it can contain secrets.

5.Choosing One IaC Tool, Deeply

CloudFormation, CDK, and Terraform all solve the same problem, and the difference between knowing one of them well and knowing three of them shallowly is large. Depth is what lets you read a failed deployment, understand why a resource is being replaced, and recover a broken stack. Breadth is worth having as vocabulary, so you can read someone else's repository — not as a second toolchain in your own.

Key features

  • The depth that matters is failure handling: reading a rollback, recovering a stack stuck mid-update, importing an existing resource, moving a resource between stacks
  • CloudFormation fits an all-AWS estate with no extra tooling to run, and is what CDK produces anyway
  • CDK fits teams who want real language constructs, reusable typed components, and tests over their infrastructure definitions
  • Terraform fits estates spanning AWS plus other platforms, and teams already invested in its module ecosystem
  • Mixing tools per resource is what creates the worst failures — two tools that each believe they own a resource will fight over it on every apply
  • Whichever you pick, the properties that make it work are the same: code is the only path to production, changes are reviewed as a diff, and drift is detected rather than assumed absent

Choosing a primary tool

Choosing a primary tool
SituationPrimary toolReason
All-AWS, small team, no existing IaCCloudFormationNothing extra to install, run, or secure
All-AWS, application developers own the infrastructureCDKReal language, typed reusable constructs, testable
AWS plus other platforms, or an existing module libraryTerraformOne configuration language across providers
A team already fluent in one of themThat oneFluency in failure handling outweighs tool features

Command

text
# One owner per resource — the rule that prevents the worst outcome
network/     -> Terraform
application/ -> Terraform      # not CDK; do not split ownership per resource
data/        -> Terraform

Pick one tool and get deep enough to handle failures — stuck updates, imports, moves, replacements. Learn the other two well enough to read a repository. Never let two tools own the same resource, or every apply becomes a correction of the last one.

Remember

  • A change set shows what will change, not whether the update will succeed — quotas and permissions are not checked.
  • Set `DeletionPolicy: Retain` on databases, buckets, and log groups before the stack reaches production.
  • Split stacks by how often their resources change, not by what they are.
  • One tool owns each resource. Two owners means every apply undoes the last one.

Pro tip

  • An emergency console change is fine — not backporting it into the template is what breaks things, because the next deploy silently reverts it.
  • Depth in one tool means failure handling: recovering a stuck update, importing a resource, moving one between stacks. That is what you need at 3am.

Next up

  • CI/CD on AWS
  • ECS Deployment Architecture
  • Operational Excellence

Sources

  • How CloudFormation works — docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html
  • AWS CDK core concepts — docs.aws.amazon.com/cdk/v2/guide/core_concepts.html (fetch returned a summarized rendering; see the CDK concept's header note)
  • Terraform state — developer.hashicorp.com/terraform/language/state
  • Checked against official documentation 2026-08-29

Spotted a mistake on this page? Tell us.