Bird
Raised Fist0
Terraformcloud~15 mins

Code review for infrastructure changes in Terraform - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Code review for infrastructure changes
What is it?
Code review for infrastructure changes is the process of examining changes made to infrastructure code before applying them. It ensures that updates to cloud resources are safe, efficient, and follow best practices. This helps prevent errors that could cause downtime or security issues. It is like double-checking a recipe before cooking to avoid mistakes.
Why it matters
Without code review, infrastructure changes can introduce bugs, security holes, or costly mistakes that affect live systems. This can lead to outages, data loss, or unexpected expenses. Code review acts as a safety net, catching problems early and improving collaboration among teams. It makes infrastructure updates more reliable and predictable.
Where it fits
Before learning code review, you should understand infrastructure as code basics and how to write Terraform configurations. After mastering code review, you can learn about automated testing, continuous integration, and deployment pipelines for infrastructure.
Mental Model
Core Idea
Code review for infrastructure changes is a careful check of proposed updates to infrastructure code to catch errors and improve quality before applying them.
Think of it like...
It's like having a friend proofread your instructions before you build a piece of furniture, so you don't miss a step or use the wrong part.
┌───────────────────────────────┐
│ Developer writes infrastructure │
│ code changes (Terraform)       │
└───────────────┬───────────────┘
                │
                ▼
┌───────────────────────────────┐
│ Code review by team members    │
│ - Check correctness            │
│ - Check security               │
│ - Check best practices         │
└───────────────┬───────────────┘
                │
                ▼
┌───────────────────────────────┐
│ Approved changes applied       │
│ to infrastructure safely      │
└───────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Infrastructure as Code
🤔
Concept: Learn what infrastructure as code means and why Terraform is used to manage cloud resources.
Infrastructure as code means writing code to define and manage cloud resources like servers, networks, and databases. Terraform is a tool that lets you write this code in files, so you can create, update, or delete resources automatically. This replaces manual clicks in cloud consoles with repeatable code.
Result
You can describe your cloud setup in code files that Terraform understands.
Understanding infrastructure as code is essential because code review only works if infrastructure is defined as code.
2
FoundationBasics of Terraform Configuration Files
🤔
Concept: Learn the structure and purpose of Terraform files that describe infrastructure.
Terraform uses files ending with .tf to describe resources. These files include blocks like 'resource', 'variable', and 'output'. Each resource block defines a cloud component, such as a virtual machine or storage bucket. Variables let you customize configurations, and outputs show important information after deployment.
Result
You can read and write simple Terraform files that define cloud resources.
Knowing Terraform file structure helps you understand what changes are being reviewed.
3
IntermediateWhat to Check in Infrastructure Code Reviews
🤔Before reading on: do you think code review should focus only on syntax errors or also on security and cost? Commit to your answer.
Concept: Code review covers correctness, security, cost, and best practices, not just syntax.
During code review, reviewers check if the code will create the intended resources correctly. They look for security issues like open network ports or weak permissions. They also consider cost impacts, such as creating expensive resources unnecessarily. Best practices include naming conventions and modular design.
Result
Code reviews catch many issues before deployment, improving safety and quality.
Understanding the broad scope of code review prevents overlooking critical risks beyond simple errors.
4
IntermediateUsing Pull Requests for Infrastructure Changes
🤔Before reading on: do you think pull requests are only for application code or also useful for infrastructure code? Commit to your answer.
Concept: Pull requests are a common way to propose and review infrastructure code changes collaboratively.
Developers create a branch with their Terraform changes and open a pull request (PR) in a version control system like GitHub. Team members review the PR, comment on issues, and approve or request changes. This process creates a clear history and discussion around infrastructure updates.
Result
Infrastructure changes are reviewed transparently and collaboratively before merging.
Knowing how pull requests work helps integrate infrastructure code review into existing development workflows.
5
IntermediateAutomating Checks with Terraform Plan
🤔Before reading on: do you think running 'terraform plan' automatically is helpful or unnecessary in code review? Commit to your answer.
Concept: 'terraform plan' shows what changes Terraform will make, helping reviewers understand impact.
Terraform plan is a command that previews changes without applying them. Integrating it into code review pipelines lets reviewers see exactly what resources will be created, changed, or destroyed. Automated checks can also validate syntax and run security scanners.
Result
Reviewers get clear, automated insights into proposed infrastructure changes.
Using terraform plan in reviews reduces guesswork and prevents unintended changes.
6
AdvancedHandling Secrets and Sensitive Data in Reviews
🤔Before reading on: should secrets be included directly in Terraform code or handled differently? Commit to your answer.
Concept: Secrets must be managed securely and not exposed in code reviews.
Sensitive data like passwords or API keys should never be hardcoded in Terraform files. Instead, use secure storage solutions or environment variables. Code reviews should verify that secrets are handled properly and not leaked. Tools can scan for accidental secret exposure.
Result
Infrastructure code remains secure and secrets are protected during review.
Knowing how to handle secrets prevents serious security breaches from code exposure.
7
ExpertReviewing Complex Terraform Modules and State Changes
🤔Before reading on: do you think reviewing Terraform modules and state changes is straightforward or requires special attention? Commit to your answer.
Concept: Complex modules and state changes need careful review to avoid hidden risks.
Terraform modules are reusable code packages that can hide complexity. Reviewing them requires understanding their inputs, outputs, and side effects. State files track real infrastructure and can cause drift if not managed well. Reviewers must check that module updates and state changes won't cause resource conflicts or data loss.
Result
Infrastructure updates are safe even when using advanced Terraform features.
Understanding modules and state intricacies prevents subtle bugs and downtime in production.
Under the Hood
Terraform code is parsed and converted into a plan that describes desired cloud resources. The plan compares current infrastructure state with the desired state. Code review happens before applying the plan, allowing humans to inspect the intended changes. Terraform state files track real resources, and changes update this state. Code review ensures the plan matches expectations and avoids harmful changes.
Why designed this way?
Terraform separates planning from applying to give users a chance to verify changes. Code review fits naturally in this gap to catch errors early. This design reduces risks of manual mistakes and supports collaboration. Alternatives like manual cloud console changes lack this safety and repeatability.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ Terraform     │      │ Terraform     │      │ Terraform     │
│ Code (.tf)   ─┼─────▶│ Plan          ├─────▶│ Apply         │
└───────────────┘      └─────┬─────────┘      └─────┬─────────┘
                              │                     │
                              ▼                     ▼
                      ┌───────────────┐      ┌───────────────┐
                      │ Code Review   │      │ Cloud         │
                      │ (Human check) │      │ Infrastructure│
                      └───────────────┘      └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Is code review only about finding syntax errors? Commit yes or no.
