Subscribe

Running terraform plan on pull requests and apply on merge with GitHub Actions

Part 8 of the shorty series: a GitHub Actions workflow that posts terraform plan as a pull request comment and applies after merge behind an environment approval. Separate OIDC roles for plan and apply, read-only PR plans without the state lock, and why apply plans again.

Running terraform plan on pull requests and apply on merge with GitHub Actions

In the last part the shorty infrastructure went into infra/app and got applied from a laptop. That works when it's one person. It stops working the day two people apply from two laptops with two different versions of the code, or the day someone reviews a pull request that changes a security group without seeing what it will actually do.

In this blog we will move Terraform into GitHub Actions. Every pull request that touches infra/app gets a terraform plan posted as a comment. After merge, the same workflow plans again and applies, but only after someone approves it. AWS access is through OIDC with two separate roles, one that can only read and one that can change things.

This is part 8 of the shorty series. Level is intermediate. You need the S3 state backend from storing Terraform state in S3 with native locking and the GitHub OIDC provider from part 6. Versions: Terraform 1.17.1, AWS provider 6.73.0, hashicorp/setup-terraform@v4, actions/github-script@v9, aws-actions/configure-aws-credentials@v6. I checked the workflow with actionlint and the Terraform with validate and terraform test. It has not run against a real account or a real pull request yet, so if GitHub changes something in the comment API, that's the part I'd look at first.

Two roles, told apart by the sub claim

When a job asks GitHub for an OIDC token, the sub claim in it describes where the job runs. A few examples:

repo:fenixara/shorty:pull_request                 any pull_request event
repo:fenixara/shorty:ref:refs/heads/main          a push to main
repo:fenixara/shorty:environment:production       a job with environment: production

The last one is what makes this design work. A job that declares environment: production gets that sub, no matter which event started it. And GitHub only starts such a job after the environment's protection rules pass, like required reviewers. So I trust the apply role only for environment:production, and the plan role only for pull_request. A pull request can never get the apply role, because its token says pull_request.

Both roles go into infra/bootstrap, the small stack from part 6 that I apply by hand. It has to be by hand only: the roles that let CI run Terraform can't be created by that same CI.

data "aws_iam_policy_document" "tf_plan_trust" {
  statement {
    actions = ["sts:AssumeRoleWithWebIdentity"]
    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }
    condition {
      test     = "StringEquals"
      variable = local.oidc_aud
      values   = ["sts.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = local.oidc_sub
      values   = ["repo:${var.github_repo}:pull_request"]
    }
  }
}

The apply trust is the same block with repo:${var.github_repo}:environment:production.

What the plan role may do

terraform plan refreshes every resource in the state, so it needs to read EC2, ELB, ECS, IAM, ACM, Route 53 and logs. Listing all those read actions by hand is a long afternoon, so I attached the AWS managed ReadOnlyAccess policy, plus read access to the state objects:

resource "aws_iam_role_policy_attachment" "tf_plan_readonly" {
  role       = aws_iam_role.tf_plan.name
  policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}

data "aws_iam_policy_document" "state_read" {
  statement {
    actions   = ["s3:ListBucket"]
    resources = ["arn:aws:s3:::${var.state_bucket}"]
  }
  statement {
    actions   = ["s3:GetObject"]
    resources = ["arn:aws:s3:::${var.state_bucket}/app/*"]
  }
}

There's no s3:PutObject there, and that's on purpose. With S3 native locking, every plan writes a .tflock object next to the state and deletes it at the end. I didn't want pull requests to be able to write anything in the state bucket, not even a lock file. So PR plans run with -lock=false. A plan never writes state, so the only risk is reading the state while an apply is in the middle of saving it. S3 writes whole objects, so you see the old state or the new one, and the worst case is a plan that's one apply out of date. The concurrency group below makes that rare anyway.

Now the uncomfortable bit. See, "read-only" is not "harmless". ReadOnlyAccess can read objects in every S3 bucket in the account, and the plan job runs the workflow file from the pull request's branch. Anyone who can push a branch to this repo can change the plan job to run whatever they want with this role. Terraform providers and external data sources run code during plan too. So treat the plan role as "everything a repo writer may read". In a busy account I would replace ReadOnlyAccess with a narrower list. Securing GitHub Actions workflows goes into the workflow side of this.

What the apply role may do

