Skip to content

    System Design

    Infrastructure as Code with Terraform: Plans, State and Modules

    Learn how Terraform turns infrastructure into reviewed code: declarative configuration, plan and apply, remote state and locking, modules, drift and import.

    By Published 12 min read

    Share

    Standard lessonintermediateBackend System Design

    Before this: Docker and Containers

    What you'll learn: By the end of this lesson you will be able to explain what infrastructure as code changes about operating a system, describe how Terraform turns a declarative configuration into a plan and then into changes, say what the state file is for and why it needs a remote, locked and encrypted home, split a system into modules and separate states, and recover safely when someone changes infrastructure by hand.

    A restaurant opens a second branch. If the first kitchen was built by a contractor who took verbal instructions, nobody can say exactly what was built, and the second kitchen will differ in ways that surface only on a busy night. If the first kitchen was built from architect's drawings, the second is a matter of re-reading the drawings, and a proposed change can be reviewed on paper before anyone picks up a hammer.

    Infrastructure as code (IaC) is the drawings. This lesson teaches the one tool the course uses for it, Terraform. Containers, which this lesson assumes, are covered in the Docker lesson, and the pipeline that runs Terraform is the CI/CD lesson; both are named in plain text because they are written alongside this one.

    Verified on 2026-12-01 against the Terraform documentation at developer.hashicorp.com (pages that show a version showed 1.17.x). No Terraform command was run and no cloud account was used: every configuration and command below is shown as not run.

    The core idea

    Terraform keeps three things in step: the configuration you wrote (the desired state), the real infrastructure, and a recorded map between them (the state). A plan is the difference, and apply carries it out. The configuration files are declarative: the Terraform introduction says they "describe the end state of your infrastructure", and Terraform works out the steps. It reaches each platform through a provider, a plugin that talks to that platform's API, and it builds a resource graph so that independent resources can be changed in parallel while dependent ones go in order.

    Three illustrations run through the lesson, each labelled:

    • Minimal example: the write, plan, apply loop on a built-in resource that needs no cloud.
    • Realistic example: ShopStream split into modules and separate states per environment.
    • Failure example: a console edit made during an incident, and the next apply that undoes it.
    Terraform: configuration, state and a provider talking to a cloud APIConfiguration to Terraform CLI (desired state); Terraform CLI to State (read and write); Terraform CLI to Provider plugin (create, update, destroy); Provider plugin to Cloud API (API calls)Configuration: reviewed in version controlConfigurationreviewed inversion controlTerraform CLI: plan, then applyTerraform CLIplan, then applyState: remote, locked, encryptedStateremote, locked,encryptedProvider pluginProviderpluginCloud API: real infrastructureCloud APIrealinfrastructuredesired stateread and writecreate, update, destroyAPI calls

    Figure 1. The moving parts. How to read this: the configuration says what should exist. The CLI compares it with the state, a record of what Terraform manages, and asks the provider to make the cloud API match. Nothing talks to the cloud except through a provider.

    The workflow: write, plan, apply

    The introduction describes the loop as write, plan and apply. In plan, Terraform "creates an execution plan describing the infrastructure it will create, update, or destroy" by comparing the configuration with what exists. On approval, apply performs the operations in dependency order. The plan command alone does not carry out any change.

    A plan proposes four kinds of action, all from the resource behaviour page: create what is configured but missing, update in place when the remote API allows it, destroy and re-create when an argument cannot be updated in place, and destroy what is in the state but no longer in the configuration. The third kind is the dangerous one: a harmless-looking edit can replace a database, which is why you read the plan and not only the diff of the code.

    Illustration 1: the minimal example

    terraform_data is a built-in resource: it takes no action of its own, stores an input value in the state, and needs no provider. It is enough to show the loop with no cloud account. Not run:

    terraform {
      required_version = ">= 1.10.0" # illustrative minimum
    }
    
    variable "revision" {
      type    = number
      default = 1
    }
    
    resource "terraform_data" "release_marker" {
      input = var.revision
    }

    Run terraform init to install providers and modules, then terraform plan to see the proposed actions, then terraform apply. Because this was not run, no plan output is shown. Inputs are declared with variable blocks and read as var.<NAME>. A value can be set with -var, a .tfvars file or a TF_VAR_ environment variable; command-line values beat *.auto.tfvars, which beat terraform.tfvars, which beat environment variables, which beat the default.

    sequenceDiagram accTitle: Plan then apply a saved plan in automation accDescr: A pipeline runs terraform plan with an output file and a reviewer inspects it. After approval the pipeline runs terraform apply with the saved plan file, which carries out exactly those operations without prompting again. The state is read during the plan and updated by the apply. participant P as Pipeline participant T as Terraform participant S as State participant C as Cloud API P->>T: plan, write to a plan file T->>S: read current state T->>C: refresh real objects T-->>P: proposed changes Note over P: a person reviews and approves P->>T: apply the saved plan file T->>C: create, update, destroy T->>S: record the result

    Figure 2. Plan, review, apply. How to read this: the plan is a document you can review before anything changes. Applying the saved file carries out those operations; the page says it does so "without prompting you for confirmation", so the approval must happen before it.

    Two command-line facts matter in automation. With -out, a plan is written to an opaque file that apply can execute. That file holds the full configuration and values, and sensitive data is saved in it in cleartext, so treat it as sensitive. And -detailed-exitcode makes plan return 0 for no changes, 1 for an error and 2 for changes present, which lets a scheduled job detect drift.

    State: the map that makes plans possible

    Terraform's state maps each resource in the configuration to the real object it manages, tracks metadata, and speeds up planning on large infrastructures. By default it is a local terraform.tfstate file. The documentation says not to edit it by hand (use terraform state commands), warns that the format is JSON that may change between versions (read it through terraform show -json or terraform output -json), and states a one-to-one rule: each configured resource instance maps to exactly one remote object, and you must keep that true when you import or remove bindings.

    State needs three protections that a local file does not give you.

    • Sharing and locking. A backend says where state lives; the default is local, and a remote backend lets several people and pipelines use the same state. Terraform locks state during any operation that could write it, so that others cannot acquire the lock and "potentially corrupt" it. -lock=false is not recommended, and force-unlock should be used with great care because unlocking while someone else holds the lock could cause multiple writers. Not every backend supports locking.
    • Secrets. If you put a secret in configuration, Terraform stores it in the state and plan files. Marking a variable sensitive only hides it from CLI output: the page states it is still stored in state, and anyone who can read the state can read it. The recommendation is to treat state as sensitive: store it remotely, encrypt it at rest, restrict access and audit it. Ephemeral values and write-only arguments exist to keep a value out of state.
    • Recovery. For the S3 backend the documentation "highly recommended" enabling bucket versioning so state can be recovered after accidental deletion.
    Two writers, one remote state, one lockEngineer to Lock (acquire); Pipeline to Lock (acquire); Lock to Remote state (read and write)Engineer: plan on a laptopEngineerplan on a laptopPipeline: apply from mainPipelineapply from mainLock: one writer at a timeLockone writer at atimeRemote state: encrypted, versionedRemote stateencrypted,versionedacquireacquireread and write

    Figure 3. State locking. How to read this: while the engineer's operation holds the lock, the pipeline's attempt (red, dashed) is refused instead of racing and corrupting the state. The pipeline retries or fails; it does not write.

    A remote backend is declared in the terraform block, one per configuration, with static values only (a backend block cannot refer to input variables). For the S3 backend bucket, key and region are required, encrypt turns on server-side encryption of the state and lock files, and use_lockfile = true enables S3-based locking through a .tflock object next to the state. The older DynamoDB locking arguments are documented as deprecated. Not run:

    terraform {
      backend "s3" {
        bucket       = "shopstream-tfstate-example" # illustrative name
        key          = "staging/network/terraform.tfstate"
        region       = "eu-west-1"                  # illustrative
        use_lockfile = true
        encrypt      = true
      }
    }

    After changing a backend you run terraform init again, and Terraform offers to migrate existing state; back up terraform.tfstate first.

    Versions, providers and the lock file

    A configuration should say which Terraform CLI versions can run it (required_version) and which providers it needs (required_providers, each with a source and a version constraint). The ~> operator "allows only the right-most version component to increment": ~> 1.1 permits 1.2 and 1.10 but not 2.0. The documentation advises root modules to use ~> to bound each provider, and reusable modules to state only minimum versions.

    terraform init also writes .terraform.lock.hcl, which records the exact provider versions chosen, with checksums. Commit it so a version change goes through review; terraform init -upgrade deliberately ignores it and picks the newest allowed versions. The lock file tracks only providers, not modules, so pin third-party module versions yourself.

    Modules and how to split state

    A module is a collection of resources managed together. The directory you run in is the root module; a module block calls a child module, and Terraform manages its resources as part of the configuration. The block's source can be a local path, a registry or a version-control address; the version argument works only for registry sources; inputs are arguments of the block, and outputs are read as module.<label>.<output>. Run terraform init again after changing a source or version. for_each creates several instances from one block.

    Illustration 2: the realistic example

    ShopStream (the grocery marketplace from the project lessons) needs the same network and order database in staging and production. Each environment is its own root configuration with its own state, calling shared modules. Not run:

    # environments/staging/main.tf
    module "network" {
      source      = "../../modules/network"
      environment = "staging"
    }
    
    module "orders_database" {
      source      = "../../modules/orders-database"
      environment = "staging"
      subnet_ids  = module.network.private_subnet_ids # an output this module defines
    }

    The module names, inputs and the output are this lesson's own design, not a published module. The point is the shape: the interface is a few inputs and outputs, and the resources behind it can change without touching the callers. Separate states also limit the blast radius: a mistake in staging cannot plan changes to production, and a lock on one environment does not block the other.

    Drift, import and guard rails

    Drift is real infrastructure that no longer matches what Terraform recorded, usually because someone changed it by hand. Plan refreshes the state against reality, so drift appears as a proposed change that would put things back. terraform plan -refresh-only instead creates a plan whose goal is only to update the state, which the documentation says is useful when resources were changed outside Terraform, for example during incident response. -refresh=false ignores external changes and can give an incomplete plan.

    To bring an existing object under management, write a matching resource block and an import block giving the address and the provider-specific ID; terraform plan -generate-config-out can draft the resource block. Importing is also how you start with infrastructure someone built by hand.

    Guard rails live in the lifecycle block. prevent_destroy makes Terraform reject plans that would destroy the object, but the documentation is explicit that it does not stop destruction if you remove the resource block. create_before_destroy builds the replacement first. ignore_changes skips named attributes when planning updates. Not run:

    resource "aws_db_instance" "orders" {
      # arguments omitted
      lifecycle {
        prevent_destroy = true
      }
    }

    Before a plan, terraform fmt -check -recursive reports unformatted files, and terraform validate checks syntax and internal consistency without contacting remote systems; it needs an initialised directory (terraform init -backend=false avoids touching the backend).

    flowchart TD accTitle: What to do when a plan shows an unexpected change accDescr: A decision flow. If the plan shows a change nobody wrote, run a refresh-only plan to see the drift. If the manual change was right, copy it into the configuration so plan shows nothing. If it was wrong, apply to revert it. If the plan proposes replacing a stateful resource, stop and find the argument that forces replacement. S["Plan shows a change nobody wrote"] --> Q1{"Does it replace a
    stateful resource?"} Q1 -->|yes| R1["Stop. Find the argument that
    forces replacement, before any apply"] Q1 -->|no| Q2{"Was it a manual edit
    outside Terraform?"} Q2 -->|no| R2["Read the diff: a code or
    version change caused it"] Q2 -->|yes| Q3{"Was the manual edit right?"} Q3 -->|yes| R3["Copy it into the configuration,
    then plan shows no change"] Q3 -->|no| R4["Apply to revert it,
    and close the console path"]

    Figure 4. Reading an unexpected plan. How to read this: check for replacement of anything with data first, because it is the only branch that can lose data. Then decide who is right, the code or the console.

    Trade-offs

    Choice Gain Cost
    Infrastructure in code Review, history, repeatable environments A new skill; state to protect
    Remote state with locking Safe shared use; no two writers A backend to secure and back up
    One state for everything Simple to start Large blast radius; slow plans; one lock
    Many small states Isolation; faster plans Cross-state references to manage
    Shared modules One tested definition reused A module version becomes a dependency
    Apply from a pipeline only Audited, consistent credentials Slower emergency fixes; drift pressure
    prevent_destroy Blocks accidental deletion Does not stop removal of the block

    Build it

    This lesson has no lab. Terraform, a cloud account and a hosted backend are not available here, and a model of Terraform would only restate its documentation. Every block above and the commands below were not run. Run them yourself against a throwaway account, starting with Illustration 1, which needs no cloud.

    In practice: staging and production from one set of modules

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's first environment was clicked together in a cloud console. Resilience work needs a second environment that matches it, and a review of the first has found nobody can list exactly what exists. All numbers here are illustrative.

    Starting architecture

    One environment, built by hand, with a wiki page of steps that is two months out of date. Engineers can change anything from the console.

    Options considered

    Option Gain Cost Wrong when
    A. Keep the console and improve the wiki No new tooling The page drifts again Environments must match
    B. Modules, one state per environment and layer, applied by a pipeline Repeatable, reviewed, isolated Import work; state to run The team cannot own the pipeline
    C. One root configuration and one state for everything Simplest layout One lock and one blast radius More than one team applies

    The decision

    Option B. A network and a data layer per environment, each with its own state in a remote, encrypted, versioned backend with locking. Plans run on pull requests; apply runs from the main branch from a saved plan, after approval, in the pipeline described in the CI/CD lesson. Secrets stay out of configuration, as the secrets lesson explains.

    Rollout and verification

    Import existing resources first, and require terraform plan to show no changes before anything else is merged. Build staging from the modules and compare it with production by hand once. Only then change production through the pipeline. Add a scheduled plan -detailed-exitcode that alerts on exit code 2.

    The 2 a.m. failure

    During an incident an engineer widens a firewall rule from the console. The page clears. At 10:00 the next pipeline apply reverts the rule and the incident returns.

    sequenceDiagram accTitle: A console edit during an incident is reverted by the next apply accDescr: An engineer edits a firewall rule in the console to stop an incident. Terraform's state still holds the old rule. The next pipeline apply plans a change to restore the configured rule and applies it, so the incident resumes. A refresh-only plan would have shown the drift first. participant E as Engineer participant C as Cloud console participant T as Terraform pipeline E->>C: widen firewall rule by hand Note over C: incident clears, state is now stale T->>C: refresh and plan T->>C: apply, restores the configured rule Note over C: incident returns

    First checks: read the plan that the pipeline ran, then run terraform plan -refresh-only to see the drift as the documentation describes it. Mitigation: re-apply the manual fix, but through the configuration. Follow-up: write incident edits into code the same day, and make the scheduled drift check page someone.

    Architect's notes

    • Read the plan, not the pull request. A small code change can replace a database; only the plan says so.
    • Treat state as a secret store. Encrypt it, restrict it, version the bucket, never commit it.
    • Split states by blast radius and by who applies. Not by the number of files.
    • Pin and commit. Provider constraints in code, .terraform.lock.hcl in version control.
    • Emergency console edits are allowed, un-recorded ones are not.

    Common mistakes

    • One state for the whole company. One lock, one failure domain.
    • Believing sensitive = true keeps a value out of state. It does not.
    • Editing the state file by hand. Use the terraform state commands or an import block.
    • -lock=false or force-unlock as a habit. Both risk multiple writers.
    • Floating provider versions. A new release changes a plan with no code change.
    • Applying an unreviewed plan. -auto-approve skips the human checkpoint.

    Key takeaways

    • IaC turns infrastructure into reviewed, versioned configuration; Terraform compares it with a state and applies the difference.
    • Plan shows create, update in place, destroy and replace; read it for replacements.
    • State maps config to real objects, can hold secrets, and belongs in an encrypted, versioned, locked remote backend.
    • Modules package resources; separate states limit blast radius.
    • Drift is found by plan; -refresh-only records it, and the fix is either code or revert.
    • Commit the dependency lock file and pin versions.

    Practice exercises

    Exercise 1 (30 min). Write the Illustration 1 files in a scratch folder and run init, plan and apply. Record what the plan says before and after you change revision, and describe the action Terraform chose.

    Exercise 2 (45 min). For ShopStream, list its environments and layers and decide the state boundaries. For each boundary name who applies and what one failed lock would block.

    Exercise 3 (45 min). Write a pipeline outline with fmt -check, validate, plan -out, approval and apply of the saved plan. Say where credentials come from and which step is allowed to write state.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments