How to Use GitHub Actions with Terraform: A Safe Plan-and-Apply Workflow

github actions improve iac terraform

GitHub Actions can run Terraform checks when infrastructure code changes, give reviewers a consistent view of proposed changes, and gate deployments behind approval. For a solo developer or small team, that makes infrastructure changes easier to review and repeat. It does not make every terraform apply safe to automate: production changes still need a clear review and approval path.

Terraform provides the configuration language, providers, plan and apply commands, and state. GitHub Actions runs those commands in response to repository events. The workflow below separates basic pull-request checks from access to cloud resources, then explains how to add a controlled plan-and-apply stage.

Separate validation, planning, and applying

A useful workflow has three distinct stages:

  1. Validate the change. On a pull request, check formatting, initialize the configuration without its backend, and validate the syntax and internal consistency. These checks can run without production backend credentials or state; a private module registry may still need a separately scoped read credential.
  2. Create a plan for review. A Terraform plan reads the current state and may query provider APIs. Run a state-connected plan only in a job whose code and credentials are trusted. A speculative plan can help reviewers, but it does not apply the proposed changes.
  3. Apply the reviewed change. After the change reaches a protected branch, generate a fresh plan and require an appropriate human approval before applying it. If the plan is stale or the state has changed, create and review a new plan rather than applying an old one.

This follows Terraform's plan and apply workflow. Keep state in a shared remote backend that supports state locking, and leave locking enabled. It prevents concurrent writers from corrupting state; a GitHub Actions concurrency setting is not a replacement for a backend lock.

For code review and collaboration basics, see our guide to version control systems.

Add a pull-request validation workflow

Save a workflow like this as .github/workflows/terraform-check.yml. Change terraform/** and the working directory to match your repository layout.

name: Terraform checks

on:
  pull_request:
    paths:
      - "terraform/**"

permissions:
  contents: read

jobs:
  validate:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: terraform
    steps:
      - name: Check out the repository
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd
      - name: Install Terraform
        uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd
        with:
          terraform_version: 1.17.2
      - name: Check formatting
        run: terraform fmt -check -recursive
      - name: Initialize without a backend
        run: terraform init -backend=false -input=false -lockfile=readonly
      - name: Validate configuration
        run: terraform validate

The action references are full commit SHAs for actions/checkout v6.0.2 and HashiCorp's setup-terraform v3.1.2. Review action updates and pin any additional third-party actions to verified full-length SHAs, as recommended by GitHub's secure-use guidance. The example pins Terraform to 1.17.2; use the version your project has tested and update it deliberately.

terraform init -backend=false skips connecting to the configured backend, which lets this validation job run without state credentials. Commit .terraform.lock.hcl and use -lockfile=readonly so CI uses the checked-in provider selections instead of silently changing them. The lock file does not pin remote module versions, so specify and review module versions separately.

This workflow deliberately does not run a state-connected plan or an apply. A pull request can change Terraform configuration and other code that a workflow executes. Do not expose production secrets or cloud credentials to an untrusted pull request just because the job runs terraform plan rather than terraform apply. Avoid using pull_request_target to check out and run untrusted pull-request code, and do not run it on a self-hosted runner that has access to sensitive systems.

Protect credentials and deployment permissions

When a trusted job needs cloud access, prefer GitHub Actions OpenID Connect (OIDC) over a long-lived cloud access key stored as a repository secret. Configure the cloud identity's trust policy to accept only the intended repository and branch or protected environment, then limit the role's permissions to the resources that workflow needs. OIDC avoids storing a reusable cloud key in GitHub; it does not make an overly broad cloud role safe.

Keep the workflow's GITHUB_TOKEN permissions minimal. contents: read is enough for the validation example. Grant id-token: write only to a deployment job that requests an OIDC token; that permission allows token issuance but does not itself grant cloud access. The cloud trust policy and role permissions control that separately.

If you use GitHub Environments, put production credentials on the protected environment and configure its deployment branch rules and required reviewers where available for your repository plan. The job should reference that environment so its protection rules run before the job can access environment secrets. An environment name by itself does not restrict which branches may deploy. See GitHub's environment configuration guide.

Keep the plan and approval connected

For a production deployment, create the plan from a trusted, protected-branch commit. Show reviewers the resource changes and any warnings, then make the apply job use the exact plan that was reviewed. A saved plan is not a harmless text report: it contains a copy of the configuration, state, and variable values used to create it. Treat it as sensitive, restrict artifact access, and remove it after the apply. Do not publish it in a public pull request or repository.

The plan and apply jobs must use compatible Terraform versions, provider plugins, operating systems, and CPU architectures. Allow only one outstanding plan for a workspace at a time. If another deployment changes the state while approval is pending, the earlier plan can no longer be trusted; generate and review a fresh one.

Applying a saved plan does not prompt for Terraform's interactive approval. Make the protected GitHub Environment or another explicit review step the gate before the apply job starts. Avoid -auto-approve for production: it removes Terraform's interactive prompt, not the need to inspect and approve the proposed infrastructure changes. GitHub's workflow status badges can show run status in a README, but a badge is informational; configure a required check if a successful workflow must block or allow merging.

Handle failed applies and temporary environments carefully

Terraform does not automatically roll back an apply that fails partway through. Some resources may already have changed. Check the error and the actual infrastructure, then create a new plan before deciding what to do next; do not assume that rerunning the previous plan is a rollback.

Temporary environments for pull requests can help a team inspect a proposed change, but give each environment isolated state, restrict access, and automate cleanup so abandoned infrastructure does not remain running. This Terraform and GitHub Actions guide from env0 describes an example workflow. Use it as an implementation reference, not as a substitute for reviewing your own state, access, and cost controls.

For a practical introduction to protecting tokens in workflows, see this GitHub Actions secrets walkthrough alongside GitHub's official secure-use documentation.

Official documentation

Cover Photo by Mohammad Rahmani on Unsplash

Leave a Reply