Interview Prep/Real-World Interview/Write-a-pipeline tasks

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.

All Real-World Interview questions Roadmap: Interview readiness

More on Write-a-pipeline tasks