Terraform and GitHub Actions secure CI/CD pipeline with shield and lock

Secure CI/CD with Terraform and GitHub Actions (2026 Guide)

Infrastructure as code made cloud changes reviewable, repeatable and fast. It also turned your CI/CD pipeline into one of the most powerful identities in your company. Whatever can run terraform apply can usually create, change or destroy production. That is why a Terraform GitHub Actions setup deserves the same security attention as your production servers.

This guide walks through a practical, security-first pipeline: plan on pull requests, apply on the main branch behind an approval gate, short-lived cloud credentials through OIDC, locked remote state, pinned actions, scanning and policy checks. Every recommendation links to official documentation so you can verify it yourself.

Terraform and GitHub Actions in 60 Seconds

Terraform is HashiCorp’s infrastructure-as-code tool. You describe resources (networks, databases, IAM roles, DNS records) in HCL files, and Terraform works out what needs to change to make the real world match the code. The core workflow is short:

  • terraform init downloads providers and connects to the state backend.
  • terraform plan compares code with state and shows the proposed changes.
  • terraform apply executes those changes.

GitHub Actions is GitHub’s built-in automation platform. Workflows are YAML files under .github/workflows/ that run on events such as pull_request or push. Put the two together and every infrastructure change goes through a pull request, gets an automatic plan for reviewers, and is applied only after merge. No more “I ran apply from my laptop.”

If you are newer to containers and platform tooling, our explainer on Docker vs Kubernetes is a good companion read, since many Terraform projects end up provisioning container platforms.

The Recommended Pipeline: Plan on PR, Apply on Main

The safest common pattern splits the pipeline into two jobs with different trust levels:

  • Plan job runs on every pull request. It uses a read-only cloud role, runs format, validate and plan, and shows the result to reviewers.
  • Apply job runs only on pushes to main. It targets a protected GitHub environment (for example production) that requires a human approval before the job can start or access the environment’s secrets.

Here is a complete workflow for AWS. Notice that the permissions are set per job, the actions are pinned to full commit SHAs, and there are no access keys anywhere.

name: terraform

on:
  pull_request:
    branches: [main]
    paths: ["infra/**"]
  push:
    branches: [main]
    paths: ["infra/**"]

permissions: {}   # nothing by default; each job asks for what it needs

concurrency:
  group: terraform-${{ github.ref }}
  cancel-in-progress: false

jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write        # needed to request the OIDC token
      pull-requests: write   # only if you post the plan as a PR comment
    defaults:
      run:
        working-directory: infra
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
      - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
        with:
          role-to-assume: arn:aws:iam::111122223333:role/gha-terraform-plan
          aws-region: ap-south-1
      - run: terraform fmt -check -recursive
      - run: terraform init -input=false
      - run: terraform validate
      - run: terraform plan -input=false -lock-timeout=5m -out=tfplan

  apply:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production   # required reviewers gate this job
    permissions:
      contents: read
      id-token: write
    defaults:
      run:
        working-directory: infra
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false
      - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4.0.1
      - uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
        with:
          role-to-assume: arn:aws:iam::111122223333:role/gha-terraform-apply
          aws-region: ap-south-1
      - run: terraform init -input=false
      - run: terraform plan -input=false -lock-timeout=5m -out=tfplan
      - run: terraform apply -input=false tfplan

A few details worth calling out:

  • permissions: {} at the top means a job gets nothing unless it asks. New jobs added later do not silently inherit write access.
  • concurrency prevents two applies from racing each other. State locking (covered below) is the second line of defence.
  • persist-credentials: false stops the checkout action from leaving a Git token on disk for later steps.

Use OIDC Instead of Long-Lived Cloud Secrets

The old pattern was to create an IAM user, generate access keys and paste them into repository secrets. Those keys never expire on their own, they are easy to leak in logs, and anyone who steals them can use them from anywhere.

GitHub’s OpenID Connect support replaces that with short-lived tokens. On each run, GitHub issues a signed JWT describing the workflow (repository, branch, environment and more). Your cloud provider checks the token against a trust policy and returns temporary credentials that expire shortly after the job ends. The job must have id-token: write to request the token; that permission does not grant write access to anything else.

Lock down the trust policy

