TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Plan on Pull Request, Apply on Merge

Plan on Pull Request, Apply on Merge

The roadmap's last IaC item is "plan/apply pipelines within CI/CD". The pattern almost every team converges on:

  1. On every pull request: format check, validate, lint, test, then plan against the real environment with read-only credentials, and post the plan to the pull request for review.
  2. On merge to main: apply with write credentials, after an approval for production, serialised so two applies never overlap.
  3. On a schedule: a drift check (Drift & Refresh).

The CI/CD course teaches GitHub Actions and GitLab CI in general; this lesson is the IaC-specific part.

The checks, as one script

A pipeline is easier to trust when the same script runs locally and in CI. This one runs the quality gate, plans, and then applies a policy to the plan JSON: it fails if the plan would delete or replace a database or a state bucket, so such a change needs a deliberate, separate approval. Run here against the offline AWS setup, first with a harmless change, then with a dangerous one:

bash · try it yourself
mkdir -p infra/tests && cd infra
cat > offline.tf <<'HCL'
provider "aws" {
  region                      = "eu-west-1"
  access_key                  = "offline"
  secret_key                  = "offline"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}
HCL
cat > main.tf <<'HCL'
terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

variable "queue_retention" {
  type    = number
  default = 345600
}

resource "aws_sqs_queue" "jobs" {
  name                      = "linkly-jobs"
  message_retention_seconds = var.queue_retention
}
HCL
cat > tests/queue.tftest.hcl <<'HCL'
mock_provider "aws" {}
run "retention_is_four_days" {
  command = plan
  assert {
    condition     = aws_sqs_queue.jobs.message_retention_seconds == 345600
    error_message = "unexpected retention"
  }
}
HCL
cat > ci.sh <<'SH'
#!/usr/bin/env bash
# Usage: ./ci.sh  - the same gate locally and in CI
set -euo pipefail
step() { echo "::: $*"; }

step fmt;      tofu fmt -check -recursive
step init;     tofu init -input=false >/dev/null
step validate; tofu validate | tail -1
step test;     tofu test | tail -1
step plan
set +e; tofu plan -input=false -lock-timeout=5m -detailed-exitcode -out=tfplan >plan.log; code=$?; set -e
[ "$code" -eq 1 ] && { cat plan.log; exit 1; }
grep '^Plan:' plan.log || echo "no changes"

