StackPractices
advanced By Mathias Paulenko

Complete Guide to Terraform in Production

Operate Terraform safely in production: remote state with native locking, environment isolation, drift detection, CI/CD pipelines that apply reviewed plans, and policy as code.

Introduction

Terraform plans are easy. Operating Terraform is not. The failure modes that hurt teams rarely come from bad HCL — they come from a corrupted state file, two engineers applying at once, a resource someone “quickly fixed” in the AWS console, or a CI pipeline that applies a plan nobody reviewed. This guide is about the operational layer: how to store and lock state safely, how to separate environments, how to detect drift before it compounds, how to build a pipeline where the plan you reviewed is the plan that gets applied, and how to enforce policy so mistakes never reach apply.

Terraform is HashiCorp’s open-source infrastructure-as-code tool: you describe resources declaratively in HCL and providers translate that into cloud API calls. This guide assumes you already write Terraform; if you are still learning module authoring, start with the Complete Guide to Terraform Modules and the broader Terraform best practices guide. What follows picks up where those leave off: everything that happens after terraform init on a shared codebase.

You need Terraform 1.9 or newer for the native S3 state locking used here (1.11+ recommended), an AWS account, and a CI system. Examples use GitHub Actions but translate directly to GitLab CI or Azure DevOps.

Project Structure

The layout that scales worst is the single flat directory with one state file. Anything beyond a solo project needs separation between reusable modules and environment root configurations:

terraform/
├── modules/                  # Reusable, versioned building blocks
│   ├── vpc/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   ├── outputs.tf
│   │   └── versions.tf
│   ├── eks/
│   └── rds/
├── environments/             # One root config per environment
│   ├── staging/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   ├── backend.tf
│   │   └── terraform.tfvars
│   └── production/
│       ├── main.tf
│       ├── variables.tf
│       ├── backend.tf
│       └── terraform.tfvars
├── policies/                 # Sentinel or OPA policies
└── README.md

Two rules make this work. First, each environment directory is a separate root module with its own state file and backend config: terraform apply inside environments/staging can never touch production state. Second, environment directories contain almost no resource logic: they compose modules and pass variables. All the reusable logic lives under modules/, which means staging and production run the same code and differ only in inputs (size, count, CIDR, feature flags), which is the property that makes staging a meaningful rehearsal for production.