The apply role gets what infra/app manages and nothing else: ACM, EC2 (VPC and security groups live there), ECS, ELB, CloudWatch Logs, Route 53, and IAM only on the two shorty role names. Plus read and write on the state, including the lock file. It's in iam_terraform.tf in the repo. I won't paste the whole thing, the IAM part is the interesting one:

  statement {
    sid = "OnlyShortyRoles"
    actions = [
      "iam:AttachRolePolicy",
      "iam:CreateRole",
      "iam:DeleteRole",
      "iam:GetRole",
      "iam:PassRole",
      "iam:PutRolePolicy",
      "iam:UpdateAssumeRolePolicy",
    ]
    resources = [
      "arn:aws:iam::*:role/shorty-execution",
      "arn:aws:iam::*:role/shorty-task",
    ]
  }

(The real list has a few more Get, List, Tag and Detach actions that Terraform calls.) If the apply role could create any role and attach any policy, it could make itself admin with one pull request. Limiting IAM to named roles closes that.

Apply both with the bootstrap:

cd infra/bootstrap
terraform plan -out tfplan
terraform apply tfplan
terraform output tf_plan_role_arn
terraform output tf_apply_role_arn

Put those in the repo variables AWS_TF_PLAN_ROLE_ARN and AWS_TF_APPLY_ROLE_ARN.

The production environment

In the repo, Settings, Environments, create production. Add yourself (or the team) as required reviewers, and under deployment branches allow only main. The branch rule matters: without it, a workflow on any branch could ask for the environment, and only the reviewer would stand between that branch and production. GitHub's environment settings have a lot more in them, but that's enough here.

The workflow

.github/workflows/terraform.yml:

name: terraform

on:
  pull_request:
    paths:
      - "infra/app/**"
      - ".github/workflows/terraform.yml"
  push:
    branches: [main]
    paths:
      - "infra/app/**"
      - ".github/workflows/terraform.yml"

permissions:
  contents: read

# One run at a time for this state. Never cancel: a cancelled apply can
# leave the state locked and half the resources changed.
concurrency:
  group: terraform-infra-app
  cancel-in-progress: false

env:
  AWS_REGION: ap-south-1
  TF_IN_AUTOMATION: "1"
  TF_INPUT: "0"

defaults:
  run:
    working-directory: infra/app

jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: read
      id-token: write
      pull-requests: write # to post the plan as a comment

    steps:
      - uses: actions/checkout@v7

      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_version: 1.17.1
          terraform_wrapper: false

      - name: terraform fmt
        run: terraform fmt -check -recursive -diff

      - name: terraform test (mocked AWS, no credentials)
        run: |
          terraform init -backend=false
          terraform validate
          terraform test

      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_TF_PLAN_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}

      - name: terraform plan
        id: plan
        run: |
          terraform init -reconfigure
          set +e
          terraform plan -lock=false -no-color -detailed-exitcode -out=tfplan > plan.log 2>&1
          code=$?
          set -e
          cat plan.log
          echo "exitcode=$code" >> "$GITHUB_OUTPUT"
          if [ "$code" -eq 1 ]; then exit 1; fi
          terraform show -no-color tfplan > plan.txt

      # ... the comment step, below

  apply:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    timeout-minutes: 30
    environment: production # required reviewers are set on this environment
    permissions:
      contents: read
      id-token: write

    steps:
      - uses: actions/checkout@v7

      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_version: 1.17.1
          terraform_wrapper: false

      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_TF_APPLY_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}

      - name: terraform plan
        run: |
          terraform init
          terraform plan -no-color -out=tfplan

      - name: terraform apply
        run: terraform apply -no-color tfplan

Let us go through it.

The paths filter means app code changes don't start Terraform at all. The workflow file itself is in the list, so a change to this YAML gets a plan too.

cancel-in-progress: false is the one setting I'd never change here. For CI on Go code, cancelling the old run when a new commit lands is great. For an apply, cancelling halfway leaves you with some resources changed and possibly a stale lock to clean up. Runs in the group waits in line instead.

The first steps need no AWS access at all. terraform fmt -check fails the PR on formatting. terraform test is the mocked-provider test from part 7, which plans all 30 resources with fake data and checks things like "the ALB health check is /readyz". It runs before credentials step, so a broken change fails fast without ever touching AWS.

I pin terraform_version to the same 1.17.1 I use locally, and I commit .terraform.lock.hcl, so CI uses the same AWS provider build as my laptop. While copying these folders around, init once refused to run with "the cached package ... does not match any of the checksums recorded in the dependency lock file". Deleting .terraform and the lock file and running init again gave back the exact same h1: hash, and it worked. I still don't know why the cached copy didn't match, actually. The lock file was doing its job there, it just isn't very friendly about it.