step policy
tofu show -json tfplan > plan.json
dangerous=$(jq -r '.resource_changes[]
  | select(.change.actions | index("delete"))
  | select(.type | test("^aws_(db_instance|rds_cluster|s3_bucket|dynamodb_table)
quot;)) | "\(.change.actions | join("+")) \(.address)"' plan.json) if [ -n "$dangerous" ]; then echo "BLOCKED: this plan deletes or replaces stateful resources:" echo "$dangerous" exit 3 fi echo "policy ok" SH chmod +x ci.sh echo "=== pull request 1: a new queue" ./ci.sh; echo "exit=$?" echo "=== pull request 2: renames the assets bucket (a replacement)" cat >> main.tf <<'HCL' resource "aws_s3_bucket" "assets" { bucket = "linkly-assets-v2" } HCL tofu plan -out=tfplan >/dev/null # offline there is no old bucket in state, so mark it as the replacement a real plan would show tofu show -json tfplan | jq '(.resource_changes[] | select(.type == "aws_s3_bucket") | .change.actions) = ["delete","create"]' > plan.json jq -r '.resource_changes[] | select(.change.actions | index("delete")) | select(.type | test("^aws_(db_instance|rds_cluster|s3_bucket|dynamodb_table)
quot;)) | "BLOCKED: \(.change.actions | join("+")) \(.address)"' plan.json
=== pull request 1: a new queue
::: fmt
::: init
::: validate
Success! The configuration is valid.
::: test
Success! 1 passed, 0 failed.
::: plan
Plan: 1 to add, 0 to change, 0 to destroy.
::: policy
policy ok
exit=0
=== pull request 2: renames the assets bucket (a replacement)
BLOCKED: delete+create aws_s3_bucket.assets

The first pull request passes every step. The second renames a bucket, which on a real account is a replacement; offline there is no old bucket in state, so the session marks the bucket's action as delete+create in the JSON (exactly what show -json reports for a -/+ replacement) and runs the same policy query on it. In a real pipeline the plan JSON comes straight from tofu show -json, and policy engines such as OPA/Conftest or Checkov do the same with richer rule sets (Toolkit).

GitHub Actions

yaml
# .github/workflows/infra.yml
name: infra
on:
  pull_request:
    paths: ["infra/**"]
  push:
    branches: [main]
    paths: ["infra/**"]

permissions:
  contents: read
  id-token: write          # OIDC: exchange the job's token for AWS credentials
  pull-requests: write     # post the plan as a comment

concurrency:
  group: infra-prod        # one run per state at a time; queued, never cancelled mid-apply
  cancel-in-progress: false

defaults:
  run:
    working-directory: infra

jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: opentofu/setup-opentofu@v2
        with:
          tofu_version: 1.13.2
          tofu_wrapper: false
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::123456789012:role/linkly-infra-plan    # read-only
          aws-region: eu-west-1
      - run: ./ci.sh
      - run: tofu show -no-color tfplan > plan.txt
      - uses: actions/upload-artifact@v7
        with:
          name: tfplan
          path: infra/plan.txt
      - name: Comment the plan
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          { echo '<details><summary>OpenTofu plan</summary>'; echo; echo '```'; head -c 60000 plan.txt; echo '```'; echo '</details>'; } > comment.md
          gh pr comment ${{ github.event.pull_request.number }} --body-file comment.md

  apply:
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: production          # required reviewers approve before this job starts
    steps:
      - uses: actions/checkout@v7
      - uses: opentofu/setup-opentofu@v2
        with:
          tofu_version: 1.13.2
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::123456789012:role/linkly-infra-apply   # write
          aws-region: eu-west-1
      - run: tofu init -input=false
      - run: tofu plan -input=false -lock-timeout=5m -out=tfplan
      - run: tofu apply -input=false tfplan

With Terraform, replace the setup step with hashicorp/setup-terraform@v4 (terraform_version: 1.17.0, terraform_wrapper: false) and tofu with terraform.

Design decisions in this workflow:

  • Two IAM roles. The pull-request role can only read (its trust policy allows pull_request events); the apply role can write and trusts only the main branch and the production environment. A malicious pull request can't apply anything. Permissions, OIDC & Pinning by SHA shows the trust-policy conditions; pin third-party actions to commit SHAs in real repositories.
  • Apply re-plans on main. The reviewed plan was made against the PR branch; after merge, other changes may have landed. Re-planning and applying in one job (with the lock held throughout) is simple and safe. The stricter alternative saves the reviewed plan as an artifact and applies exactly that file, failing if it has become stale (init, plan, apply & destroy in Depth).
  • concurrency serialises runs per state on top of state locking.
  • Plan files and logs can contain secrets: keep artifacts short-lived and private.

GitLab CI

yaml
# .gitlab-ci.yml (excerpt)
stages: [check, plan, apply]

default:
  image: registry.example.com/platform/iac-runner:2026.10   # your image: tofu 1.13.2, tflint, jq
  before_script: [cd infra]

check:
  stage: check
  script: [tofu fmt -check -recursive, tofu init -backend=false, tofu validate, tofu test]

plan:
  stage: plan
  id_tokens:
    AWS_ID_TOKEN: { aud: sts.amazonaws.com }
  script:
    - ./ci.sh
    - tofu show -json tfplan > plan.json
  artifacts:
    paths: [infra/tfplan, infra/plan.json]
    expire_in: 1 week
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"

apply:
  stage: apply
  script: [tofu init -input=false, tofu apply -input=false -auto-approve]
  environment: production
  resource_group: infra-prod        # GitLab's way to serialise jobs
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual

GitLab also offers an OpenTofu CI/CD component and a managed Terraform state backend (the http backend) per project.

Pull-request automation tools

Atlantis (self-hosted), HCP Terraform, Spacelift, env0, Scalr and Terrateam run this workflow as a service: plans as PR comments, atlantis apply from a comment, locking per directory, policy checks and drift detection. They are worth it once you have many states; the Toolkit compares them.

Test yourself

Why should the pull-request plan job use a different, read-only IAM role than the apply job?

  1. Plans are faster with read-only roles
  2. So that code in an unmerged pull request can never change infrastructure
  3. AWS requires two roles
  4. Read-only roles can't see state

What does tofu plan -detailed-exitcode return when changes are present, and why does the script handle it?

  1. 0; nothing to handle
  2. 2; with set -e that would abort the script, so it is captured and only 1 is treated as an error
  3. 1; it is an error
  4. 3; a policy failure

What does a GitHub Actions concurrency group add on top of state locking?

  1. Nothing
  2. Runs for the same state are queued instead of failing on the lock or racing between plan and apply
  3. It encrypts the state
  4. It speeds up apply