Skip to main content

Infrastructure as code · Advanced · 30 min

Plan Relay changes in pull requests and apply them on merge with GitHub Actions

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · OpenTofu 1.13.10 · actionlint 1.7.12 · GitHub Actions

You will have a GitHub Actions workflow that checks, tests and plans every Relay pull request with a read-only AWS role, posts the plan as a comment, and on merge applies that exact saved plan behind a production environment.

On this page

So far every change to Relay has gone from your laptop straight to AWS: you edit, plan, read the plan and apply. That works for one person. It stops working when a second person joins, when you want a record of who changed what, or when the laptop with the admin credentials is lost.

In this part you move that loop into pull requests. When you open one, GitHub Actions formats, validates, tests and plans the change, and posts the plan as a comment so a reviewer reads the real effect, not just the diff. When the pull request is merged, a second job applies the plan file the reviewer saw, not a fresh one, and only after someone approves it in a production environment.

The series builds one environment, the dev stack in dev.tfvars with its state at relay/dev/terraform.tfstate. production here is only the name of the GitHub approval gate that the apply job passes through, not a second, separate stack, so the apply job applying dev.tfvars is intended.

The pieces, all in ~/relay-demo:

  • two AWS roles that GitHub can assume through OIDC, so no access keys are stored anywhere: relay-plan, which can read and nothing more, and relay-apply, which can change Relay's resources
  • four short scripts in ci/ that hold the logic, so you can run the same checks on your laptop
  • one workflow, .github/workflows/relay.yml, with a plan job for pull requests and an apply job for main

Nothing in this part creates AWS resources that bill. The one infrastructure change you make, a lifecycle rule on the assets bucket, reduces storage over time rather than adding to it. GitHub Actions minutes on private repositories count against your plan's allowance.

Step 1 · Put Relay in a GitHub repository

The workflow runs on what is in the repository, so the project needs to be there, without anything that should stay on your machine. Add the ignore rules first. >> appends, so any rules you already have stay, and a repeated line does no harm:

Bash
cd ~/relay-demo
cat >> .gitignore <<'EOF'
# OpenTofu working files and local state
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log
# Written by the CI scripts
plan/
.tofu-plugin-cache/
EOF

Which GitHub plan you are on decides whether the repository can stay private. The apply role in the next step is safe only if GitHub restricts the production environment to the main branch, and on a personal account that setting exists for a private repository only on GitHub Pro or above (Team or Enterprise Cloud for an organisation). Branch protection on a private repository needs the same plans. On GitHub Free you have two choices: upgrade, or create the repository as public, where every plan gets deployment branches, branch protection and required reviewers. Public means anyone can read the code, the plan comments with your resource IDs, and dev.tfvars. Do not go public on Free without reading step 6 first.

The lock files stay in Git on purpose. .terraform.lock.hcl in the root and in modules/network record the exact provider version and its checksums, and CI refuses to run without them, so the provider on the runner is the one you tested with. dev.tfvars is committed too: it holds your SSH address, which is not a secret, but it is one reason to keep the repository private. If you make it public, anyone can see that address, so keep nothing else in it that you would not publish. Never put passwords or keys in a tfvars file.

If ~/relay-demo is not a Git repository yet, create one and make the first commit:

Bash
git init -b main
git add .
git commit -m "Relay infrastructure, parts 1 to 6"

Then create the private repository on GitHub and push to it. gh uses the folder name, so the repository is called relay-demo:

Bash
gh repo create relay-demo --private --source . --push

On GitHub Free, use --public in place of --private, for the reasons above.

Check it worked

git ls-files | grep tfstate prints nothing. git ls-files .terraform.lock.hcl modules/network/.terraform.lock.hcl prints both paths. gh repo view --json visibility prints "visibility":"PRIVATE" (or "PUBLIC" if you chose that on GitHub Free).

Step 2 · Create a read-only plan role and a separate apply role

A plan reads every resource Relay manages. An apply creates and deletes them. Those are different levels of trust, so they get different roles, and each role's trust policy says exactly which GitHub jobs may assume it:

  • relay-plan trusts any pull request job in your repository. That includes a pull request that edits the workflow itself, which is why this role can only read.
  • relay-apply trusts only jobs that run in the production environment, which you limit to main in step 6.

The difference lives in the sub claim of GitHub's OIDC token. A pull request job gets repo:OWNER/REPO:pull_request, and a job that names an environment gets repo:OWNER/REPO:environment:production. The tutorial on deploying to AWS from GitHub Actions with OIDC explains the identity provider, the aud check and why a wildcard in sub is dangerous. Here you write the two policies Relay needs.

Set four values first. Replace each one: your 12-digit account ID, your GitHub user or organisation and repository, and the state bucket and key from part 4:

Bash
ACCOUNT_ID=123456789012              # replace this
REPO=your-github-user/relay-demo     # replace this
STATE_BUCKET=relay-tfstate-123456789012-eu-west-1 # replace with the bucket from part 4
STATE_KEY=relay/dev/terraform.tfstate             # replace with the key from part 4
mkdir -p iam

Write the two trust policies. The heredocs are unquoted so the shell fills in your values:

Bash
cat > iam/plan-trust.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Federated": "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/token.actions.githubusercontent.com" },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:${REPO}:pull_request"
        }
      }
    }
  ]
}
EOF
cat > iam/apply-trust.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Federated": "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/token.actions.githubusercontent.com" },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:${REPO}:environment:production"
        }
      }
    }
  ]
}
EOF

"Read-only" needs one exception. Part 4's backend uses use_lockfile, which writes a small .tflock object next to the state while a plan runs. The plan role gets AWS's ReadOnlyAccess managed policy plus permission to write and delete that one object:

Bash
cat > iam/plan-lock.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "StateLockOnly",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::${STATE_BUCKET}/${STATE_KEY}.tflock"
    }
  ]
}
EOF

The apply role needs to change what Relay manages: EC2 networking and the instance, its own S3 buckets, the instance's IAM role, and the state itself:

Bash
cat > iam/apply-permissions.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    { "Sid": "Ec2", "Effect": "Allow", "Action": "ec2:*", "Resource": "*" },
    {
      "Sid": "RelayBuckets",
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": ["arn:aws:s3:::relay-*", "arn:aws:s3:::relay-*/*"]
    },
    {
      "Sid": "RelayIam",
      "Effect": "Allow",
      "Action": "iam:*",
      "Resource": [
        "arn:aws:iam::${ACCOUNT_ID}:role/relay-*",
        "arn:aws:iam::${ACCOUNT_ID}:instance-profile/relay-*"
      ]
    },
    {
      "Sid": "State",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket"],
      "Resource": ["arn:aws:s3:::${STATE_BUCKET}", "arn:aws:s3:::${STATE_BUCKET}/*"]
    }
  ]
}
EOF
python3 -m json.tool iam/apply-permissions.json > /dev/null && echo "apply-permissions.json is valid JSON"

This is a starting point, not least privilege. iam:* on relay-* roles means anyone who gets a change through review could create a relay- role with wide permissions. That is acceptable in a sandbox account behind a required reviewer; in a shared account, add a permissions boundary or narrow the actions once you know which calls Relay makes. If part 4 left you with an aws_kms key provider instead of a passphrase, both roles also need kms:Encrypt, kms:Decrypt and kms:GenerateDataKey on that key.

Create the roles with the AWS CLI, using an admin profile on your laptop:

Bash
aws iam create-role --role-name relay-plan --assume-role-policy-document file://iam/plan-trust.json
aws iam attach-role-policy --role-name relay-plan --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
aws iam put-role-policy --role-name relay-plan --policy-name relay-state-lock --policy-document file://iam/plan-lock.json
aws iam create-role --role-name relay-apply --assume-role-policy-document file://iam/apply-trust.json
aws iam put-role-policy --role-name relay-apply --policy-name relay-apply --policy-document file://iam/apply-permissions.json

Check it worked

grep sub iam/*-trust.json shows two different subjects, one ending in :pull_request and one in :environment:production, both with your repository. aws iam list-attached-role-policies --role-name relay-plan lists ReadOnlyAccess, and aws iam get-role --role-name relay-apply --query Role.Arn --output text prints the ARN you will give GitHub in step 6.

Step 3 · Write the plan scripts and run them on your laptop

Keep the logic in scripts and the workflow thin. You can run a script on your own machine, and when CI fails you can reproduce it with one command instead of guessing from a log.

ci/plan.sh runs every check in order and stops at the first failure. It ends with a saved plan, the plan as text, and the Git tree ID of the code it planned. That tree ID is what lets the apply job prove later that it is applying the code that was reviewed:

Bash
mkdir -p ci
cat > ci/plan.sh <<'SH'
#!/usr/bin/env bash
# Check, test and plan Relay. Writes the saved plan and its text to plan/.
set -euo pipefail

VAR_FILE="${VAR_FILE:-dev.tfvars}"
OUT_DIR="${OUT_DIR:-plan}"
mkdir -p "$OUT_DIR"
if [ -n "${TF_PLUGIN_CACHE_DIR:-}" ]; then mkdir -p "$TF_PLUGIN_CACHE_DIR"; fi

tofu fmt -check -recursive
tofu init -input=false -lockfile=readonly
tofu validate
tofu -chdir=modules/network init -input=false -lockfile=readonly
tofu -chdir=modules/network test
tofu plan -input=false -lock-timeout=5m -var-file="$VAR_FILE" -out="$OUT_DIR/relay.tfplan"
tofu show -no-color "$OUT_DIR/relay.tfplan" > "$OUT_DIR/plan.txt"
git rev-parse 'HEAD^{tree}' > "$OUT_DIR/tree.txt"
SH
chmod +x ci/plan.sh

-lockfile=readonly makes init fail instead of quietly changing the lock file, so a provider upgrade has to arrive in its own reviewed commit. -lock-timeout=5m waits for another plan or apply to release the state lock rather than failing at once.

ci/comment.sh turns the plan into a pull request comment. A reviewer needs the summary line and the list of resources first; the full plan goes in a collapsed section, cut short if it would pass GitHub's comment size limit:

Bash
cat > ci/comment.sh <<'SH'
#!/usr/bin/env bash
# Build plan/comment.md from plan/plan.txt.
set -euo pipefail

OUT_DIR="${OUT_DIR:-plan}"
PLAN_TEXT="$OUT_DIR/plan.txt"
summary=$(grep -E '^(Plan:|No changes\.)' "$PLAN_TEXT" | head -n 1 || true)
changes=$(grep -E '^  # .* (will|must) be ' "$PLAN_TEXT" || true)

{
  echo "### OpenTofu plan for ${COMMIT_SHA:-your working copy}"
  echo
  echo "**${summary:-No summary line found. Read the full plan.}**"
  echo
  if [ -n "$changes" ]; then
    echo '```text'
    echo "$changes"
    echo '```'
  fi
  echo
  echo "<details><summary>Full plan</summary>"
  echo
  echo '```text'
  head -c 60000 "$PLAN_TEXT"
  echo
  echo '```'
  if [ "$(wc -c < "$PLAN_TEXT")" -gt 60000 ]; then
    echo "The plan is longer than this comment allows. Download the relay-plan artifact for all of it."
  fi
  echo "</details>"
} > "$OUT_DIR/comment.md"
SH
chmod +x ci/comment.sh

Run both on your laptop, with your AWS credentials and TF_VAR_state_passphrase set as in part 4:

Bash
./ci/plan.sh
./ci/comment.sh
head -n 3 plan/comment.md

The saved plan is encrypted. Part 4 put a plan block in the encryption configuration, so relay.tfplan is unreadable without the passphrase. That matters here, because the plan file is about to be uploaded to GitHub, and a plan can hold values that never appear in the code. The text version, plan.txt, is not encrypted, but tofu show prints sensitive values as (sensitive value).

Check it worked

fmt, validate and both test runs pass, and the plan says No changes. Your infrastructure matches the configuration. The head shows the comment's heading, a blank line and the bold No changes. line. ls plan lists comment.md, plan.txt, relay.tfplan and tree.txt. Running git status --short shows the new ci/ and iam/ folders but not plan/.

Step 4 · Write the apply scripts

The apply job runs on main after a merge, in a different workflow run from the plan. It has to find the right plan, check it still describes this code, and apply it.

ci/fetch-plan.sh asks GitHub which pull request produced the commit on main, finds the successful plan run for that pull request's last commit, and downloads its artifact. It works the same for merge commits, squash merges and rebases, because GitHub tracks which pull request each of those commits came from:

Bash
cat > ci/fetch-plan.sh <<'SH'
#!/usr/bin/env bash
# Download the plan artifact from the pull request that produced this commit.
set -euo pipefail

OUT_DIR="${OUT_DIR:-plan}"

head_sha=$(gh api "repos/$GITHUB_REPOSITORY/commits/$GITHUB_SHA/pulls" \
  --jq '[.[] | select(.merged_at != null)][0].head.sha // empty')
if [ -z "$head_sha" ]; then
  echo "No merged pull request found for $GITHUB_SHA. Change Relay through pull requests only."
  exit 1
fi

run_id=$(gh run list --repo "$GITHUB_REPOSITORY" --workflow relay.yml --event pull_request \
  --commit "$head_sha" --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty')
if [ -z "$run_id" ]; then
  echo "No successful plan run for $head_sha. Push a new commit to a pull request to plan again."
  exit 1
fi

gh run download "$run_id" --repo "$GITHUB_REPOSITORY" --name relay-plan --dir "$OUT_DIR"
SH
chmod +x ci/fetch-plan.sh

ci/apply.sh compares tree IDs before it touches anything. On a pull request, GitHub checks out a preview of the merge, so the plan's tree.txt records the code as it would look on main. If another change reached main in between, the tree after the real merge is different, and the script stops instead of applying a plan made against other code:

Bash
cat > ci/apply.sh <<'SH'
#!/usr/bin/env bash
# Apply the downloaded plan, but only to the code it was made from.
set -euo pipefail

OUT_DIR="${OUT_DIR:-plan}"
planned_tree=$(cat "$OUT_DIR/tree.txt")
current_tree=$(git rev-parse 'HEAD^{tree}')
if [ "$planned_tree" != "$current_tree" ]; then
  echo "This commit is not the code that was planned (planned $planned_tree, now $current_tree)."
  echo "Open a pull request from main so the change gets a fresh plan and review."
  exit 1
fi
if [ -n "${TF_PLUGIN_CACHE_DIR:-}" ]; then mkdir -p "$TF_PLUGIN_CACHE_DIR"; fi

tofu init -input=false -lockfile=readonly
tofu apply -input=false -lock-timeout=5m "$OUT_DIR/relay.tfplan"
SH
chmod +x ci/apply.sh
bash -n ci/fetch-plan.sh
bash -n ci/apply.sh

OpenTofu adds a second guard of its own. A saved plan records which version of the state it was made from, and tofu apply refuses a plan whose state has changed since, with an error saying the saved plan is stale. So if two pull requests were both planned against the same state, the first merge applies and the second apply fails safely. Its fix is the same: update the pull request branch so it plans again.

Check it worked

ls ci lists apply.sh, comment.sh, fetch-plan.sh and plan.sh, and ls -l ci shows all four as executable. bash -n prints nothing, which means both new scripts parse.

Step 5 · Write the workflow and lint it

The workflow has one job per event. permissions: {} at the top removes every token permission, and each job asks only for what it uses: id-token: write to get the OIDC token, pull-requests: write for the comment, pull-requests: read to look up which pull request a commit on main came from, and actions: read to download another run's artifact. None of the apply job's permissions can write to the repository.

Bash
mkdir -p .github/workflows
cat > .github/workflows/relay.yml <<'YAML'
name: relay

on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

permissions: {}

env:
  TOFU_VERSION: 1.13.10
  VAR_FILE: dev.tfvars
  TF_IN_AUTOMATION: "1"
  TF_INPUT: "0"
  TF_PLUGIN_CACHE_DIR: ${{ github.workspace }}/.tofu-plugin-cache

jobs:
  plan:
    if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      id-token: write
      pull-requests: write
    concurrency:
      group: relay-plan-${{ github.event.pull_request.number }}
      cancel-in-progress: true
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false

      - uses: opentofu/setup-opentofu@v2
        with:
          tofu_version: ${{ env.TOFU_VERSION }}
          tofu_wrapper: false

      - uses: actions/cache@v6
        with:
          path: ${{ env.TF_PLUGIN_CACHE_DIR }}
          key: tofu-providers-${{ runner.os }}-${{ hashFiles('**/.terraform.lock.hcl') }}

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

      - name: Check, test and plan
        env:
          TF_VAR_state_passphrase: ${{ secrets.STATE_PASSPHRASE }}
        run: ./ci/plan.sh

      - name: Build the comment
        env:
          COMMIT_SHA: ${{ github.event.pull_request.head.sha }}
        run: ./ci/comment.sh

      - uses: actions/upload-artifact@v7
        with:
          name: relay-plan
          path: plan/
          retention-days: 14
          if-no-files-found: error

      - name: Comment on the pull request
        env:
          GH_TOKEN: ${{ github.token }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: gh pr comment "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --edit-last --create-if-none --body-file plan/comment.md

  apply:
    if: github.event_name == 'push'
    runs-on: ubuntu-24.04
    environment: production
    permissions:
      contents: read
      id-token: write
      actions: read
      pull-requests: read
    concurrency:
      group: relay-apply
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false

      - uses: opentofu/setup-opentofu@v2
        with:
          tofu_version: ${{ env.TOFU_VERSION }}
          tofu_wrapper: false

      - uses: actions/cache@v6
        with:
          path: ${{ env.TF_PLUGIN_CACHE_DIR }}
          key: tofu-providers-${{ runner.os }}-${{ hashFiles('**/.terraform.lock.hcl') }}

      - name: Download the reviewed plan
        env:
          GH_TOKEN: ${{ github.token }}
        run: ./ci/fetch-plan.sh

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

      - name: Apply the reviewed plan
        env:
          TF_VAR_state_passphrase: ${{ secrets.STATE_PASSPHRASE }}
        run: ./ci/apply.sh
YAML

A few lines carry most of the design:

  • The if on plan skips pull requests from forks. GitHub does not pass secrets to those runs and gives them a read-only token, so the job would fail anyway; skipping it makes that explicit.
  • tofu_wrapper: false turns off the setup action's wrapper around tofu, which captures output and exit codes for later steps. The scripts read files, not step outputs, so the plain binary is simpler.
  • The two concurrency groups. A new commit on a pull request cancels that pull request's older plan, since only the newest one matters. Applies share one group that never cancels a running job, so two applies cannot touch the state at once. By default GitHub keeps one apply waiting and cancels an older waiting one when a newer one arrives; that older plan would have been stale by then anyway. GitHub also documents a queue setting for keeping more runs waiting.
  • The order of steps in apply. The plan is downloaded with the GitHub token before AWS credentials exist, and the apply role is assumed only for the final step.

A note on cost and speed: the AWS provider is one of the largest provider downloads. The cache step keeps it between runs, keyed on the lock files, so it is fetched again only when the provider version changes. If you or your team pay for data by the bundle, as many people on prepaid mobile data across Africa do, the same idea helps on your laptop: set TF_PLUGIN_CACHE_DIR once in your shell profile and every project reuses the providers you already have.

Now lint the workflow. actionlint checks the syntax, the expressions, the contexts each key may use and the inputs of well-known actions. Install release 1.7.12 and check its checksum. It is a single binary that no package manager updates, so to upgrade, repeat these commands with a newer version. On macOS, brew install actionlint does the same job:

Bash
VERSION=1.7.12
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v${VERSION}/actionlint_${VERSION}_linux_${ARCH}.tar.gz"
curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v${VERSION}/actionlint_${VERSION}_checksums.txt"
sha256sum --ignore-missing -c "actionlint_${VERSION}_checksums.txt"
tar -xzf "actionlint_${VERSION}_linux_${ARCH}.tar.gz" actionlint
sudo install -m 0755 actionlint /usr/local/bin/actionlint
cd ~/relay-demo
actionlint -version
actionlint .github/workflows/relay.yml && echo "relay.yml passed actionlint"

Check it worked

The checksum line ends in OK, actionlint -version prints a first line with 1.7.12 in it, and the last command prints relay.yml passed actionlint with no errors above it. To see what it catches, change id-token: write to id-token: writ and run it again: it reports the line and column. Change it back before you go on.

Step 6 · Give GitHub the roles, the secret and a protected environment

The workflow reads three repository variables and one secret. Variables are not secret, and role ARNs do not need to be: the trust policy, not the ARN, decides who can use a role. Run these on your laptop from ~/relay-demo, with your own account ID in place of the example:

Bash
gh variable set AWS_REGION --body eu-west-1
gh variable set RELAY_PLAN_ROLE_ARN --body "arn:aws:iam::123456789012:role/relay-plan"
gh variable set RELAY_APPLY_ROLE_ARN --body "arn:aws:iam::123456789012:role/relay-apply"
gh secret set STATE_PASSPHRASE

gh secret set with no --body asks for the value and keeps it out of your shell history. Paste part 4's passphrase.

Be clear about what that secret protects against. Any job in a pull request from a branch in this repository can read STATE_PASSPHRASE and assume relay-plan, and someone with push access could edit ci/plan.sh to print them. So the people who can push branches are the people who can read Relay's state. Keep write access to the repository to the people you would trust with that.

Next, create the production environment under the repository's Settings, then Environments, and set:

  • Deployment branches and tags: selected branches, main only. This is the setting the apply role depends on.
  • Required reviewers: yourself and anyone else who may approve a change to AWS, with Prevent self-review on once there are two of you, so the person who merged cannot also approve. Only if your plan offers it, see below.

Why the branch setting matters: the apply role trusts any job whose token says environment:production, and any pull request can edit the workflow. A pull request that adds environment: production to its own job gets that subject and could assume relay-apply. With deployment branches set to main only, GitHub refuses to run that job, because a pull request runs on its own ref, not on main. Without that setting, the apply role can be assumed from any branch.

The tutorial on requiring approval before production deploys does this with gh api and explains each setting. What you get depends on the plan, according to GitHub's documentation checked on 26 November 2026:

  • Public repository, any plan: deployment branches, required reviewers and branch protection are all available. Set everything above.
  • Private repository on GitHub Pro or Team: deployment branches and branch protection are available, but required reviewers are not, so nobody is asked to approve the apply. Your review gate is the pull request itself.
  • Private repository on GitHub Free: none of these exist. Do not use this workflow there: without the branch restriction anyone who can push a branch can apply to AWS. Upgrade or make the repository public, as in step 1.

Do not add a branch rule to main yet. The next step pushes the CI files straight to main, and a rule that requires pull requests would refuse that push. You add the rule in the next step, once the CI commit is on main and the plan check has run once.

Check it worked

gh variable list shows AWS_REGION, RELAY_APPLY_ROLE_ARN and RELAY_PLAN_ROLE_ARN. gh secret list shows STATE_PASSPHRASE with an update time but no value. gh api repos/{owner}/{repo}/environments --jq '.environments[].name' prints production.

Step 7 · Open a pull request with a real change

Versioning on the assets bucket (part 1) keeps every old copy of every file forever, and each one is billed as storage. A lifecycle rule that removes old versions after 30 days is a small, useful first change to send through the pipeline.

Commit the CI files on main first, so the workflow exists before the first pull request. In a team you would review this through a pull request too:

Bash
git add .gitignore ci iam .github
git commit -m "Plan in pull requests, apply on merge"

Before you push, know that this first run is expected to fail. Pushing to main starts the apply job straight away (after an approval, if you set required reviewers). This commit did not come from a pull request, so ci/fetch-plan.sh stops with No merged pull request found for .... That is the guard doing its job, not a broken workflow. If the run waits for approval, cancel it with gh run cancel instead of approving it:

Bash
git push

Now make the change on a branch:

Bash
git switch -c expire-old-asset-versions
cat >> assets.tf <<'HCL'

resource "aws_s3_bucket_lifecycle_configuration" "assets" {
  bucket = aws_s3_bucket.assets.id

  rule {
    id     = "expire-noncurrent-versions"
    status = "Enabled"

    filter {}

    noncurrent_version_expiration {
      noncurrent_days = 30
    }
  }

  depends_on = [aws_s3_bucket_versioning.assets]
}
HCL
git add assets.tf
git commit -m "Expire old versions of Relay assets after 30 days"
./ci/plan.sh
./ci/comment.sh
head -n 3 plan/comment.md

Running the plan script before you push catches formatting and test failures in seconds rather than after a CI run. Commit first: the script records the tree of the last commit, so a plan of uncommitted edits would not match it. depends_on makes sure versioning is on before the rule is written, as the provider documentation recommends for rules about noncurrent versions.

Push the branch and open the pull request:

Bash
git push -u origin expire-old-asset-versions
gh pr create --fill --base main
gh pr checks --watch

Now protect main, before you merge. Under the repository's Settings, then Branches (or Rules, then Rulesets, if your plan has them), add a rule for main that:

  • requires a pull request before merging, with one approval;
  • requires the plan status check to pass. GitHub offers checks that have already run in the repository, which is why the rule waits until now;
  • requires branches to be up to date before merging, so a pull request is always planned against the latest main and the tree check in apply.sh almost never has to stop a run.

If you work alone, set the number of required approvals to 0. GitHub does not let you approve your own pull request, so a rule that needs one approval would block every merge you make. Keep the pull request and the plan check required. With 0 approvals, nobody but you reads the plan before it reaches main. Prefer this to merging with gh pr merge --admin, which skips the whole rule, the plan check included. Raise it to 1 as soon as a second person joins. On a private repository on Pro or Team, where the production environment has no required reviewers, that approval is the only human check before the apply, so do not leave it at 0 once there are two of you.

Check it worked

Locally, the comment's bold line reads Plan: 1 to add, 0 to change, 0 to destroy. On GitHub, gh pr checks shows the plan check passing, and the pull request has a comment headed OpenTofu plan for and the branch's commit ID, listing aws_s3_bucket_lifecycle_configuration.assets will be created. The pull request's merge box lists plan as a required check. The run's summary page lists a relay-plan artifact. Push another commit to the branch and the same comment is updated rather than a new one added, because of --edit-last.

Step 8 · Merge, approve and watch the saved plan apply

Read the plan comment as the reviewer would: one resource added, nothing changed or destroyed. If a second person is on the repository, they approve the pull request first; if you work alone with 0 required approvals, you can merge straight away. Then merge:

Bash
gh pr merge --squash --delete-branch

The push to main starts the apply job, which waits for approval because it names the production environment. Open the run, read the plan comment once more if you need to, and approve it under Review deployments. Then follow it from your terminal:

Bash
gh run watch

The apply job downloads the relay-plan artifact from the pull request run, checks the tree ID, assumes relay-apply and applies the saved file. It does not plan again, so what happens in AWS is what the reviewer read.

When it goes wrong, the log says which guard stopped it:

  • No merged pull request found for ...: the commit reached main without a pull request, such as the CI commit you pushed in step 7. Nothing was applied. Send the change through a pull request.
  • No successful plan run for ...: the plan job failed on the last commit, or the artifact expired after its 14 days. Push a new commit to a pull request.
  • This commit is not the code that was planned: main changed between the plan and the merge. Turn on "require branches to be up to date" and open a pull request from main so the current code is planned.
  • Saved plan is stale (or similar wording): another apply changed the state first. Update the other pull request's branch so it plans again.

Check it worked

The apply job ends with Apply complete! Resources: 1 added, 0 changed, 0 destroyed. On your laptop, git pull and then ./ci/plan.sh prints No changes. Your infrastructure matches the configuration., because main and AWS now agree. aws s3api get-bucket-lifecycle-configuration --bucket "$(tofu output -raw assets_bucket_name)" shows the rule expire-noncurrent-versions with NoncurrentDays of 30. Leave the roles, the workflow and the environment in place: part 8 adds a scheduled drift check that uses the plan role.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.