flowchart diagram: subgraph env[

The policies/ directory sits outside both because policy is evaluated against plans, not against a specific environment; the same “no public S3” rule should gate staging and production alike.

On repo layout: a single Terraform monorepo like the tree above is the pragmatic default for small teams. One pipeline, atomic cross-module changes, easy ../../modules/ references. It stops scaling when unrelated teams share it (plan output becomes noise, applies block each other on the same lock). The next step is splitting per domain into separate repos with registry-published modules — but don’t do that until the pain is real; premature repo splits multiply pipeline and versioning overhead for no benefit.

Remote State and Locking

Local state is fine for experiments and dangerous anywhere else. A .tfstate file on a laptop cannot be shared, cannot be locked, and leaks plaintext secrets to whoever opens the file. Production state belongs in a remote backend with three properties: encryption at rest, versioning for recovery, and locking so two applies cannot run concurrently.

S3 backend with native locking

Since Terraform 1.10 the S3 backend supports native state locking via lockfiles: a .tflock object written next to the state object. Older setups needed a DynamoDB table (dynamodb_table), which is now deprecated; if you still have one, remove the argument and set use_lockfile = true (keep the table around until every workspace has migrated, then delete it).

# environments/production/backend.tf
terraform {
  backend "s3" {
    bucket       = "sp-terraform-state-prod"
    key          = "production/terraform.tfstate"
    region       = "us-east-1"
    use_lockfile = true
    # encrypt defaults to true with SSE-S3; use kms_key_id for SSE-KMS
    # Assume a dedicated role so state access is auditable
    # assume_role = { role_arn = "arn:aws:iam::123456789012:role/TerraformStateAccess" }
  }
}

Two details worth knowing: each environment uses a different key (or a different bucket entirely for stronger isolation), and state locking is per-key, so staging and production can apply in parallel because they lock different objects.

When a lock is held, any plan or apply from another process fails immediately with a lock error naming the holder. That error is the system working; it means a teammate’s apply is in flight. Resist terraform force-unlock: it exists for locks orphaned by crashed runs, and using it on an active apply lets two processes write state concurrently, which is exactly how state gets corrupted. If a lock looks stale, confirm the run actually died (check CI history) before force-unlocking, then re-run rather than editing state by hand.

For the full copy-paste setup — bucket bootstrap, per-environment keys, workspaces, and the GitHub Actions pipeline — see Store Terraform Remote State in S3 with Locking.

Bootstrapping the state bucket

The state bucket cannot manage itself; it must exist before terraform init runs. Create it once, either by hand, with a separate tiny Terraform config applied from local state, or with your cloud provisioning tool. However you create it, enable versioning and block all public access:

# bootstrap/main.tf — run once, keep state locally or in a separate bootstrap workspace
resource "aws_s3_bucket" "terraform_state" {
  bucket = "sp-terraform-state-prod"

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_s3_bucket_versioning" "terraform_state" {
  bucket = aws_s3_bucket.terraform_state.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_public_access_block" "terraform_state" {
  bucket                  = aws_s3_bucket.terraform_state.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

Versioning is your rollback path: if an apply corrupts state, you restore the previous object version instead of rebuilding by hand. Treat the state file itself as a secret: it contains resource IDs, IPs, and often database passwords in plaintext. Restrict the bucket IAM policy to the CI role and the humans who need it, and never commit *.tfstate or *.tflock files to git.

Working with existing state

Day two of any real deployment is surgery on existing state. The commands below are the ones you will actually use:

# Import an existing resource into state
terraform import aws_s3_bucket.logs sp-app-logs-prod

# Import into a module address
terraform import module.rds.aws_db_instance.main prod-db-01

# Inspect and modify
terraform state list
terraform state show module.rds.aws_db_instance.main
terraform state mv aws_instance.old aws_instance.web   # rename without rebuild
terraform state rm aws_instance.deprecated             # stop managing, keep resource

# Download state — contains plaintext secrets, keep the file out of git
terraform state pull > backup.tfstate

Two habits prevent most state accidents. Always terraform state pull a backup before state mv/rm on production; one wrong address is unrecoverable otherwise. And prefer moved blocks in configuration over state mv for refactors that ship through CI, because the move is then versioned and reviewed like any other change (the modules guide covers that refactoring workflow in detail).

Environments and Workspaces

Workspaces (terraform workspace) store multiple states under one backend configuration. They look tempting for environment separation and are the wrong tool for it: every workspace shares the same backend, the same variables, and the same code, so terraform workspace select prod followed by apply is one typo away from destroying production with staging’s variable values.

Separate directoriesWorkspaces
State isolationSeparate files/backends — fullSame backend, same IAM — none
Different variablesPer-env tfvarsShared or manual switching
Different IAM per envYes (different backend role)No
Blast radiusLimited to that envA wrong select hits any env
Best forstaging vs productionEphemeral/preview envs

The rule: directories (or separate AWS accounts) for long-lived environments, workspaces for short-lived, structurally identical ones — PR preview environments, developer sandboxes, ephemeral test rigs:

# Workspaces shine for identical, disposable environments
terraform workspace new pr-1234
terraform apply -var="name_prefix=sp-pr1234"
terraform destroy
terraform workspace delete pr-1234

# terraform.workspace interpolates into names
# bucket = "sp-app-${terraform.workspace}"

For production, separate AWS accounts per environment are even better than separate directories: the blast radius stops at the account boundary and IAM is cleanly scoped. A common layout is one account per environment under AWS Organizations, with a state bucket in each account and a CI role that can only assume into the account it deploys to. If multi-account is not feasible yet, separate state files plus a production-only IAM role for applies gets you most of the isolation at a fraction of the overhead.

Composing Modules per Environment

Environment roots stay thin: declare providers, set default_tags, and wire modules together. Version pins matter more in the environment layer than anywhere else; an unpinned provider or module source turning over silently is a classic cause of “works in staging, broke in prod”.

# environments/production/main.tf
terraform {
  required_version = ">= 1.9"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.80"
    }
  }
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = {
      Project     = "stackpractices"
      Environment = "production"
      ManagedBy   = "terraform"
      Owner       = "platform-team"
    }
  }
}

module "vpc" {
  source = "../../modules/vpc"

  name_prefix        = "sp-prod"          # example name — use your own prefix
  cidr_block         = "10.10.0.0/16"
  availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"]

  tags = { CostCenter = "platform" }
}

module "eks" {
  source = "../../modules/eks"

