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.
Previous
How is chaos engineering integrated into CD pipelines?
Next
What is compliance as code and how do tools like OPA enforce it in pipelines?
More CI/CD Pipelines Questions
View all →- Advanced What are the core principles of GitOps?
- Advanced What is progressive delivery and how does it extend beyond basic canary releases?
- Advanced How is chaos engineering integrated into CD pipelines?
- Advanced What is compliance as code and how do tools like OPA enforce it in pipelines?
- Advanced What is software supply chain security and what are SLSA levels, SBOMs, and image signing?