Skip to content

Lesson 12 of 14 · 18m

Terraform in CI: Plan on PR, Apply on Merge

Plan output posted on the PR is the review; OIDC role assumption replaces stored access keys; saved plan files are secrets too.

At some point "who runs terraform apply" stops being "whoever has the repo checked out" and becomes a pipeline question — because laptops hold credentials, laptops go offline mid-apply, and a review process that ends at "someone ran plan on their machine" isn't a process.

The pipeline shape

PR opened  → fmt → validate → tflint/checkov → plan → plan output posted on the PR
PR merged  → apply against the environment backend (serialized by the state lock)
  • terraform fmt -check and validate are the free gates — syntax and schema errors die in seconds.
  • Static analysis — checkov, trivy config, tflint — flags the policy violations humans miss at 200 lines of diff: 0.0.0.0/0 on port 22, unencrypted storage, missing logging. More on the policy layer in its own lesson.
  • terraform plan -out=plan.tfplan in the PR job, output posted as a comment or artifact. Reviewers approve the diff, not the intention.
  • terraform apply plan.tfplan on merge — the saved plan ensures the thing that runs is the thing that was reviewed. -detailed-exitcode lets the apply job skip cleanly when the merge produced no diff.
  • Drift detection runs on a schedule: a nightly plan -detailed-exitcode against prod. Exit code 2 means reality diverged from code — someone clicked, or something changed upstream. That's an alarm, filed automatically.

Atlantis is the open-source tool that productized this workflow — PR comments trigger plan, approval triggers apply, all serialized through the state lock. HCP Terraform, Spacelift, and env0 sell the same shape hosted. The mechanics are identical regardless of vendor: plan on PR, apply on merge, lock prevents concurrent writes.

Authentication: OIDC or go home

The pipeline needs cloud credentials, and the wrong answer is still the common one: a long-lived AKIA... access key stored in GitHub secrets. Stored keys leak — the 2021 Codecov incident exfiltrated CI credentials en masse through a modified bash uploader, and a leaked AKIA key is valid until someone notices.

The right answer is OIDC federation — the CI job exchanges its own signed identity token for short-lived cloud credentials:

# .github/workflows/terraform.yml
permissions:
  id-token: write    # lets the job mint an OIDC token
  contents: read

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

The AWS side is an IAM role with a trust policy on token.actions.githubusercontent.com — scoped to your repo, your branch, sometimes your environment. No stored secrets, credentials that expire in minutes, and a trust policy that says exactly which CI jobs may assume the role. GitLab (id_tokens), CircleCI, and Azure all implement the same OIDC pattern; the role-trust-policy shape is universal.

The artifacts are secrets too

plan.tfplan files contain resolved values — everything apply will see, including masked-in-CLI sensitive attributes. Store them as CI artifacts with the same access controls as state; never commit them. Same for terraform show -json output piped to policy tools — the JSON is a plaintext dump of your intended infrastructure. CI job logs that echo plan output inherit the same exposure.

Who applies, in the end

The pipeline owns the apply; humans own the merge. That separation is the audit trail — every infrastructure change maps to a reviewed PR, a recorded plan, and a logged apply. The laptop path doesn't vanish — terraform import, state surgery, debugging — but routine changes that bypass the pipeline are drift by definition.

Field notes

  • Pin the Terraform version in CI — hashicorp/setup-terraform with terraform_version: 1.12.x — because HCL behavior shifts between minors and your state file is picky about versions.
  • apply jobs should be serialized per environment; the state lock is the enforcement, but pipeline concurrency groups make it orderly instead of racy.
  • A failed apply mid-run leaves resources created and state updated — the next plan continues from where it stopped. Re-running is safe; panicking and clicking is not.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.