CHAPTER 14
CI/CD with Terraform
Updated: May 15, 2026
25 min read
# CHAPTER 14
CI/CD with Terraform
1. Introduction
If developers are manually typingterraform apply on their laptops, your company is not doing DevOps; you are just typing faster. True Infrastructure as Code maturity requires automation. Infrastructure changes must go through the exact same rigorous review process as application code: submitted via a Pull Request, reviewed by peers, tested by robots, and automatically deployed upon merge. In this chapter, we will integrate Terraform with CI/CD platforms like GitHub Actions, establishing the definitive, enterprise-grade workflow for infrastructure deployment.
2. Learning Objectives
By the end of this chapter, you will be able to:- Explain the necessity of integrating Terraform with CI/CD pipelines.
- Architect a two-phase deployment workflow (Plan on PR, Apply on Merge).
- Configure a GitHub Actions YAML file to execute Terraform safely.
- Understand how to inject cloud credentials securely into the CI/CD runner.
-
Automate posting
terraform planoutput as comments on Pull Requests.
3. Beginner-Friendly Explanation
Imagine proposing a major renovation to an office building.- The Old Way (Laptop Execution): A rogue architect writes a blueprint, walks to the building site at 2:00 AM, and starts knocking down walls without telling anyone.
- The DevOps Way (CI/CD):
- The architect writes the blueprint and submits it to a committee (Opens a Pull Request).
-
A robot (CI/CD) reads the blueprint and creates a 3D simulation of exactly what walls will be knocked down (
terraform plan).
- The committee looks at the simulation. They agree it looks good and sign the approval (Merge).
-
A different robot instantly takes the approved blueprint and physically knocks down the walls (
terraform apply).
4. The Enterprise CI/CD Workflow
A robust infrastructure pipeline relies on strict branch management.-
1.
Developer creates a branch (e.g.,
add-new-database).
-
2.
Developer writes HCL code and opens a Pull Request to
main.
-
3.
CI Pipeline triggers. It runs
terraform fmt,terraform validate, andterraform plan.
-
4.
CI Pipeline comments the output of the
plandirectly onto the GitHub PR so human reviewers can see exactly what will be created/destroyed.
- 5. Team approves and merges.
-
6.
CD Pipeline triggers. Now running on the
mainbranch, it executesterraform apply -auto-approve, modifying the live cloud.
5. Mini Project: Build Terraform CI/CD Workflow
Let's construct the GitHub Actions workflow that executes the "Plan" phase when a Pull Request is opened.Step-by-Step Architecture Concept:
yaml
6. The Magic: PR Comments
Runningterraform plan is useless if the reviewer has to dig through 500 lines of GitHub Actions logs to find the result. We use a marketplace action to extract the plan output and post it as a highly visible comment on the Pull Request.
yaml
7. Real-World Scenarios
A senior engineer manually ranterraform apply from their laptop to add a new IAM user. They didn't realize they had an outdated version of the code on their laptop that was missing a recent database configuration. Terraform saw the discrepancy and deleted the production database to make reality match the engineer's outdated laptop.
Following this disaster, the company revoked all cloud write permissions from human engineers. They forced 100% of infrastructure changes through a Jenkins CI/CD pipeline. The pipeline ensured that terraform apply only ever executed against the absolute latest code in the main branch, permanently eliminating "laptop drift."
8. Best Practices
-
-auto-approveFlag: When runningterraform applyin the CD pipeline (after the merge), the pipeline will hang infinitely waiting for a human to type "yes." You must append the-auto-approveflag to the command. Since the code was already peer-reviewed during the PR phase, this automated execution is considered safe.
9. Security Recommendations
-
Locking State in CI: If two developers merge Pull Requests at the exact same time, two GitHub Actions runners will trigger
terraform applysimultaneously. This is why a remote backend with State Locking (Chapter 5) is an absolute, non-negotiable requirement before implementing CI/CD. The lock ensures one pipeline waits for the other to finish.
10. Troubleshooting Tips
-
Pipeline Permissions: If the "Post Plan to PR" step fails with a
403 Forbiddenerror, check your repository settings. Ensure the automaticGITHUB_TOKENhas read/write permissions for Pull Requests, otherwise it cannot post the comment.
11. Exercises
- 1. Explain the "Plan on PR, Apply on Merge" workflow paradigm.
-
2.
Why is it dangerous for human developers to possess the AWS IAM credentials required to run
terraform applyfrom their local machines?
12. FAQs
Q: Can I use GitLab CI or Bitbucket Pipelines instead of GitHub Actions? A: Absolutely. The terminal commands (init, plan, apply) are completely identical regardless of the CI platform. The only thing that changes is the YAML syntax specific to your chosen pipeline provider.
13. Interview Questions
- Q: Describe the architectural workflow of a fully automated Infrastructure as Code CI/CD pipeline. How do you implement a human-in-the-loop review process without requiring developers to manually execute commands?
- Q: An organization wants to ensure that no infrastructure code is merged if it violates company tagging policies. At what stage in the CI/CD pipeline would you implement this validation, and how?
14. Summary
In Chapter 14, we transitioned from manual execution to true infrastructure automation. We established the industry-standard paradigm: "Plan on Pull Request, Apply on Merge." By integrating Terraform with CI/CD platforms like GitHub Actions, we brought the rigorous quality assurance, peer review, and auditability of software engineering directly into the realm of cloud provisioning. By automating the display ofterraform plan outputs on Pull Requests, we empowered teams to visualize and approve massive architectural changes safely before they ever touch a live cloud environment.