OIDC is only as strong as the conditions on the cloud side. GitHub’s docs state that you must define at least one condition so untrusted repositories cannot get tokens for your cloud. In practice:

  • Match the sub claim exactly, for example repo:my-org/infra:environment:production for the apply role, rather than wildcards like repo:my-org/*.
  • Use separate roles: a read-only role for plan on pull requests and a write role that only trusts the production environment.
  • Check the aud claim (for AWS it is sts.amazonaws.com).
  • Prefer GitHub’s newer immutable subject format (which includes owner and repository IDs) where available, so a deleted and recreated repository name cannot inherit trust. Repositories created after 15 July 2026 use it by default; older ones can opt in.

AWS, Azure and GCP snippets

Each major cloud has an official login action. The workflow side always looks similar:

# AWS: IAM OIDC identity provider + role trust policy
- uses: aws-actions/configure-aws-credentials@45666896f5d8e0f10ae255413f3a4cdd03bdc8f5 # v6.3.1
  with:
    role-to-assume: arn:aws:iam::111122223333:role/gha-terraform-apply
    aws-region: ap-south-1

# Azure: federated credential on an app registration or managed identity
- uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
  with:
    client-id: ${{ vars.AZURE_CLIENT_ID }}
    tenant-id: ${{ vars.AZURE_TENANT_ID }}
    subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
# Terraform azurerm provider: set ARM_USE_OIDC=true plus the same IDs

# GCP: Workload Identity Federation
- uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3
  with:
    workload_identity_provider: projects/123456789/locations/global/workloadIdentityPools/github/providers/my-repo
    service_account: terraform@my-project.iam.gserviceaccount.com

Remote State With Locking

Terraform state maps your code to real resources, and it often contains sensitive values such as generated passwords or connection strings. Two rules follow: never commit state to Git, and always store it in a remote backend with encryption, access control and locking. Locking stops two runs from writing state at the same time and corrupting it.

Platform Backend Locking Notes
AWS s3 use_lockfile = true (S3 native lock file) DynamoDB-based locking still works but HashiCorp marks it deprecated; enable bucket versioning and encryption.
Azure azurerm Built in via blob leases Supports OIDC with use_oidc = true; restrict storage account network access.
Google Cloud gcs Built in Turn on object versioning for recovery.
Any HCP Terraform (cloud block) Built in Managed state, run history, policy sets and team access controls.

A minimal S3 backend with native locking looks like this:

terraform {
  backend "s3" {
    bucket       = "my-org-tf-state"
    key          = "prod/network/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}

Least-Privilege GITHUB_TOKEN Permissions

Every workflow run receives an automatic GITHUB_TOKEN. Depending on when your organization was created and how it is configured, its default scope can be read-only or read/write. Do not rely on the default:

  • In organization and repository settings, set the default workflow permissions to read repository contents.
  • Declare permissions explicitly in every workflow, ideally per job, as in the example above.
  • Grant pull-requests: write only to the job that posts plan comments, and id-token: write only to jobs that log in to a cloud.
  • Be very careful with the pull_request_target trigger. It runs with the base repository’s permissions and secrets, so never check out and execute untrusted pull request code under it.

Pin Actions to a Full Commit SHA

When you write uses: some-org/some-action@v4, you trust whoever controls that tag. Tags can be moved. GitHub’s security hardening guide says pinning to a full-length commit SHA is currently the only way to use an action as an immutable release.

This is not theoretical. In March 2025, the popular tj-actions/changed-files action was compromised and its version tags were pointed at malicious code that dumped CI secrets into workflow logs. It is tracked as GHSA-mrrh-fwg8-r2c3 (CVE-2025-30066). Workflows pinned to an older, known-good SHA were not affected by the moved tags.

Practical tips:

  • Pin with a trailing comment showing the human version, for example # v7.0.1, so reviewers know what they are looking at.
  • Let Dependabot propose SHA bumps so pinning does not mean “never update.”
  • Organization admins can use the Actions policy settings to allow only selected actions and, where available, require SHA pinning.

Secrets, Environments and Required Reviewers

OIDC removes most cloud secrets, but you will still have some: API tokens for a DNS provider, a Terraform registry token, a monitoring key. Handle them carefully:

  • Use environment secrets for anything production-only. They are only available to jobs that target that environment, and only after its protection rules pass.
  • Configure required reviewers on the production environment, and enable “prevent self-review” so the person who pushed cannot approve their own deployment.
  • Restrict deployment branches so only main (or release branches) can deploy to production.
  • Mark Terraform outputs and variables as sensitive so they are redacted in plan output.

Branch Protection and Rulesets

Your pipeline trusts main, so main must be hard to change. Use repository rulesets (or classic branch protection) to:

  • Require pull requests with at least one approving review before merging.
  • Require status checks to pass, including the Terraform plan job and your security scans.
  • Require review from code owners for .github/workflows/ and infra/ via a CODEOWNERS file.

Dependabot, CodeQL, Secret Scanning and Push Protection

GitHub ships several security features that fit naturally into an IaC repository:

  • Dependabot version updates support both the terraform ecosystem (providers and modules) and the github-actions ecosystem, which keeps your pinned SHAs fresh.
  • CodeQL code scanning can analyze your GitHub Actions workflows themselves and flag risky patterns such as script injection from untrusted input.
  • Secret scanning detects known credential formats committed to the repository, and push protection blocks those commits before they land.
# .github/dependabot.yml
version: 2
updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
  - package-ecosystem: "terraform"
    directory: "/infra"
    schedule:
      interval: "weekly"

Secret scanning and Dependabot are free for public repositories; private repositories need GitHub Advanced Security products (Secret Protection and Code Security) for the full feature set. Check your plan before you count on them.

Policy as Code: Trivy, Checkov and OPA/Conftest

Human reviewers miss things in a 400-line plan. Automated policy checks catch the common mistakes (public buckets, open security groups, unencrypted disks) before they reach production.

  • Trivy (which absorbed the earlier tfsec project) scans Terraform for misconfigurations.
  • Checkov ships hundreds of built-in policies for Terraform and other IaC formats.
  • OPA with Conftest lets you write your own rules in Rego, for example “every resource must have an owner tag” or “no instance types bigger than X in dev”. Run them against terraform show -json tfplan output so you evaluate the real planned change.
  • HCP Terraform users can enforce Sentinel or OPA policy sets natively before apply.

Supply-Chain Risks You Should Plan For

A Terraform pipeline pulls code from many places. Each is a possible entry point:

  • Third-party actions: pin, review and limit them, as covered above.
  • Terraform providers: commit .terraform.lock.hcl so provider versions and checksums are locked and verified on every run.
  • Modules: pin registry modules to exact versions and Git modules to a commit or tag you control.
  • Untrusted input: pull request titles, branch names and issue bodies can contain shell injection payloads. Pass them through environment variables, not directly into run: scripts.

The OWASP Top 10 CI/CD Security Risks is a useful map of these threats, from poisoned pipeline execution to insufficient credential hygiene. Security tooling for open source is evolving quickly too; see our take on AI-assisted open-source security scanning.

Do’s and Don’ts

Do Don’t
Use OIDC with tightly scoped trust policies Store long-lived cloud access keys in repository secrets
Set permissions explicitly per job Rely on a read/write default GITHUB_TOKEN
Pin actions to full commit SHAs Use @main or movable tags for third-party actions
Use remote state with encryption and locking Commit terraform.tfstate to Git
Gate apply behind a protected environment with reviewers Auto-apply from feature branches
Separate plan (read) and apply (write) roles Give the pipeline administrator access “for now”
Run Trivy/Checkov/Conftest as required checks Rely only on manual review of large plans
Commit .terraform.lock.hcl Let provider versions float between runs

Quick Security Checklist

  • Default workflow permissions set to read-only at org/repo level.
  • Every job declares minimal permissions.
  • Cloud access via OIDC; trust policies match exact sub and aud.
  • Separate plan and apply roles; apply role trusts only the production environment.
  • production environment has required reviewers and branch restrictions.
  • Remote state is encrypted, versioned and locked.
  • All actions pinned to full SHAs; Dependabot tracks github-actions and terraform.
  • Rulesets require PR reviews, status checks and CODEOWNERS for workflows and infra.
  • Secret scanning and push protection enabled; CodeQL scans workflows.
  • IaC scanning and policy checks block risky changes.
  • No pull_request_target running untrusted code; no self-hosted runners on public repos.

For the wider organizational view, our guide on building a comprehensive IT security plan shows where pipeline security fits in the bigger picture.

Frequently Asked Questions

Is it safe to run terraform apply from GitHub Actions?

Yes, if you control who and what can trigger it. Use OIDC instead of stored keys, restrict apply to the main branch, require approval through a protected environment, and give the apply role only the permissions your infrastructure actually needs.

Do I still need secrets if I use OIDC?

Usually far fewer. OIDC replaces cloud credentials, but third-party APIs without OIDC support still need tokens. Store those as environment secrets behind required reviewers and rotate them regularly.

Should I use DynamoDB for Terraform state locking on AWS?

For new setups, HashiCorp’s S3 backend documentation recommends the native S3 lock file (use_lockfile = true) and marks DynamoDB-based locking as deprecated. Existing setups can enable both during migration.

Why pin actions to a commit SHA instead of a version tag?

Tags can be moved to point at different code, as happened in the tj-actions/changed-files incident. A full commit SHA is immutable, so you run exactly the code you reviewed.

Which IaC scanner should I choose: Trivy, Checkov or Conftest?

They complement each other. Trivy and Checkov give you broad built-in rules quickly. Conftest with OPA is best for organization-specific rules. Many teams run one built-in scanner plus a small set of custom Rego policies.

Can I show the Terraform plan in the pull request?

Yes. A common approach is to post a summary as a PR comment, which needs pull-requests: write on that job only. Be careful: plans may include sensitive values, so mark variables and outputs as sensitive and avoid posting full plans on public repositories.

Wrapping Up

A secure Terraform GitHub Actions pipeline is not one big feature; it is a stack of small, boring controls. Short-lived OIDC credentials, minimal token permissions, pinned actions, locked state, protected environments and automated policy checks each close a specific door. Put them in place once as a template, reuse it across repositories, and your infrastructure changes become both faster and safer.

Looking for more hands-on DevOps basics? Brush up with our list of common Docker commands you must know.

Sources

Content Protection by DMCA.com
Spread the love
Scroll to Top
×