Write a Terraform plan-on-PR, apply-on-merge workflow.
AdvancedHands-onWrite-a-pipeline tasks
Answer
name: terraform
on:
pull_request: { paths: ["infra/**"] }
push: { branches: [main], paths: ["infra/**"] }
permissions:
id-token: write
contents: read
pull-requests: write
jobs:
tf:
runs-on: ubuntu-latest
defaults: { run: { working-directory: infra } }
concurrency: { group: tf-infra, cancel-in-progress: false }
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: 1.9.8 }
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/gha-terraform
aws-region: ap-south-1
- run: terraform init -input=false
- run: terraform fmt -check
- run: terraform validate
- run: terraform plan -input=false -out=tfplan
- if: github.event_name == 'pull_request'
run: terraform show -no-color tfplan > plan.txt
- if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const plan = require('fs').readFileSync('infra/plan.txt', 'utf8').slice(0, 60000);
github.rest.issues.createComment({ ...context.repo, issue_number: context.issue.number,
body: "```\n" + plan + "\n```" });
- if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: terraform apply -input=false tfplan
Key trick → concurrency with cancel-in-progress: false queues runs so two applies never race on state, and applying the saved tfplan guarantees you apply exactly what was planned.
More on Write-a-pipeline tasks
Write a GitHub Actions workflow that runs tests on every PR and push to main.BeginnerWrite a workflow that builds a Docker image and pushes it to ECR using OIDC (no access keys).IntermediateWrite a matrix job that tests on Python 3.10, 3.11 and 3.12 on Linux and Windows.BeginnerWrite a declarative Jenkinsfile with build, test, Docker push and a manual approval before prod.AdvancedWrite a GitHub Actions deploy job that requires approval for production using environments.BeginnerWrite a reusable workflow and call it from another repo.Intermediate