All guides

Terraform in pull requests: plan on review, apply on merge

HashiCorp's guide to running Terraform in automation plans to a file and then applies that file. This workflow does the same on GitHub Actions. It plans on every pull request, publishes the plan for the reviewer and applies on the merge to main.

Python code on a screen, seen at an angle

The shape of the workflow

  1. A pull request triggers terraform plan, saved to a file.
  2. The workflow publishes the plan where the reviewer can read it.
  3. The reviewer approves the code and the plan together.
  4. The merge to main plans again and applies that saved plan.

The commands come from HashiCorp's guide to running Terraform in automation: terraform init -input=false, terraform plan -out=tfplan -input=false and terraform apply -input=false tfplan.

Credentials through OIDC

GitHub's guide to OpenID Connect in AWS says OIDC lets a workflow access AWS resources with no AWS credentials stored as long-lived GitHub secrets. The workflow's OIDC token is used to authenticate with a short-lived access token. The id-token: write permission allows the workflow to request the OIDC token.

The same guide says you must define at least one condition on the role's trust policy, so that untrusted repositories cannot request access tokens for your cloud resources. Its example sets the sub condition to one branch, in the form repo:octo-org/octo-repo:ref:refs/heads/octo-branch.

Use two roles. Give the role that can write a sub condition for the main branch. Give pull request runs a second role that can read. With the S3 backend and use_lockfile, that second role also needs s3:GetObject, s3:PutObject and s3:DeleteObject on the lock file.

One workflow for plan and apply

The role names, the account ID, the region, the lock timeout and the concurrency group name are the example's choice.

YAML

on:
  pull_request:
  push:
    branches: [main]

permissions:
  id-token: write
  contents: read

env:
  ROLE: ${{ case(github.event_name == 'push', 'terraform-apply', 'terraform-plan') }}

jobs:
  terraform:
    runs-on: ubuntu-latest
    concurrency:
      group: terraform-${{ github.ref }}
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/${{ env.ROLE }}
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_wrapper: false
      - run: terraform init -input=false
      - run: terraform plan -input=false -lock-timeout=5m -out=tfplan
      - run: |
          {
            echo '```text'
            terraform show -no-color tfplan
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"
      - if: github.event_name == 'push'
        run: terraform apply -input=false tfplan

GitHub's case function returns the value that belongs to the first predicate that evaluates to true, and its last argument when none does. Here it picks the role name from the event.

The last step runs on a push only. It passes the saved plan file to apply, and Terraform performs the operations in a saved plan with no prompt for confirmation.

terraform_wrapper: false leaves out the wrapper script that setup-terraform installs. The wrapper exposes Terraform's output to later steps, and its README says it can be skipped when no later step needs those results.

The plan the reviewer reads

The terraform show step writes the plan to the job summary, which GitHub shows on the summary page of the workflow run. Each step's summary is limited to 1 MiB. If a step adds more, its upload fails and GitHub creates an error annotation.

A saved plan file stores sensitive data in cleartext, even where the terminal output obscures it. HashiCorp says to treat saved plan files as sensitive artifacts. This workflow uploads no artifact.

The run on main creates its own plan and applies that one. It does not reuse the file from the pull request. GitHub's branch protection setting Require branches to be up to date before merging requires a branch to be up to date with the base branch before it merges.

Locking and concurrent runs

If the backend supports it, Terraform locks the state for all operations that could write state. If locking fails, Terraform does not continue. -lock-timeout tells it to retry acquiring the lock for a period before it returns an error. HashiCorp does not recommend -lock=false.

A concurrency group works one level higher. GitHub runs only a single job or workflow in the same concurrency group at a time. By default, an existing pending job in the group is canceled when a new one is queued. For a pull request, github.ref is refs/pull/<number>/merge, so each pull request forms its own group and pushes to main share one.

Tools that run this for you

  • Atlantis describes itself as Terraform pull request automation. It is open source and self-hosted. It attempts to run terraform plan on any new pull request and on any new commit to one, and it takes commands such as atlantis apply as pull request comments. Its locking page says the directory and Terraform workspace stay locked until the pull request is merged or closed.
  • HCP Terraform, in its VCS-driven workflow, runs a speculative plan for each newly opened pull request and adds a link to that plan in the pull request. Its page on remote operations says speculative plans cannot apply any changes. A merge to the workspace's branch queues a run, which requires confirmation unless auto apply is enabled. A run in progress locks its workspace.

What to check first

  • The trust policy of the write role has a sub condition for the main branch.
  • The state is in a backend that supports locking.
  • A test pull request shows its plan on the summary page of the run.
  • main is a protected branch that requires branches to be up to date.
  • No step uploads the plan file.

Sources

Want a second pair of eyes on yours? We do this work for a living.

Book a call

More guides