How does Terraform work in fully automated pipelines with plan PR comments and apply on merge?

Answer

A mature Terraform CI/CD pipeline implements the following flow. On a pull request: authenticate with the cloud provider using OIDC (short-lived tokens, no static secrets), run terraform init to configure the backend and download providers, run terraform fmt -check and terraform validate for syntax correctness, run terraform plan -out=plan.tfplan, and post the plan output as a PR comment using tools like github-actions-terraform or Atlantis. Policy gates run OPA or Checkov against the plan to reject non-compliant changes (e.g., unencrypted S3 buckets, overly permissive IAM policies). On merge to main: authenticate again via OIDC, download the saved plan artifact (to ensure apply matches what was reviewed), run terraform apply plan.tfplan, and post the apply output as a comment on the merged PR. State locking (DynamoDB) prevents concurrent applies. Using a saved plan file is critical — it ensures that the exact changes reviewed in the PR comment are applied, preventing race conditions where the infrastructure state changed between plan and apply.