Terraform in CI: saved plans and approvals

Intermediate · 25 min

Run Terraform from a pipeline with a saved plan, a pinned version, a queue and an approval gate, so the plan a person approved is the one applied.

Before thisState locking and concurrent appliesFormatting, validation and TFLint

HashiCorp, an IBM Company · 25 min

Terraform in CI: saved plans and approvals

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by HashiCorp, an IBM CompanyReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • terraform plan -out saves exact changes and terraform apply on that file runs only them; the file holds the configuration and variables, with sensitive values in cleartext, so protect it.
  • A saved plan is tied to the state and the versions it was made against; applying one plan invalidates other plans for that state, so serialise runs.
  • Pin the same Terraform version in the plan and apply jobs, and gate the apply with a protected environment or approval step.
  • Use -input=false, -lock-timeout and TF_IN_AUTOMATION in pipelines; -detailed-exitcode returns 2 when changes are present.

Who is allowed to press apply

For the first months, terraform apply runs on someone’s laptop. That person has production credentials, a local checkout that may be two commits behind, and a terminal that may still be set to the wrong profile. Nobody else saw the plan. When the apply goes wrong, the only record is a screenshot.

Moving Terraform into CI fixes those three things at once: one place with credentials, a clean checkout of a known commit, and a log of every plan and apply. It also introduces a new problem. The plan a reviewer approved on Tuesday has to be the thing that is applied on Wednesday, even though the repository and the infrastructure kept moving in between.

The two files that make it safe

A saved plan. terraform plan -out=tfplan writes the exact set of changes to a file, and terraform apply tfplan executes that file and nothing else. HashiCorp’s automation tutorial says the plan file contains the full configuration and the variables passed to plan, and the plan docs add that sensitive values inside it are stored in cleartext. Treat it like a secret: store it as a protected artifact, not in a public log.

State, and its lock. A saved plan records the state it was computed against. If anything changes that state in the meantime, the plan is no longer safe to apply. The tutorial puts it plainly: when a plan is applied, any other existing plans produced against the same state are invalidated, and an error is produced if Terraform or its plugins are upgraded between creating and applying a plan. It recommends allowing only one outstanding plan at a time.

I wrote a small stand-in in Python to see what that means in practice. It models the state as a counter that every apply increments, and a plan as the counter value it was made from. It is not Terraform, and Terraform’s own error text will differ. Two pull requests are planned from the same state:

$ python3 -I stale.py
both plans made from serial 41
applied PR-101 bigger instance: state serial 42, web={'size': 'large'}
REFUSED PR-102 add tag: planned against serial 41, state is now 42
applied PR-102 add tag (re-planned): state serial 43, web={'size': 'large', 'tag': 'blue'}

The second plan is refused until it is made again from the new state. That refusal is a feature: PR-102’s reviewer approved a diff against a world that no longer exists. In CI this is why the apply job must either run immediately after the plan job on the same commit, or serialise runs so the queue is plan, approve, apply, then the next plan.

A workflow, in outline

This is a GitHub Actions workflow written from the setup-terraform README and the Terraform CLI docs. I did not run it, and Terraform is not installed here. On 28 November 2026 the latest releases I saw were hashicorp/setup-terraform v4.0.1 and actions/checkout v7.0.1, actions/upload-artifact v7.0.2 and actions/download-artifact v8.0.2, so I use their major tags:

name: terraform
on:
  pull_request:
  push: { branches: [main] }

concurrency: terraform-prod        # one run at a time

permissions: { contents: read, id-token: write, pull-requests: write }

env:
  TF_IN_AUTOMATION: "true"
  TF_INPUT: "false"