  name_prefix     = "sp-prod"
  vpc_id          = module.vpc.vpc_id
  subnet_ids      = module.vpc.private_subnet_ids
  cluster_version = "1.33"
  node_groups = {
    general = {
      desired_size   = 3
      min_size       = 2
      max_size       = 6
      instance_types = ["t3.large"]
    }
  }

  tags = { CostCenter = "platform" }
}

default_tags deserves emphasis: tags set at the provider level apply to every taggable resource automatically, which is also how policy checks should read them (they land in tags_all, not tags). Staging mirrors this file with a smaller name_prefix, fewer AZs, smaller instance classes, and ideally a single NAT gateway, since three NAT gateways across AZs run roughly $100/month before data processing. Cost is a legitimate reason to accept single-AZ egress in staging; it is not in production.

Secrets never appear in this file. Database passwords and the like flow in as TF_VAR_* environment variables in CI (shown below) or get read at plan time from a secrets store; see the secrets management guide for the full pattern.

Versioning and Upgrades

Production Terraform rots on three axes: the CLI version, provider versions, and module versions. Pin all three, then upgrade deliberately.

  • CLI: required_version = ">= 1.9" sets a floor; the CI pipeline pins the exact version (terraform_version: "1.9.8") so every run is reproducible. Upgrade the pin in a dedicated PR, run plan, merge. Never let a latest tag pick the version.
  • Providers: ~> 5.80 allows patch releases but not a major jump. AWS provider majors arrive yearly and break resources; review the upgrade guide before relaxing the constraint.
  • Modules: for local ./modules paths, the version is the git commit. For registry or remote sources, pin version = "x.y.z" or a git ?ref=vX.Y.Z. An unpinned module source means tomorrow’s apply silently pulls different code than the one you reviewed.

Provider and module upgrades should land as small, frequent PRs rather than quarterly mega-upgrades. The same is true for CLI versions: each minor Terraform release is easier to adopt than three at once, and staying within a year of current keeps you off deprecated arguments (like dynamodb_table) before they get removed.

Drift Detection

Drift is the gap between your state and reality: a security group opened in the console during an incident, an instance type changed by hand, a bucket made public “temporarily”. Left alone, drift makes the next apply a surprise — Terraform either reverts the manual change or fails on the conflict.

The subtlety most guides get wrong: terraform plan -detailed-exitcode alone does not detect drift. Exit code 2 means “the plan is non-empty”, which includes changes from your own code that haven’t been applied yet. A nightly job that runs plain plan will fire “drift” alerts every time a PR merges before its apply runs. To detect drift specifically, refresh state against the real infrastructure without evaluating new configuration:

# exit 2 here means reality changed vs state — actual drift
terraform plan -refresh-only -detailed-exitcode

A scheduled job around that command catches out-of-band changes within a day:

# .github/workflows/drift-detection.yml
name: Terraform Drift Detection
on:
  schedule:
    - cron: "0 8 * * *"   # daily, 08:00 UTC
  workflow_dispatch:

permissions:
  id-token: write
  contents: read

jobs:
  drift-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/GitHubTerraformPlan
          aws-region: us-east-1

      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: "1.9.8"

      - name: Detect drift
        working-directory: terraform/environments/production
        run: |
          terraform init -input=false
          set +e
          terraform plan -refresh-only -detailed-exitcode -out=refresh.tfplan
          CODE=$?
          set -e
          if [ $CODE -eq 2 ]; then
            terraform show -no-color refresh.tfplan | head -100
            echo "::warning title=drift::Infrastructure drifted from Terraform state"
            exit 1
          fi
          exit $CODE

The job fails the workflow on drift, which is what you want: a red check that someone must acknowledge. Pipe the terraform show output into Slack or an issue if the team lives there.

Remediation is a decision, not an automatic fix. If the manual change was legitimate (an emergency fix), import it or encode it in configuration and let the next apply keep it. If it was an accident, terraform apply converges reality back to code. Either way, resolve drift before the next planned apply; applying onto unknown drift is how outages happen.

Worth stating plainly: staging drift matters less than production drift, but it matters. A staging environment that has silently diverged stops being evidence that the production plan is safe, which defeats the point of having it.

CI/CD Pipeline

The two invariants of a sane Terraform pipeline: the plan reviewed in the PR is the plan applied after merge, and production applies require a human gate. The classic bug is running apply against a fresh plan: the code may have changed between PR review and merge, and the reviewed plan is thrown away.

flowchart diagram: PR[

The pipeline below enforces both invariants: plan runs on PRs and on pushes to main, always uploading plan.tfplan; apply downloads that exact artifact and applies it. No re-planning, no drift between review and execution. AWS credentials use OIDC (role-to-assume) instead of long-lived access keys stored as secrets.

# .github/workflows/terraform.yml
name: Terraform Pipeline
on:
  pull_request:
    paths: ["terraform/**"]
  push:
    branches: [main]
    paths: ["terraform/**"]

permissions:
  id-token: write      # OIDC
  contents: read
  pull-requests: write # plan comments

concurrency:
  group: terraform-production
  cancel-in-progress: false   # never interrupt an apply

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: "1.9.8"
      - run: terraform fmt -check -recursive
        working-directory: terraform
      - run: terraform init -input=false -backend=false && terraform validate
        working-directory: terraform/environments/production

  plan:
    needs: validate
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/GitHubTerraformPlan
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: "1.9.8"
      - run: terraform init -input=false
        working-directory: terraform/environments/production
      - run: terraform plan -no-color -out=plan.tfplan
        working-directory: terraform/environments/production
        env:
          TF_VAR_db_password: ${{ secrets.TF_DB_PASSWORD }}
      - uses: actions/upload-artifact@v4
        with:
          name: terraform-plan
          path: terraform/environments/production/plan.tfplan
          retention-days: 5   # plan files can contain secrets — keep retention short

  apply:
    needs: plan
    if: github.ref == 'refs/heads/main' && github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: production   # required reviewers gate this job
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/GitHubTerraformApply
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: "1.9.8"
      - uses: actions/download-artifact@v4
        with:
          name: terraform-plan
          path: terraform/environments/production
      - run: terraform init -input=false
        working-directory: terraform/environments/production
      - run: terraform apply -no-color plan.tfplan
        working-directory: terraform/environments/production
        env:
          TF_VAR_db_password: ${{ secrets.TF_DB_PASSWORD }}

Three details worth copying exactly. concurrency with cancel-in-progress: false prevents a second apply from queueing behind or interrupting the first (with state locking it would fail anyway, but the explicit group makes the behavior visible). The environment: production job pauses for a required reviewer, which is your human gate. And terraform apply plan.tfplan applies the saved plan file; Terraform refuses if the plan is stale, which is precisely the guarantee you want. Note the plan artifact itself can contain sensitive values, hence short retention and a plan-time role (GitHubTerraformPlan) that can read but not write.

The OIDC trust on the AWS side is a one-time setup: create an IAM OIDC provider for token.actions.githubusercontent.com and scope each role’s trust policy to the repo and ref (repo:org/repo:ref:refs/heads/main for apply, pull_request for plan). No AWS access keys ever touch CI secrets — the plan role should have read-only permissions plus state access, and only the apply role gets write.

Policy as Code

Manual plan review does not scale and humans miss things. Policy as code evaluates every plan against rules (required tags, no public buckets, encryption on) and fails the pipeline before apply. There are two mainstream options:

  • Sentinel is HashiCorp’s policy language. It only runs inside HCP Terraform and Terraform Enterprise (plus sentinel CLI for testing), not in the open-source CLI. If your setup is S3 backend + GitHub Actions, Sentinel policies will never execute; skip to OPA.
  • Open Policy Agent (OPA / Conftest) is open-source and evaluates terraform show -json plan.tfplan output anywhere, including the pipeline above.

Corrected Sentinel policy. Note strings.has_prefix (there is no starts with operator), null-safe tag checks with else, and both create and update actions:

# policies/sentinel/require-tags.sentinel
import "tfplan/v2" as tfplan
import "strings"

mandatory_tags = {"Project", "Environment", "ManagedBy", "Owner"}

aws_resources = filter tfplan.resource_changes as _, rc {
    strings.has_prefix(rc.type, "aws_") and
    rc.change.actions contains "create" or
    rc.change.actions contains "update"
}

main = rule {
    all aws_resources as _, rc {
        all mandatory_tags as t {
            # default_tags land in tags_all; resources may have no tags at all
            (rc.change.after.tags_all else {}) contains t
        }
    }
}

For public S3, checking acl on aws_s3_bucket is wrong: since provider v4 the ACL lives in a separate aws_s3_bucket_acl resource, and the real control is aws_s3_bucket_public_access_block. Policy should require that resource to exist with all four flags true for every bucket, or check tfconfig for the block. A simpler OSS alternative that works in the pipeline above without HCP Terraform is a native check block (Terraform 1.5+):

# Fails plan/apply if the bucket's public access block isn't fully locked down
check "s3_no_public_access" {
  assert {
    condition = aws_s3_bucket_public_access_block.app.block_public_acls &&
                aws_s3_bucket_public_access_block.app.restrict_public_buckets
    error_message = "S3 bucket must block all public access."
  }
}

For anything beyond a handful of assertions, OPA against the JSON plan is the production-grade OSS route: terraform show -json plan.tfplan | conftest test -p policies/ - drops straight into the plan job, and Rego policies live next to the Terraform they govern. It pairs naturally with the IaC review checklist — policy handles the mechanical rules, the checklist covers the judgment calls.

Whichever engine you pick, write policies that fail loudly and specifically. “Tag Owner is required on aws_s3_bucket.logs” gets fixed in minutes; “policy violation” gets ignored until someone digs. And keep the rule set small and stable: a policy suite nobody can satisfy without a wiki open trains teams to bypass it.

What Works

  • Separate state per environment, separate IAM per environment. The production apply role should not be assumable by a staging pipeline.
  • Refresh-only drift checks on a schedule, alerting into wherever the team already looks, never auto-remediation.
  • Apply the artifact you reviewed. Any pipeline that plans twice (once for review, once for apply) will eventually apply an unreviewed diff.
  • prevent_destroy on state-critical resources: state buckets, KMS keys, production databases. Deleting them is a bad day either way.
  • default_tags at the provider instead of repeating tag merges in every resource: cheaper to enforce and easier to audit in cost reports.

Common Mistakes

  • Using workspaces for prod vs staging. Same backend, same variables, one workspace select away from disaster. Directories or accounts.
  • Detecting “drift” with plain plan. You get alerts for unapplied code changes, not real drift, and people learn to ignore them.
  • Re-planning at apply time. If the artifact from the PR isn’t what you apply, review is theater.
  • Committing state or tfvars. *.tfstate, *.tflock, *.tfvars, plan.tfplan all belong in .gitignore; they carry plaintext secrets.
  • Ignoring Sentinel’s platform requirement. Sentinel files in a repo backed by OSS CLI + GitHub Actions are dead code; use OPA or check blocks there.
  • state mv/rm without state pull first. A backup is one command; a mistyped address is unrecoverable.

See Also

Frequently Asked Questions

Should I use workspaces or separate directories for environments?

Directories for long-lived environments. Each gets its own state file, backend config, and tfvars, so a staging apply can't touch production. Workspaces share one backend and one variable set: fine for ephemeral, structurally identical environments like PR previews, wrong for prod-vs-staging isolation. For maximum isolation, separate AWS accounts per environment beat both.

How do I handle secrets in Terraform?

Never in tfvars or HCL: secrets land in state in plaintext either way. Pass them as TF_VAR_* environment variables from CI secrets, mark variables and outputs sensitive = true, and read them at plan time from AWS Secrets Manager or Vault where possible. Encrypt the state bucket and restrict its IAM policy: the state file itself is a secrets store.

What is Terraform drift and how do I detect it?

Drift is when real infrastructure diverges from state: someone edited a resource in the console, an autoscaler changed a count. Detect it with terraform plan -refresh-only -detailed-exitcode: exit code 2 then means reality changed, not just "plan non-empty" (which includes unapplied code changes). Run it on a schedule and alert on exit 2. Remediate deliberately: encode legitimate manual changes into config, or apply to converge back.

Should I use HCP Terraform or a self-managed backend?

HCP Terraform gives you managed state, remote runs, Sentinel policies, run history, and RBAC out of the box, worth it for teams that need audit trails and approval workflows. Self-managed S3 with use_lockfile costs almost nothing and works well for small teams; you pay in operational overhead instead of license fees. Many teams start self-managed and migrate when governance requirements grow.

How do I prevent destructive changes?

Layer the defenses: lifecycle { prevent_destroy = true } on state-critical resources, plan review in PRs, a required-approvals environment gate before production applies, and policy checks (Sentinel/OPA/check) that flag delete actions on protected resource types. For zero-downtime replacements, create_before_destroy, with care, since it briefly doubles the resource.

Can I run terraform apply without a saved plan?

You can, but in CI you shouldn't. apply without a plan file re-plans and immediately applies whatever it computes, skipping the reviewed output. terraform apply plan.tfplan applies exactly the reviewed plan and fails if it's stale, which is the safety property the whole pipeline is built around.