Skip to content

Lesson 22 of 30Infrastructure as code

Infrastructure as Code: Choosing a Tool

Desired state, plans, drift and state files, how CloudFormation really deploys, and how to pick between Terraform, OpenTofu, CDK and the rest.

15 min read0/5 questions

Staging works and production does not. After two hours you find the reason: someone added a security group rule to staging in the console last March, and nobody wrote it down. This is the problem infrastructure as code solves. When every queue, bucket, role and firewall rule lives in reviewed code, "what is different between staging and prod?" becomes a git diff, and "who opened port 22?" becomes git blame. So far you have built most resources one at a time with the console and the CLI. This lesson builds the mental model every IaC tool shares, shows how CloudFormation deploys under CDK and SAM, and gives you a way to choose a tool that you can defend in a design review.

Three ways to build infrastructure

There are three ways to create cloud resources, and most teams have used all three.

Click-ops is the console. It is fine for learning and for looking around. It fails in production because nothing records what you did, nothing reviews it, and you cannot create an identical copy for staging.

Scripts call the API in order: aws sqs create-queue, then aws iam create-role, and so on. This is imperative: you describe the steps. Run the script twice and the second run fails, because the queue already exists. Change one setting and you need a new script that knows how to update instead of create. Scripts only describe how to get from nothing to something.

Declarative IaC describes the end result: "there is a queue called shop-emails with a 60 second visibility timeout." The tool compares that desired state with what exists and works out the steps itself. That gives you three properties scripts lack:

  • Idempotency. Applying the same code twice changes nothing the second time.
  • A plan before apply. The tool shows exactly what it will create, change, replace or destroy, and a human reviews it.
  • Drift detection. If someone edits a managed resource by hand, the next plan shows the difference and offers to put it back.

Every tool in this lesson (CloudFormation, CDK, Terraform, OpenTofu, Pulumi) is a version of the same loop: read the desired state, read the current state, compute a diff, apply it.

The reconcile loop every IaC tool runs
Your code: desired stateYour codedesired stateState: what the tool managesStatewhat the tool managesAWS APIs: what really existsAWS APIswhat really existsPlan / change set: + ~ -/+ -Plan / change set+ ~ -/+ -Reviewer: reads the diffReviewerreads the diffApply: calls the APIsApplycalls the APIsrefreshcomparereviewapprovecreate, updaterecord

You write what should exist. You never write the steps to get there.

1/5

The loop in thirty lines

Here is that loop as a toy. FORCES_REPLACEMENT stands in for properties AWS cannot change on a live resource. You cannot rename an S3 bucket, for example, so a new name means delete and create.

Pythonplanner.py
import copy # Properties AWS cannot change on a live resource. Changing one means replace.FORCES_REPLACEMENT = {"name"} # What the code says should exist.desired = { "bucket.site": {"name": "shop-web-prod", "versioning": True}, "db.orders": {"name": "orders", "size": "large"}, "queue.emails": {"name": "shop-emails", "timeout": 60},} # What the tool manages, as it really is right now (state, refreshed).actual = { "bucket.site": {"name": "shop-site-prod", "versioning": True}, "db.orders": {"name": "orders", "size": "medium"}, "queue.emails": {"name": "shop-emails", "timeout": 60}, "queue.legacy": {"name": "shop-legacy", "timeout": 30},} def plan(desired, actual): actions = [] for addr in sorted(desired.keys() | actual.keys()): want, have = desired.get(addr), actual.get(addr) if have is None: actions.append(("+", addr, "create")) elif want is None: actions.append(("-", addr, "destroy")) else: changed = sorted(k for k in want if want[k] != have.get(k)) if not changed: continue if any(k in FORCES_REPLACEMENT for k in changed): actions.append(("-/+", addr, f"replace ({', '.join(changed)} forces it)")) else: actions.append(("~", addr, f"update in place ({', '.join(changed)})")) return actions def apply(actions, desired, actual): for symbol, addr, _ in actions: if symbol == "-": del actual[addr] else: actual[addr] = copy.deepcopy(desired[addr]) def show(title, actions): print(title) for symbol, addr, why in actions or [("", "", "No changes. Infrastructure matches the configuration.")]: print(f" {symbol:<4}{addr:<14}{why}") first = plan(desired, actual)show("Plan 1:", first)apply(first, desired, actual)show("Plan 2 (run it again):", plan(desired, actual)) actual["queue.emails"]["timeout"] = 900 # someone edits it in the consoleshow("Plan 3 (after a console change):", plan(desired, actual))
Output
Press Run (⌘ Enter) to see what happens.

Three lessons hide in that output. Deleting queue.legacy from the code destroys it, because a managed resource missing from the code means "should not exist". Renaming the bucket is a replace, and a replace of anything holding data is a data-loss event unless you planned for it. And the second plan is empty: that is idempotency.

Predict the outputPython

What does this print?

desired = {"queue.emails": 60, "queue.orders": 30}
state = {"queue.emails": 60, "queue.orders": 30}
account = dict(state)

account["queue.orders"] = 300   # console edit to a managed queue
account["queue.debug"] = 30     # clicked together, never imported

def refresh(state, account):
  return {k: account[k] for k in state if k in account}

seen = refresh(state, account)
drift = [k for k in sorted(desired) if desired[k] != seen.get(k)]
print(drift, "queue.debug" in seen)
Need a nudge? Hints walk you through it.

CloudFormation: the engine under CDK and SAM

AWS CloudFormation is AWS's own IaC service, and it matters even if you never write a template by hand. AWS CDK and AWS SAM both compile to CloudFormation templates, so every CDK deploy is a CloudFormation deploy, and its failure modes are yours.

The unit is a stack: one template, deployed as a group of resources that are created, updated and deleted together. The state lives inside the CloudFormation service, so there is no state file for you to lose or lock.

  • Change sets are CloudFormation's plan. Create one, read it (each change says whether it is Modify or a Replacement), then execute it. cdk diff and cdk deploy create change sets for you.
  • Rollback on failure. If any resource fails during an update, CloudFormation rolls the whole stack back to the last working version. A half-applied deploy is rare. Terraform does not do this: a failed apply leaves whatever succeeded in place, and you fix forward.
  • UPDATE_ROLLBACK_FAILED is the state you will meet at 2 a.m. The update failed, then the rollback also failed, often because someone deleted a resource by hand or a dependency changed outside the stack. The stack is stuck until you run continue-update-rollback, sometimes telling it to skip the broken resource. Deleting the stack is rarely the right fix when it holds data.
  • Drift detection compares stack resources with reality on request. Unlike Terraform, a normal deploy does not fix drift for properties you did not change, so run drift detection on a schedule.
  • DeletionPolicy: Retain (and UpdateReplacePolicy: Retain) keep a database or bucket when the stack deletes or replaces it. Put it on everything stateful.
  • Stack policies block updates to named resources, such as "never replace the production database". Termination protection blocks deleting the stack itself.
template.yaml (excerpt)
Resources:
  OrdersTable:
    Type: AWS::DynamoDB::Table
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - { AttributeName: pk, AttributeType: S }
      KeySchema:
        - { AttributeName: pk, KeyType: HASH }
aws cloudformation continue-update-rollback --stack-name shop-prod --resources-to-skip OrdersQueue
Quick check
A CDK deploy fails halfway. The rollback then also fails because a Lambda function in the stack was deleted by hand last week. What state is the stack in, and what is the usual way out?
Need a nudge? A hint rules out a wrong answer.

State: who remembers what you built

Every tool needs to map "the thing in my code called orders" to "the real table with this ARN". That mapping is state, and where it lives shapes how you work.

ToolWhere state livesWhat you must manage
CloudFormation, CDK, SAMInside the CloudFormation serviceNothing: AWS stores and locks it
Terraform, OpenTofuA state file in a backend you choose (usually S3)Storage, locking, encryption, backups, access
PulumiPulumi Cloud or your own backend (S3 works)Same as Terraform if self-managed

A Terraform state file is JSON containing every attribute of every managed resource. That includes generated database passwords and secret values in plain text, even if you marked the variable sensitive. Treat the state bucket like a secrets store: encrypted, versioned, tightly scoped IAM, and never in git. The next lesson shows the S3 backend and newer features that keep some secrets out of state.

Two rules hold for every tool. One state per environment (and usually per component), so a bad plan in dev cannot touch prod. And only the tool changes managed resources: every console edit is drift waiting to surprise someone.

Environments: the same code, different inputs

The pattern most companies use is one AWS account per environment (dev, staging, prod), with the same IaC code deployed to each with different inputs: instance sizes, counts, domain names. Separate accounts give a hard blast-radius boundary that IAM inside one account cannot.

  • In CDK each environment is a Stage or a stack instance with its own env (account and Region).
  • In Terraform it is a separate state per environment, either a directory per environment that calls shared modules, or one root module with a different backend key and variables file per environment. Terraform workspaces exist, but many teams avoid them for production separation because they share one backend and credentials.

Promote changes the same way you promote code: merge, apply to dev, apply to staging, approve, apply to prod. If prod is the first place a change runs, you are testing in production.

The tool landscape in 2026

Licenses and ownership: why OpenTofu exists

HashiCorp moved Terraform from the open source MPL 2.0 license to the Business Source License (BSL 1.1) starting with version 1.6 in 2023. You can still use it freely to manage your own infrastructure; the license restricts building competing commercial products. In response, the community forked the last MPL version as OpenTofu, first under the Linux Foundation and now a CNCF project. IBM completed its acquisition of HashiCorp in February 2025. For most companies the license change made no practical difference, but some (especially vendors and those with strict open source policies) moved to OpenTofu. HCL code, providers and modules are largely shared between the two, though new features now land separately in each.

ToolWhat it isWhere you see it
TerraformHCL, huge provider ecosystem (AWS, Cloudflare, GitHub, Datadog...), state fileThe most common IaC skill in job postings; multi-cloud and platform teams
OpenTofuOpen source fork of Terraform, same HCLTeams that want an MPL-licensed Terraform
CloudFormationYAML or JSON templates, AWS-managed stateOlder AWS shops, AWS-provided templates, StackSets across accounts
AWS CDKTypeScript, Python, Java, C# or Go that synthesizes CloudFormationAWS-only product teams who want loops, types and reusable constructs
AWS SAMA CloudFormation shorthand for serverless, plus a local runnerLambda-heavy apps
PulumiReal languages, its own engine and state, many cloudsTeams that want CDK-style code without CloudFormation
CrossplaneCloud resources as Kubernetes custom resourcesKubernetes-centered platform teams
CDK for TerraformCDK-style code generating TerraformDeprecated and archived by HashiCorp in December 2025; do not start new projects on it

The Serverless Framework is still common in older Lambda projects, but it changed its licensing in v4, so check its terms before choosing it for something new.

Quality gates before apply

A plan shows what will change. Static checks catch what should never be written at all. A typical pipeline runs them in this order, failing fast on the cheap checks.

  • Format and lint: terraform fmt -check, tflint (catches invalid instance types, deprecated arguments), cfn-lint for CloudFormation.
  • Policy and security: checkov or trivy config (which absorbed tfsec) for Terraform and CloudFormation, cfn-guard for your own CloudFormation rules, cdk-nag inside CDK synth. They flag public buckets, unencrypted volumes and "Action": "*" policies.
  • Cost diff: Infracost comments on the pull request with the estimated monthly change, so "this adds three NAT gateways" is visible before merge.
  • Plan review: a human reads the plan or change set, with special attention to replaces and destroys.
Put it in order5 steps

Order the checks a pull request with an infrastructure change should pass, from first to last.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Choosing a tool

There is rarely one right answer, so interviewers listen for the reasoning. Work through these questions in order.

  1. What does the team already run? Two IaC tools in one company doubles the expertise you need. Joining an existing Terraform shop and writing CDK is a cost, not a preference.
  2. Is it only AWS? If you also manage Cloudflare DNS, GitHub repositories, Datadog monitors or a second cloud, Terraform or OpenTofu covers them all in one plan. CDK covers AWS (and anything you wrap in a custom resource).
  3. Who writes it? Application developers comfortable in TypeScript or Python often move fastest in CDK, where grants and high-level constructs remove a lot of IAM boilerplate. Platform teams often prefer HCL, because it is deliberately limited and every plan reads the same way.
  4. How much abstraction do you want? CDK can create twenty resources in one line, which is great until you must explain all twenty. HCL is explicit and verbose.
  5. Where should state live? CloudFormation-based tools give you managed state and automatic rollback. Terraform gives you speed (it calls APIs directly) and fine control, at the price of running the state backend.
Match the pairs0/5 matched

Match each team to the tool that fits it best.

Choose an item, then its match on the other side.
Quick check
A teammate says the Terraform state is safe to commit to the repo because all database passwords are marked sensitive = true. What is wrong?
Need a nudge? A hint rules out a wrong answer.
Key terms
desired state
What the code says should exist. The tool works out the steps to make reality match it.
idempotent
Applying the same configuration twice makes no changes the second time.
drift
A difference between a managed resource's real configuration and the code, usually from a manual change.
change set
CloudFormation's preview of what a stack update will add, modify, replace or remove.
UPDATE_ROLLBACK_FAILED
A CloudFormation stack whose update and rollback both failed. Fixed with continue-update-rollback.
DeletionPolicy: Retain
A CloudFormation setting that keeps a resource when its stack deletes or replaces it.
state file
Terraform's JSON record mapping code addresses to real resources and their attributes, secrets included.