jobs:
  plan:
    runs-on: ubuntu-latest
    defaults: { run: { working-directory: envs/prod/app } }
    steps:
      - uses: actions/checkout@v7
      - uses: hashicorp/setup-terraform@v4
        with: { terraform_version: "1.17.2", terraform_wrapper: false }
      - run: terraform fmt -check -recursive
      - run: terraform init -lock-timeout=60s
      - run: terraform validate
      - run: terraform plan -out=tfplan -lock-timeout=60s
      - run: terraform show -no-color tfplan > plan.txt
      - uses: actions/upload-artifact@v7
        with: { name: tfplan, path: envs/prod/app/tfplan }

  apply:
    needs: plan
    if: github.ref == 'refs/heads/main'
    environment: production        # required reviewers gate this job
    runs-on: ubuntu-latest
    defaults: { run: { working-directory: envs/prod/app } }
    steps:
      - uses: actions/checkout@v7
      - uses: hashicorp/setup-terraform@v4
        with: { terraform_version: "1.17.2", terraform_wrapper: false }
      - uses: actions/download-artifact@v8
        with: { name: tfplan, path: envs/prod/app }
      - run: terraform init -lock-timeout=60s
      - run: terraform apply tfplan

What matters in it:

  • terraform_version is pinned to the same version in both jobs. A saved plan will not apply if Terraform or its plugins change between the two, so a floating latest is a trap.
  • concurrency is the queue that keeps a second plan from being made while one waits for approval.
  • environment: production attaches a GitHub Environment, where you can require named reviewers before the job starts. The approval then happens at the apply, with plan.txt visible, not at the code review.
  • -lock-timeout makes a run wait for the state lock for a while instead of failing at once, which suits a queue.
  • terraform apply tfplan has no -auto-approve. Applying a saved plan does not ask for confirmation, because the plan file is the approval. The docs reserve -auto-approve for non-critical infrastructure.
  • Credentials: a long-lived key in a repository secret is the weak spot. OIDC replaces it; that is the next lesson.

The upload and download actions are on different major versions (7 and 8) in that list. Check their release notes that the pair is compatible before copying it.

Plan on pull request

For pull requests, the plan job runs with a read-only role, so that a forked or compromised branch cannot change anything. Post the plan to the pull request as a comment or in $GITHUB_STEP_SUMMARY, because a GitHub comment is limited to 65,535 characters, which the setup-terraform README warns can break a workflow for a large plan. If the plan run uses -detailed-exitcode, exit code 2 means “succeeded, changes present,” 0 means no changes, and 1 an error. That makes it a way to run drift checks on a schedule too, which comes back in drift detection.

What goes wrong anyway

The usual failures are mundane. The plan job and apply job use different Terraform versions. The plan artifact expires before someone approves. An approver clicks through without reading the 800-line plan. A pipeline applies on every merge to main with no gate, because the team was sure about a small change. And a stale lock from a cancelled run blocks everyone, so know the force-unlock procedure before you need it.

About the video

The embed is HashiCorp’s “Terraform and GitHub: Infrastructure as Code meets GitHub Automation and Collaboration”, 25 minutes 21 seconds, published March 2026 and presented by Patrick Koch. Its description says it demonstrates a complete GitHub Flow for managing code changes in a Terraform configuration, discusses best practices, and covers the GitHub tools for collaboration. It is a conference session, so it is vendor-presented and aimed at beginners to the GitHub side. I took its content from the description and did not watch it all, and I judged it English from the title, description, channel and its English auto-caption track. The Spacelift video in deeper, from January 2026, covers setting up Terraform in GitHub Actions and its limits, and is by a vendor that sells an alternative.

Where this fits

A pipeline needs credentials. The next lesson covers how a workflow gets them without storing a key: OIDC from CI to the cloud.

Check yourself

  1. 01Why must the plan and apply jobs use the same Terraform and provider versions?

    Terraform produces an error if Terraform or its plugins are upgraded between creating and applying a saved plan.

  2. 02Two pull requests were planned from the same state and the first one applies. What happens to the second plan?

    It is invalidated because the state changed. It must be planned again from the new state.

  3. 03Why does terraform apply tfplan not need -auto-approve?

    Applying a saved plan file does not prompt, because the file itself is the approved set of changes. Approval belongs before that step.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark