Terraform GitHub Actions on AWS: Plan on PR, Apply on Merge

  • DevOps
  • AWS
  • Hands-on lab
  • 25 min read

A Terraform GitHub Actions pipeline lets you change AWS without anyone running terraform apply from a laptop. Every change starts as a pull request. The pipeline shows the plan, a teammate reviews it, and only the main branch is allowed to apply it. The first part of this guide explains how the pipeline works. The second part is a 13-step lab: you build the pipeline in your own accounts, create a small VPC through a pull request, change it by hand to test the drift alert, and delete everything at the end.

Last updated: December 2026

In short

  • Git: one main branch, short-lived feature branches, one folder per environment.
  • State: keep it in a versioned S3 bucket, locked with use_lockfile = true. DynamoDB locking is deprecated.
  • Access: GitHub signs in to AWS with OIDC. A read-only role plans pull requests; a separate role, trusted only for main, applies.
  • Checks: pre-commit on the laptop, fmt, validate and plan in the pull request, required reviews before merge.
  • Drift: a scheduled plan -detailed-exitcode run alerts you when AWS no longer matches the code.
Terraform GitHub Actions pipeline on AWS with plan, apply and drift check
The whole flow on one page: five stages, two AWS roles and the nightly drift check. Tap the picture to see it full size.

Why Run Terraform From a Pipeline?

When people apply from their own machines, three things go wrong sooner or later. Someone applies code that nobody reviewed. Two people apply at the same time and the state file gets damaged. And somebody’s laptop holds AWS keys that can change everything in the account.

A pipeline fixes all three. The code in Git is the only source of changes, the state lives in one locked place, and only the pipeline holds write access to AWS, through short-lived credentials. Git history becomes your audit trail: who changed what, when, who approved it, and the exact plan they saw.

New to state files and locking? Read 8 Terraform Best Practices for a Safer Workflow first; this guide builds on it.

Git Basics for Infrastructure Code

You only need a handful of Git commands for this workflow. Each one appears again in the lab:

CommandWhat it does here
git clone <url>Copies the repository to your machine
git switch -c <branch>Creates a new branch and moves you onto it
git add .Picks up your changed files for the next commit
git commit -m "<message>"Saves those changes; the pre-commit checks run at this moment
git push -u origin <branch>Sends the branch to GitHub and remembers the link, so later git push and git pull need no extra words
git pull --rebase origin mainPuts your commits on top of the newest main, so the history stays a straight line

Which branching model? Use GitHub flow, a simple form of trunk-based development: create a short-lived branch, open a pull request, merge it into the default branch, delete the branch. It suits Terraform because main always describes what is running in AWS. Git Flow, with long-lived develop and release branches, works for some application teams, but with Terraform every long-lived branch is another version of the truth, and the state file can only match one of them. Keep one main and separate environments with folders such as envs/dev and envs/prod, not with branches.

How to merge: a squash merge turns the whole pull request into one commit on main. One change becomes one commit, which is easy to read in the log and easy to undo with git revert.

The Terraform GitHub Actions Workflow in 5 Stages

  1. Laptop: you create a branch, edit the .tf files and commit. Pre-commit hooks format and check the code before the commit is saved.

  2. Pull request: GitHub Actions runs fmt, validate and plan with a read-only AWS role, then posts the plan in the pull request.

  3. Review: CODEOWNERS asks the right team. Branch protection demands approvals and a green plan job.

  4. Main branch: after the merge, a second job plans again and applies that saved plan with the apply role.

  5. AWS: resources change, the state in S3 is updated, and a scheduled job checks every night that nothing has drifted.

Tools Used in This Pipeline

ToolIts jobCost
Git and GitHubVersion history, pull requests, reviews and branch protectionFree plan is enough
GitHub ActionsRuns the plan, apply and drift jobsFree minutes, see the cost box below
TerraformPlans and applies the changes to AWSFree CLI
aws-actions/configure-aws-credentialsTrades GitHub’s OIDC token for temporary AWS credentialsFree
hashicorp/setup-terraformInstalls a fixed Terraform version on the runnerFree
pre-commitRuns checks on your laptop before each commitFree
TFLintFinds provider mistakes, such as an instance type that does not existFree
CheckovFlags insecure settings, such as SSH open to the whole internetFree, open source
tfsecAn older security scanner; its makers now point users to Trivy (trivy config)Free
AtlantisAn alternative to Actions that runs plan and apply from pull request comments; you host it yourselfFree software, you pay for its server

Hands-On Lab: What You Need First

The lab builds everything shown in the diagram above, in this order: repository, state bucket, code, local checks, AWS roles, workflows, pull request, review rules, merge, drift test and clean-up. Plan about an hour. You need:

  • An AWS account for testing (not production) and the AWS CLI v2, signed in with admin rights. Only your laptop uses these rights, for the one-time setup; the pipeline never does.
  • A GitHub account and the GitHub CLI, signed in with gh auth login.
  • Terraform 1.11 or newer, Git, Python 3 and TFLint.
  • On Windows, run the lab inside WSL. The pre-commit hooks are shell scripts and run best on Linux or macOS.

The examples use the organization my-org, the repository aws-infra, the account ID 111122223333 and the region us-east-1. Replace them with your own values everywhere. A personal GitHub account works too: use your user name in place of my-org.

What the lab costs

Close to nothing. AWS does not charge for a VPC on its own (NAT gateways and public IPv4 addresses cost money, and the lab creates neither). The state bucket holds a few kilobytes, so S3 costs cents at most. The GitHub Actions runs fit inside the free minutes. Step 13 deletes everything.

Terraform GitHub Actions Lab: 13 Steps From Empty Repo to Apply

01 Create the Repository and Folders

  • GitHub
  • 5 minutes

On GitHub, create a new private repository named aws-infra with a README, so it already has a main branch. Then copy it to your machine:

Any OS · Git
git clone https://github.com/my-org/aws-infra.git

By the end of the lab, the repository will look like this:

Text · folder layout
aws-infra/
  .github/
    CODEOWNERS
    workflows/
      terraform.yml
      drift.yml
  envs/
    dev/
      backend.tf
      main.tf
      .terraform.lock.hcl
  .gitignore
  .pre-commit-config.yaml
  README.md

Create a .gitignore file in the repository root first, so no local Terraform files end up in Git:

Text · .gitignore
.terraform/
*.tfstate
*.tfstate.backup
tfplan
plan.txt

A saved plan file can contain secret values from your resources, so it must never be committed. The .terraform.lock.hcl file is different: commit it, because it pins the exact provider versions for everyone.

02 Set Up the Terraform S3 Backend With use_lockfile

  • Terraform 1.11 or newer
  • One-time setup

The pipeline and every engineer must read the same state, and only one run may change it at a time. Bucket names are global, so add something unique to the name. Create a bucket for the environment:

Any OS · AWS CLI
aws s3api create-bucket --bucket my-org-tfstate-dev --region us-east-1

Turn on versioning, so you can go back to yesterday’s state if a run goes wrong:

Any OS · AWS CLI
aws s3api put-bucket-versioning --bucket my-org-tfstate-dev --versioning-configuration Status=Enabled

New buckets are already encrypted (since January 2023) and have Block Public Access on (since April 2023), so you do not need extra commands for those. Outside us-east-1, add --create-bucket-configuration LocationConstraint=<region> to the first command.

Then point Terraform at the bucket in envs/dev/backend.tf:

HCL · envs/dev/backend.tf
terraform {
  required_version = ">= 1.11"

  backend "s3" {
    bucket       = "my-org-tfstate-dev"
    key          = "network/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

Why no DynamoDB table? Many tutorials still create one for locking. Since Terraform 1.11, the S3 backend can lock with a small .tflock file next to the state, and HashiCorp marks the DynamoDB option as deprecated. use_lockfile is off by default, so you must set it. For more on state, see our Terraform best practices guide.

03 Write the VPC Code and Test It Locally

  • HCL
  • No changes in AWS yet

The lab manages one small resource: a VPC. Save this as envs/dev/main.tf:

HCL · envs/dev/main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_hostnames = true

  tags = {
    Name        = "lab-vpc"
    Environment = "dev"
  }
}

Move into the folder:

Linux / macOS / WSL · Bash
cd envs/dev

Download the provider and connect to the state bucket. This also creates .terraform.lock.hcl:

Any OS · Terraform
terraform init

Preview the change:

Any OS · Terraform
terraform plan

The last line should read Plan: 1 to add, 0 to change, 0 to destroy. Do not run terraform apply here. From now on, only the pipeline applies. Go back to the repository root with cd ../.. before the next step.

04 Check Code Before Every Commit

  • Runs on the laptop
  • Free tools

The pre-commit framework runs checks every time you type git commit, and blocks the commit if one fails. Add .pre-commit-config.yaml to the root of the repository:

YAML · .pre-commit-config.yaml
repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.109.5
    hooks:
      - id: terraform_fmt
      - id: terraform_validate
      - id: terraform_tflint
      - id: terraform_checkov

Install pre-commit and Checkov (TFLint you installed earlier):

Any OS · Python (pip)
pip install pre-commit checkov

Switch the hooks on for this repository:

Any OS · Git
pre-commit install

What each hook does: terraform_fmt fixes the layout, terraform_validate checks the syntax, TFLint finds provider mistakes, and Checkov flags insecure settings. Older guides use the hook id checkov; it is deprecated, use terraform_checkov.

Now start your first branch:

Any OS · Git
git switch -c add-lab-vpc

Stage the files:

Any OS · Git
git add .

Commit. Watch the hooks run before the commit is saved:

Any OS · Git
git commit -m "Add lab VPC"

If terraform_fmt changed a file, run git add . and commit again. Checkov will probably complain about the lab VPC, for example that it has no flow logs. Read the check ID it prints, then either fix the code or, for this lab only, add a skip comment inside the aws_vpc block such as # checkov:skip=<CHECK_ID>:lab only. In real projects, every skip should be reviewed like any other change.

Pre-commit only runs where it is installed, and anyone can skip it. That is why the pull request runs the same checks again.

05 Set Up GitHub Actions OIDC for AWS

  • No access keys
  • Once per AWS account

With OpenID Connect (OIDC), each workflow run gets a signed token from GitHub and trades it for temporary AWS credentials, valid for one hour by default. There is no access key to store or leak. First, tell IAM to trust GitHub’s token service:

Any OS · AWS CLI
aws iam create-open-id-connect-provider --url https://token.actions.githubusercontent.com --client-id-list sts.amazonaws.com

Older guides add a --thumbprint-list. It is optional now: AWS checks GitHub’s certificate against its own list of trusted certificate authorities. If the command says the provider already exists, someone set it up before you, and you can move on.

You also need your account ID for the next step:

Any OS · AWS CLI
aws sts get-caller-identity --query Account --output text

06 Create Two IAM Roles for Terraform: Plan and Apply

  • IAM
  • Security

The pipeline uses two roles. tf-plan can only read, and is trusted by pull requests and by the scheduled drift job on main. tf-apply can change resources, and is trusted only by the main branch. A pull request can never get the apply role, even if someone edits the workflow file in their branch.

Save the four JSON files below in a folder outside the repository, for example ~/lab-iam, and run the commands from that folder. First, the trust policy for tf-plan:

JSON · tf-plan-trust.json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Federated": "arn:aws:iam::111122223333: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:my-org/aws-infra:pull_request",
          "repo:my-org/aws-infra:ref:refs/heads/main"
        ]
      }
    }
  }]
}

The trust policy for tf-apply is the same file with a single subject, main only:

JSON · tf-apply-trust.json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Federated": "arn:aws:iam::111122223333: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:my-org/aws-infra:ref:refs/heads/main"
      }
    }
  }]
}

tf-plan may read the state and write only the lock file. The lock file needs write access because plan takes the lock too:

JSON · tf-plan-state.json
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::my-org-tfstate-dev" },
    { "Effect": "Allow", "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-org-tfstate-dev/network/terraform.tfstate" },
    { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::my-org-tfstate-dev/network/terraform.tfstate.tflock" }
  ]
}

tf-apply may also write the state itself:

JSON · tf-apply-state.json
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::my-org-tfstate-dev" },
    { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::my-org-tfstate-dev/network/terraform.tfstate" },
    { "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::my-org-tfstate-dev/network/terraform.tfstate.tflock" }
  ]
}

Create the tf-plan role:

Any OS · AWS CLI
aws iam create-role --role-name tf-plan --assume-role-policy-document file://tf-plan-trust.json

Let it read AWS resources:

Any OS · AWS CLI
aws iam attach-role-policy --role-name tf-plan --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess

Give it its state access:

Any OS · AWS CLI
aws iam put-role-policy --role-name tf-plan --policy-name tf-state --policy-document file://tf-plan-state.json

Create the tf-apply role:

Any OS · AWS CLI
aws iam create-role --role-name tf-apply --assume-role-policy-document file://tf-apply-trust.json

Let it manage VPCs, which is all this lab changes:

Any OS · AWS CLI
aws iam attach-role-policy --role-name tf-apply --policy-arn arn:aws:iam::aws:policy/AmazonVPCFullAccess

Give it its state access:

Any OS · AWS CLI
aws iam put-role-policy --role-name tf-apply --policy-name tf-state --policy-document file://tf-apply-state.json

ReadOnlyAccess keeps the lab short, but it can read almost everything in the account. In a real setup, give tf-plan read access only to the services your code manages.

New repositories use a different subject

GitHub repositories created after 15 July 2026 use an immutable subject that includes the organization and repository IDs, in the form repo:org@<ORG_ID>/repo@<REPO_ID>:.... A trust policy written with names only will not match them. Check the format in GitHub’s OIDC reference and copy the exact subject your repository uses. If the sign-in step fails in step 09, this is the first thing to check.

07 Run Terraform Plan on Pull Request, Apply on Merge

  • GitHub Actions
  • The core of the pipeline

One workflow file holds two jobs. The plan job runs on pull requests and posts the plan. The apply job runs only when code lands on main. Save it as .github/workflows/terraform.yml and put your own account ID in both role ARNs:

YAML · .github/workflows/terraform.yml
name: terraform

on:
  pull_request:
  push:
    branches: [main]

defaults:
  run:
    working-directory: envs/dev

jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/tf-plan
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_version: 1.17.3
          terraform_wrapper: false
      - run: terraform init -input=false
      - run: terraform fmt -check -recursive
      - run: terraform validate
      - run: terraform plan -input=false -no-color -out=tfplan
      - run: terraform show -no-color tfplan > plan.txt
      - uses: actions/github-script@v9
        with:
          script: |
            const fs = require('fs');
            const plan = fs.readFileSync('envs/dev/plan.txt', 'utf8').slice(0, 60000);
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: '### Terraform plan\n```\n' + plan + '\n```'
            });

  apply:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    concurrency: terraform-dev
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/tf-apply
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_version: 1.17.3
          terraform_wrapper: false
      - run: terraform init -input=false
      - run: terraform plan -input=false -out=tfplan
      - run: terraform apply -input=false tfplan

Why plan again on main? Other pull requests may have merged since yours was planned. The apply job makes a fresh plan, saves it, and applies exactly that file. A plain terraform apply -auto-approve also makes a new plan, but you never see it in the log before it runs.

A few details that matter:

  • id-token: write lets the job ask GitHub for the OIDC token. Without it, the AWS sign-in step fails.
  • concurrency makes a second apply wait for the first one instead of fighting for the lock.
  • terraform_wrapper: false gives you the plain Terraform binary, so exit codes and file output behave exactly as on your laptop.
  • github-script runs from the repository root, which is why it reads envs/dev/plan.txt. The plan is cut at 60,000 characters because a GitHub comment can only hold about 65,000.

For production, add environment: production to the apply job and set required reviewers on that environment in GitHub. The job then waits for one more click before it runs. The OIDC subject of that job changes to repo:my-org/aws-infra:environment:production, so update the tf-apply trust policy to match.

08 Terraform Drift Detection With GitHub Actions

  • Scheduled job
  • Exit codes 0, 1, 2

Drift means AWS no longer matches your code, usually because someone changed something in the console. terraform plan -detailed-exitcode tells you with its exit code: 0 means no changes, 2 means changes (drift), and 1 means an error. We checked all three on a test project before writing this. Save the second workflow as .github/workflows/drift.yml:

YAML · .github/workflows/drift.yml
name: drift-check

on:
  schedule:
    - cron: "0 2 * * *"
  workflow_dispatch:

permissions:
  id-token: write
  contents: read

jobs:
  drift:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: envs/dev
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/tf-plan
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_version: 1.17.3
          terraform_wrapper: false
      - run: terraform init -input=false
      - name: Check for drift
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
        run: |
          code=0
          terraform plan -input=false -detailed-exitcode || code=$?
          if [ "$code" -eq 2 ]; then
            curl -fsS -X POST -H 'Content-type: application/json' \
              --data '{"text":"Terraform drift found in envs/dev"}' "$SLACK_WEBHOOK_URL"
          elif [ "$code" -ne 0 ]; then
            exit "$code"
          fi

The job runs every night at 02:00 UTC, and workflow_dispatch adds a button so you can start it by hand. Scheduled and manual runs come from the default branch, so their OIDC subject is repo:my-org/aws-infra:ref:refs/heads/main. That is why the tf-plan trust policy in step 06 lists it next to pull_request: the drift job can plan without the apply role’s write access.

For the alert, create a Slack incoming webhook and save its URL as a repository secret named SLACK_WEBHOOK_URL (Settings > Secrets and variables > Actions). No Slack? You can skip it for the lab; step 12 shows what happens then.

The drift alert that never fires

Many examples run terraform plan -detailed-exitcode on one line and check if [ $? -eq 2 ] on the next. In GitHub Actions that if never runs: the default shell is started with -e, so exit code 2 ends the step at once and no alert is sent. We reproduced this with the same bash options. The || code=$? pattern above keeps the exit code without stopping the step.

09 Push the Branch and Open a Pull Request

  • Git and GitHub CLI
  • First pipeline run

Stage the two workflow files:

Any OS · Git
git add .

Commit them:

Any OS · Git
git commit -m "Add Terraform pipeline"

Send the branch to GitHub:

Any OS · Git
git push -u origin add-lab-vpc

Open the pull request. --fill uses your commit messages as its title and description:

Any OS · GitHub CLI
gh pr create --fill

Open the pull request in the browser and watch the Checks tab. After a minute or two the plan job turns green and posts a comment that ends with Plan: 1 to add, 0 to change, 0 to destroy. This is what a reviewer reads before approving. If the job fails at the AWS sign-in step, see the troubleshooting table below.

10 Protect Main and Route Reviews With CODEOWNERS

  • GitHub settings
  • No direct pushes

A .github/CODEOWNERS file names the team that owns each folder. GitHub then asks that team to review any pull request that touches it. In a company it could look like this:

Text · .github/CODEOWNERS
/envs/        @my-org/platform-team
/envs/prod/   @my-org/platform-leads
**/iam/       @my-org/security-team

Order matters: when several lines match a file, the last one wins. Put broad rules first and the most specific ones at the bottom. Here, any IAM change goes to the security team, even in production. For the lab, one line with your own GitHub user name is enough, such as /envs/ @your-name. Add the file to your branch with git add, git commit and git push; the plan runs again on the new commit.

On its own, CODEOWNERS only requests a review. To make it binding, open Settings > Branches, add a rule for main, and tick:

  • Require a pull request before merging, with Required number of approvals before merging set to 1 or 2.
  • Require review from Code Owners.
  • Require status checks to pass before merging, and select the plan job. It shows up in the search box once it has run at least once, which is why this step comes after the first pull request.
  • Require signed commits and Require linear history (optional, but useful for an audit). Linear history allows only squash and rebase merges.
  • Do not allow bypassing the above settings, so admins follow the same rules.

Working alone? GitHub does not let you approve your own pull request. For the lab, set the number of approvals to 0 and leave Code Owners review off. The status check still has to pass, so nothing reaches main without a green plan.

11 Merge and Watch the Apply

  • Changes AWS
  • main only

Squash-merge the pull request into main:

Any OS · GitHub CLI
gh pr merge --squash

The merge is a push to main, so the apply job starts. Open the Actions tab and follow it: it signs in with tf-apply, plans again and applies the saved plan. When it is green, check that the VPC exists:

Any OS · AWS CLI
aws ec2 describe-vpcs --filters Name=tag:Name,Values=lab-vpc --query "Vpcs[0].VpcId" --output text

You should see an ID such as vpc-0abc1234def567890. Write it down for the next step. Nobody ran terraform apply by hand: the change went from a branch, through a reviewed plan, to AWS.

Back on your laptop, return to main and get the merged code with git switch main and then git pull. Every new change starts again from step 04 with a new branch.

12 Test the Drift Alert

  • Break it on purpose
  • Test account only

A drift job that was never tested may not work when you need it. Make a change outside Terraform, the way someone would in the console, by adding a tag to the VPC:

Any OS · AWS CLI
aws ec2 create-tags --resources vpc-0abc1234def567890 --tags Key=Owner,Value=console

Start the drift job now instead of waiting for the night:

Any OS · GitHub CLI
gh workflow run drift.yml

Terraform manages the whole tag list of the VPC, so the plan wants to remove the Owner tag and exits with code 2. With the Slack secret set, the alert arrives in your channel. Without it, the curl call fails and the run turns red, which is also a clear signal in a lab. Either way, open the run log and you will see the planned change: - "Owner" = "console" -> null.

Now decide who is right. If the hand change should stay, add the tag to main.tf through a new pull request. If it should go, remove it:

Any OS · AWS CLI
aws ec2 delete-tags --resources vpc-0abc1234def567890 --tags Key=Owner

Run gh workflow run drift.yml once more. This time the plan exits with 0 and the run stays green. Some tags are added by other tools on purpose, for example by a cost or backup tool. To stop them showing up as drift, list them in the provider’s ignore_tags block.

13 Clean Up the Lab

  • Deletes resources
  • Laptop with admin rights

A destroy step does not belong in a pipeline, so clean up from your laptop. In envs/dev, on an up-to-date main, remove the VPC. Terraform shows what it will delete and waits for you to type yes:

Any OS · Terraform
terraform destroy

Then remove the tf-plan role. A role must be empty before it can be deleted, so detach its managed policy first:

Any OS · AWS CLI
aws iam detach-role-policy --role-name tf-plan --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess

Delete its inline state policy:

Any OS · AWS CLI
aws iam delete-role-policy --role-name tf-plan --policy-name tf-state

Delete the role:

Any OS · AWS CLI
aws iam delete-role --role-name tf-plan

Repeat the same three commands for tf-apply, with AmazonVPCFullAccess as the managed policy. Then remove the GitHub identity provider, unless other projects in the account use it:

Any OS · AWS CLI
aws iam delete-open-id-connect-provider --open-id-connect-provider-arn arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com

Last, the state bucket. Because versioning is on, it still holds old versions of the state. Open the bucket in the S3 console, choose Empty (this removes every version), and then delete the bucket:

Any OS · AWS CLI
aws s3api delete-bucket --bucket my-org-tfstate-dev

The drift job would now fail every night, because its role is gone. Switch it off:

Any OS · GitHub CLI
gh workflow disable drift.yml

Run gh workflow enable drift.yml when you repeat the lab. Keep the GitHub repository if you want to repeat the lab or show it to someone; it costs nothing.

Taking It to Production

The lab uses one account and one folder. A real setup grows in a few predictable ways:

  • One AWS account per environment. Give each account its own folder (envs/dev, envs/prod), its own state bucket and its own pair of roles. A role in the production account trusts only the production subject, so a mistake in dev can never reach it.
  • An approval before production. Use a GitHub environment with required reviewers on the production apply job, as described in step 07.
  • Your own encryption key for state. The default S3 encryption is fine for a lab. With kms_key_id in the backend block, Terraform encrypts the state and lock files with a KMS key you control, and CloudTrail records every use of that key. Our guide to AWS KMS and other security services explains how KMS keys work.
  • Smaller read rights. Replace ReadOnlyAccess on the plan role with a policy that covers only the services in your code.
  • An alarm for changes made outside the pipeline. The drift job finds them the next night. To hear about them straight away, add an EventBridge rule on CloudTrail events that fires when anyone other than the tf-apply role changes the resources you manage.
  • No pull requests from forks. Keep the infrastructure repository private and have people work in branches of it. Pull requests from forks get no secrets and only read permissions, so they cannot get an OIDC token. Do not switch to pull_request_target to get around this; it runs code from the fork with your repository’s rights.

Troubleshooting the Pipeline

Error or symptomLikely causeFix
Error acquiring the state lockAnother run is still going, or a crashed run left its lock behindWait for the other run. If none is running, use terraform force-unlock LOCK_ID with the ID from the message
Not authorized to perform sts:AssumeRoleWithWebIdentityThe token subject does not match the trust policyCompare the sub with the job type: pull request, branch or environment. New repositories use the ID-based subject
The AWS sign-in step fails before Terraform startsid-token: write is missing, so no OIDC token is issuedAdd it under permissions for that job
terraform init fails with a bucket errorThe state bucket does not exist yet, or its name or region is wrong in backend.tfCreate the bucket first (step 02) and check the name and region
Checkov blocks the commitThe code breaks a security ruleFix it, or add a reviewed checkov:skip comment with a reason
Plan wants to create something that already existsThe resource was made outside TerraformAdd an import block, run plan, and check it shows no change
Required check stays “Expected” and blocks mergeThe workflow did not run for this pull request (for example a paths filter)Remove the filter, or use a check that always runs
“Review required” and you are the only personGitHub does not let authors approve their own pull requestFor a solo lab, set required approvals to 0
The plan job fails on a pull request from a forkFork runs get no secrets and read-only permissions, so no OIDC tokenWork in branches of the main repository instead

To bring an existing resource under Terraform, add an import block next to its resource block (Terraform 1.5 and newer):

HCL · envs/dev/imports.tf
import {
  to = aws_vpc.main
  id = "vpc-0abc1234def567890"
}

Unlike the old terraform import command, the block goes through the normal pull request, so the import is reviewed like any other change.

Common Mistakes With Terraform in GitHub Actions

  1. Long-lived access keys in GitHub secrets. A leaked key works until someone notices. Use OIDC roles instead.

  2. One role for plan and apply. Then any pull request can change AWS. Keep the write role for main only.

  3. A “read-only” plan role that cannot write the lock. plan takes the lock, so give the role write access to the .tflock object and nothing else.

  4. Still creating a DynamoDB lock table. It works, but it is deprecated. Use use_lockfile = true on new projects.

  5. No bucket versioning. Without it, a damaged state file cannot be rolled back.

  6. Committing plan or state files. They can hold passwords and other secret values. Keep them in .gitignore.

  7. Admins pushing straight to main. Tick “Do not allow bypassing the above settings”.

  8. A terraform destroy step in a workflow. One wrong trigger removes an environment. Keep destroy as a rare, manual and reviewed action.

  9. Never testing the drift job. Change a tag by hand in a test account, as in step 12, and make sure the alert arrives.

What it costs

OIDC, branch protection and CODEOWNERS cost nothing. GitHub-hosted runners are free for public repositories; on the GitHub Free plan, private repositories get $12 of runner time a month, roughly 2,000 minutes on standard Linux runners. The state bucket holds a few small files, so S3 costs cents a month. See GitHub Actions billing for the current numbers.

Key takeaways

  • Use one main branch with short-lived branches, and separate environments by folder.
  • Keep state in a versioned S3 bucket with use_lockfile = true; skip DynamoDB on new projects.
  • Use OIDC with two roles: plan for pull requests, apply for main only.
  • Apply a saved plan, not a surprise one, and let only one apply run at a time.
  • Make reviews binding with branch protection and “Require review from Code Owners”.
  • Capture the exit code in drift scripts, and test the alert by changing something by hand.

Terraform GitHub Actions FAQ

Can I do this lab for free?

Almost. GitHub’s free plan and free runner minutes cover the pipeline, and AWS does not charge for a VPC on its own. The only cost is the state bucket, which comes to cents at most. Delete everything with step 13 when you finish.

Should I use Git Flow or trunk-based development for Terraform?

Trunk-based, such as GitHub flow. One main branch describes what is running, and environments are folders. Long-lived branches would each describe a different version of your infrastructure.

Do I still need DynamoDB for Terraform state locking?

Not on Terraform 1.11 or newer. The S3 backend locks with a .tflock file when you set use_lockfile = true. HashiCorp marks the DynamoDB arguments as deprecated.

Is OIDC safer than storing AWS keys in GitHub secrets?

Yes. Nothing long-lived is stored. Each run gets credentials that expire after one hour by default, and the trust policy decides exactly which repository, branch or environment may use each role.

Should the apply job use -auto-approve?

Prefer terraform plan -out=tfplan followed by terraform apply tfplan. The saved plan is applied without a prompt, and the log shows exactly what it contained.

Can I use Atlantis or HCP Terraform instead?

Yes. They run plan and apply for pull requests in a similar way; Atlantis reacts to comments such as atlantis plan. GitHub Actions is a good start when your code is already on GitHub and you want no extra service to run.

How do I detect Terraform drift with GitHub Actions?

Run terraform plan -detailed-exitcode on a schedule. Exit code 0 means no changes, 2 means drift and 1 means an error. Capture the code with || code=$? so the alert step still runs (step 08). Once a night is enough for most teams.

Official references: HashiCorp’s S3 backend and terraform plan pages, GitHub’s guide to OIDC in AWS, the configure-aws-credentials action, and the AWS CLI reference for create-open-id-connect-provider.

Inspired by Module 15 of EngiDock’s AWS DevOps Engineer course. Text, lab, examples, tests and diagram by infotechtu.com.

Related guides on infotechtu.com

Share this guide

Save

Get new guides by email

One short email when a new guide is out. Unsubscribe at any time.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top