Common Belief:Code review is just about catching syntax or formatting mistakes.
Tap to reveal reality
Reality:Code review also checks security, cost, architecture, and operational impact.
Why it matters:Focusing only on syntax misses serious risks like security holes or expensive mistakes.
Quick: Should secrets be stored directly in Terraform files? Commit yes or no.
Common Belief:It's okay to put passwords or keys directly in Terraform code for convenience.
Tap to reveal reality
Reality:Secrets must be stored securely outside code to avoid leaks during reviews or version control.
Why it matters:Exposing secrets can lead to security breaches and unauthorized access.
Quick: Can automated tests replace human code review completely? Commit yes or no.
Common Belief:Automated tests mean we don't need human reviewers for infrastructure code.
Tap to reveal reality
Reality:Automated tests help but human judgment is essential for context, security, and design decisions.
Why it matters:Skipping human review can let subtle or context-specific errors slip into production.
Quick: Is reviewing Terraform modules the same as reviewing simple resource blocks? Commit yes or no.
Common Belief:Modules are just like simple resource blocks and need no special review.
Tap to reveal reality
Reality:Modules can hide complexity and side effects, requiring deeper understanding during review.
Why it matters:Ignoring module complexity can cause unexpected resource changes or conflicts.
Expert Zone
1
Reviewing Terraform state file changes is critical because state drift can cause resource duplication or deletion without warning.
2
Understanding provider-specific behaviors helps catch subtle bugs, as different cloud providers interpret resource definitions differently.
3
Code review should include checking for idempotency to ensure repeated applies don't cause unintended changes.
When NOT to use
Code review is less effective if infrastructure is managed manually or with tools that do not support declarative code. In such cases, consider adopting infrastructure as code first. Also, for very small or experimental projects, lightweight reviews or pair programming may be more efficient.
Production Patterns
In production, teams use pull request workflows integrated with CI pipelines that run 'terraform fmt', 'terraform validate', 'terraform plan', and security scans automatically. Reviews focus on plan outputs and security implications. Modules are versioned and reviewed separately. State locking and remote backends prevent conflicts during concurrent changes.
Connections
Software Code Review
Code review for infrastructure changes builds on the same principles as software code review but applies them to cloud resources.
Understanding software code review practices helps grasp infrastructure code review since both aim to improve quality and catch errors early.
Change Management in ITIL
Code review is a technical practice that supports the broader ITIL change management process by ensuring changes are safe and approved.
Knowing ITIL change management helps appreciate why code review is essential for controlled and auditable infrastructure updates.
Quality Control in Manufacturing
Code review acts like quality control in manufacturing, inspecting products before they reach customers to prevent defects.
Seeing code review as quality control highlights its role in preventing costly failures and maintaining trust.
Common Pitfalls
#1Ignoring security checks during code review.
Wrong approach:resource "aws_security_group" "example" { ingress { from_port = 0 to_port = 65535 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } }
Correct approach:resource "aws_security_group" "example" { ingress { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = ["192.168.1.0/24"] } }
Root cause:Not reviewing security group rules carefully leads to overly open access, risking attacks.
#2Committing secrets directly in Terraform files.
Wrong approach:variable "db_password" { default = "SuperSecret123" }
Correct approach:variable "db_password" { type = string sensitive = true } # Password provided via environment variable or secret manager
Root cause:Lack of understanding about secret management causes accidental exposure.
#3Skipping terraform plan review and applying blindly.
Wrong approach:terraform apply -auto-approve
Correct approach:terraform plan # Review plan output carefully terraform apply
Root cause:Ignoring the plan step removes the chance to catch unintended changes.
Key Takeaways
Code review for infrastructure changes is essential to catch errors, security issues, and cost problems before applying updates.
It builds on infrastructure as code principles and uses tools like Terraform plan to preview changes.
Effective reviews cover correctness, security, cost, and best practices, not just syntax.
Secrets must be handled carefully to avoid exposure during reviews.
In production, code review integrates with automated pipelines and version control to ensure safe, reliable infrastructure updates.

Practice

(1/5)
1. What is the main purpose of running terraform plan before applying changes?
easy
A. To apply the changes directly to the cloud resources
B. To preview the changes Terraform will make to the infrastructure
C. To delete all existing infrastructure
D. To create a backup of the current infrastructure state

Solution

  1. Step 1: Understand the role of terraform plan

    This command shows what changes Terraform will perform without making any actual changes.
  2. Step 2: Differentiate from other commands

    terraform apply makes changes, while terraform plan previews them safely.
  3. Final Answer:

    To preview the changes Terraform will make to the infrastructure -> Option B
  4. Quick Check:

    Preview changes = terraform plan [OK]
Hint: Remember: plan previews, apply executes changes [OK]
Common Mistakes:
  • Confusing plan with apply
  • Thinking plan deletes resources
  • Assuming plan creates backups
2. Which of the following is the correct syntax to initialize a Terraform working directory?
easy
A. terraform init
B. terraform start
C. terraform setup
D. terraform configure

Solution

  1. Step 1: Identify the initialization command

    terraform init sets up the working directory by downloading providers and preparing backend.
  2. Step 2: Verify other options

    Commands like terraform start, terraform setup, and terraform configure do not exist in Terraform CLI.
  3. Final Answer:

    terraform init -> Option A
  4. Quick Check:

    Initialize = terraform init [OK]
Hint: Init means start setup in Terraform [OK]
Common Mistakes:
  • Using non-existent commands
  • Confusing init with apply
  • Assuming configure is a Terraform command
3. Given this Terraform snippet:
resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

output "instance_id" {
  value = aws_instance.example.id
}

What will terraform apply output after successful deployment?
medium
A. The ID of the created AWS instance
B. The AMI ID used in the instance
C. The instance type string
D. An error because output is missing

Solution

  1. Step 1: Understand the output block

    The output named instance_id returns the ID of the created AWS instance resource.
  2. Step 2: Confirm output value

    The value is set to aws_instance.example.id, which is the unique instance ID assigned by AWS.
  3. Final Answer:

    The ID of the created AWS instance -> Option A
  4. Quick Check:

    Output shows instance ID = The ID of the created AWS instance [OK]
Hint: Output shows resource attributes, not input values [OK]
Common Mistakes:
  • Confusing output value with input AMI
  • Expecting instance type as output
  • Thinking output block is missing or invalid
4. You see this Terraform code snippet in a pull request:
resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-unique-bucket-name"
  acl    = "public-read"
}

What is the main concern during code review before applying?
medium
A. The bucket name might not be unique globally
B. The code is missing a region specification
C. The resource type is incorrect for S3 buckets
D. The ACL setting makes the bucket publicly readable, which may be a security risk

Solution

  1. Step 1: Analyze the ACL setting

    The ACL is set to public-read, which allows anyone on the internet to read bucket contents.
  2. Step 2: Consider security best practices

    Making buckets public can expose sensitive data; this should be reviewed carefully before applying.
  3. Final Answer:

    The ACL setting makes the bucket publicly readable, which may be a security risk -> Option D
  4. Quick Check:

    Public ACL = security risk [OK]
Hint: Watch for public access settings in code reviews [OK]
Common Mistakes:
  • Ignoring security implications of ACL
  • Assuming bucket name uniqueness is the main issue
  • Thinking region is mandatory in resource block
5. A team wants to share Terraform infrastructure changes for review before applying. Which practice best supports safe collaboration?
hard
A. Send raw Terraform files via email for manual review
B. Run terraform apply directly on the main branch without review
C. Share terraform plan output in a pull request for team feedback
D. Apply changes first, then notify the team

Solution

  1. Step 1: Understand collaboration best practices

    Sharing terraform plan output in pull requests allows the team to see proposed changes safely before applying.
  2. Step 2: Evaluate other options

    Applying changes without review or sending raw files lacks safety and clarity; notifying after applying is risky.
  3. Final Answer:

    Share terraform plan output in a pull request for team feedback -> Option C
  4. Quick Check:

    Plan + PR = safe collaboration [OK]
Hint: Use plan output in PRs for safe team review [OK]
Common Mistakes:
  • Skipping review before apply
  • Sharing raw files without context
  • Applying changes before team agreement