terraform_wrapper: false: the setup-terraform wrapper runs Terraform through a Node script so it can expose stdout and the exit code as step outputs. I capture the output and exit code myself, so I'd rather have the plain binary and no surprises.

-detailed-exitcode makes plan exit 0 for no changes, 2 for changes and 1 for errors. Bash in Actions runs with -e, so a 2 would fail the step even though it's good news. That's what the set +e dance is for. Only 1 fails the job.

The plan as a comment

The comment step uses github-script, because it can find and update its own earlier comment. Otherwise every push to the PR adds another huge comment and the conversation becomes unreadable.

      - name: Comment the plan on the PR
        if: ${{ !cancelled() && steps.plan.outputs.exitcode != '' }}
        uses: actions/github-script@v9
        env:
          EXITCODE: ${{ steps.plan.outputs.exitcode }}
        with:
          script: |
            const fs = require('fs');
            const marker = '<!-- terraform-plan: infra/app -->';
            const code = process.env.EXITCODE;
            const file = code === '1' ? 'infra/app/plan.log' : 'infra/app/plan.txt';
            let out = fs.readFileSync(file, 'utf8');
            const max = 60000;
            if (out.length > max) {
              out = out.slice(0, max) + '\n... cut, see the job log for the full plan';
            }
            const title = {
              '0': 'No changes',
              '1': 'Plan FAILED',
              '2': 'Changes to apply on merge',
            }[code];
            const body = [
              marker,
              `### Terraform plan, infra/app: ${title}`,
              `Commit ${context.payload.pull_request.head.sha.slice(0, 7)}, [run log](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})`,
              '<details><summary>Show plan</summary>',
              '',
              '```text',
              out,
              '```',
              '</details>',
            ].join('\n');

            const { owner, repo } = context.repo;
            const issue_number = context.issue.number;
            const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
            const old = comments.find(c => c.user.type === 'Bot' && c.body.includes(marker));
            if (old) {
              await github.rest.issues.updateComment({ owner, repo, comment_id: old.id, body });
            } else {
              await github.rest.issues.createComment({ owner, repo, issue_number, body });
            }

The hidden HTML comment is the marker. The script lists the PR's comments, finds the bot's comment with that marker and edits it. If the plan failed, it posts the error log instead, which is usually what the reviewer wants to see anyway.

A GitHub comment can hold about 65,000 characters, so long plans get cut at 60,000 with a pointer to the job log. The plan is inside <details> so the comment stays one line until you click it.

Note steps.plan.outputs.exitcode != '' in the if. If the plan step dies before it writes the exit code (bad credentials, for example), there's no file to post and the step is skipped.

One warning for public repos. Terraform hides values marked sensitive, but anything else in the plan is now in a public comment: IPs, ARNs, account IDs, environment variables in task definitions. shorty's database URL is in SSM and only its ARN shows up, which is fine. Check your own plans before you turn this on in a public repo.

Why apply plans again

It's quite tempting to save tfplan from the PR as an artifact and apply exactly that after merge. I don't, for two reasons. The PR plan was made against the state at that moment; if another PR was merged and applied after it, the saved plan is stale and Terraform refuses to apply it anyway. And a saved plan file contains the full planned values, sensitive ones included, so I'd rather not keep it around as an artifact.

So the apply job plans again from main, with the apply role and with locking on, and applies that plan file right away. What the reviewer approved in the environment is "apply main", and the job log shows the exact plan that ran. If the two plans differ a lot from what was in the PR comment, that's a sign someone changed things outside Terraform. Importing hand-built resources is how I clean that up when it happens.

With required reviewers, the run stops at the apply job with a "Review deployments" button. The reviewer approves, the job starts, and the apply log is right there in the run.

The part I like most

The PR comment itself. A change like "open port 8080 to the ALB" is a three-line diff that looks harmless in review. The plan shows the actual aws_vpc_security_group_ingress_rule that will be created, with the source group, right under the diff. Reviewing infrastructure without that is mostly guessing.

If you also want policy checks on the plan before anyone approves it, catching insecure Terraform with Checkov or Conftest fits in as one more step after the plan. Next part goes back to the app: deploying a new image to the ECS service from GitHub Actions, with the migration first and a rollback when it goes wrong.