Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 37 ยท Workflows and Collaboration

Terraform in CI/CD: Plan on Pull Request, Apply on Merge

Automate Terraform with GitHub Actions: plan on pull requests, apply on merge, short-lived OIDC credentials, approvals, plan comments, Atlantis and HCP Terraform.

Running terraform apply from a laptop works until the second teammate arrives. Then you get "who applied that?", different provider versions, long-lived admin keys on personal machines and no review of what actually changed. The answer is the same as for application code: run Terraform in CI/CD, where every change is reviewed, every run is logged and credentials are controlled.

The standard flow is: open a pull request, a job runs plan and posts it; reviewers read the code and the plan; after merge a job applies the reviewed change.

flowchart LR
  PR["Pull request"] --> J1["CI: fmt, validate, tflint, plan"]
  J1 --> C["Plan posted as comment"]
  C --> RV{"Review and approve"}
  RV --> M["Merge to main"]
  M --> J2["CI: apply (protected environment)"]
  J2 --> ST["Remote state updated"]

The plan is part of the review, and only the pipeline can write state.

A pull request workflow

The following GitHub Actions file runs on pull requests. It is read-only here: workflows cannot run on this site.

YAML
name: terraform-plan
on:
  pull_request:
    paths: ["infra/**"]

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

jobs:
  plan:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: infra/envs/prod
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.9.5
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::111111111111:role/terraform-plan
          aws-region: eu-central-1
      - run: terraform fmt -check -recursive
      - run: terraform init -input=false
      - run: terraform validate
      - id: plan
        run: terraform plan -input=false -lock-timeout=5m -no-color -out=tfplan
      - run: terraform show -no-color tfplan > plan.txt
      - uses: actions/upload-artifact@v4
        with:
          name: tfplan
          path: infra/envs/prod/tfplan

An apply workflow runs on push to main, uses a protected GitHub environment (so a human must approve) and a role with write permissions. Because plans can drift between the PR and the merge, many teams re-plan on merge and apply that fresh plan. Others apply the saved plan artifact, accepting that a stale plan will fail safely.

Credentials: use OIDC, not stored keys

Do not paste cloud access keys into CI secrets. Use OpenID Connect: the CI provider issues a short-lived signed token for each job, and the cloud exchanges it for temporary credentials. In AWS you create an IAM role whose trust policy only accepts tokens from your repository and branch, for example repo:acme/infra:ref:refs/heads/main for the apply role and repo:acme/infra:pull_request for a read-only plan role. Azure and GCP offer the same idea (federated credentials, workload identity).

Separate roles also let you give the PR plan job read-only permissions: it can read state and describe resources but never change them.

Summarizing the plan for reviewers

Reviewers do not want to scroll through 2,000 lines. A short summary at the top of the PR comment helps: counts by action, and a loud warning for destroys and replacements. terraform show -json tfplan gives structured data you can parse. The stand-in below does that for a small plan.

Python Plan summary for a pull request comment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Atlantis and HCP Terraform

You do not have to script everything yourself.

  • Atlantis is a self-hosted server that listens to pull request webhooks. You comment atlantis plan and atlantis apply; it runs Terraform, posts output and locks the directory or workspace per PR so two PRs cannot apply over each other. A repository file (atlantis.yaml) maps folders to projects.
  • HCP Terraform (formerly Terraform Cloud) runs plans and applies remotely, stores state and variables, offers policy checks, drift detection and a private registry. A VCS-driven workspace plans on every PR automatically.
  • OpenTofu works with the same approaches; GitHub Actions use opentofu/setup-opentofu, and Atlantis supports it with a flag.
  • Many teams also use Spacelift, env0 or Scalr, which offer similar features as hosted platforms.

Safe pipeline rules

  1. Pin versions: Terraform, providers (lock file) and module versions.
  2. One apply at a time per state: use backend locking and a CI concurrency group so runs queue instead of fail.
  3. Protect main: require review and passing checks before merge.
  4. Gate production: a manual approval on the apply job.
  5. Least privilege: plan role read-only, apply role scoped to what the project needs.
  6. Mask secrets: -no-color, no TF_LOG=TRACE output in logs (trace logs contain tokens).
YAML
concurrency:
  group: terraform-prod
  cancel-in-progress: false

Setting cancel-in-progress: false matters: cancelling an apply mid-flight can leave the state locked and resources half-created.

Python Pipeline gate checklist

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is OIDC preferable to storing cloud keys in CI secrets?

    Short-lived federated tokens cannot be reused after the job and are scoped by trust policy.
  2. 2. What should the pull-request plan job be able to do?

    A read-only role limits damage if a PR from a fork or a bug triggers unexpected behavior.
  3. 3. What does Atlantis do?

    Atlantis is a self-hosted pull request automation server for Terraform and OpenTofu.
  4. 4. Why set cancel-in-progress to false for apply jobs?

    Let a running apply finish; queue later runs instead.

Summary

  • Run Terraform in CI: plan on pull requests, apply after merge, state written only by the pipeline.
  • Use OIDC with separate read-only plan and scoped apply roles; avoid stored keys.
  • Post a short plan summary and flag destroys and replacements for reviewers.
  • Atlantis, HCP Terraform and similar platforms provide this workflow ready-made.
  • Pin versions, queue runs with concurrency groups and gate production with approvals.

Next: Testing, Policy and Security Scanning