0
0
Terraformcloud~15 mins

Terraform plan for preview - Deep Dive

Choose your learning style9 modes available
Overview - Terraform plan for preview
What is it?
Terraform plan for preview is a command that shows you what changes Terraform will make to your cloud infrastructure before actually applying them. It creates a detailed report of resources to be added, changed, or destroyed without making any real changes. This helps you understand the impact of your configuration updates safely.
Why it matters
Without previewing changes, you risk accidentally breaking or deleting important parts of your infrastructure. Terraform plan lets you catch mistakes early, avoid downtime, and maintain control over your cloud environment. It acts like a rehearsal before the real deployment, saving time and preventing costly errors.
Where it fits
Before using Terraform plan, you should know basic Terraform concepts like configuration files and resource definitions. After mastering plan, you will learn how to apply changes safely and manage state files. It fits early in the Terraform workflow, between writing code and applying it.
Mental Model
Core Idea
Terraform plan previews the exact changes Terraform will make to your infrastructure without applying them, acting as a safe rehearsal.
Think of it like...
It's like reading the script of a play before the actors perform on stage, so you know what will happen without changing anything yet.
┌───────────────┐
│ Terraform     │
│ Configuration │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ terraform plan│
│ (preview)     │
└──────┬────────┘
       │ Shows planned changes
       ▼
┌───────────────┐
│ Change Report │
│ (add, modify, │
│  destroy)     │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Terraform plan command
🤔
Concept: Introducing the terraform plan command and its purpose.
Terraform plan is a command you run after writing your infrastructure code. It reads your configuration and current cloud state, then shows what will change if you apply your code. It does not change anything yet.
Result
You get a list of resources to be created, updated, or deleted.
Understanding that terraform plan previews changes without applying them helps you avoid surprises.
2
FoundationHow Terraform detects changes
🤔
Concept: Terraform compares your code with the current state to find differences.
Terraform keeps a state file recording your current infrastructure. When you run plan, it compares this state with your new code. Differences mean changes are needed.
Result
Terraform outputs a plan showing exactly what will be added, changed, or removed.
Knowing that Terraform uses state to detect changes explains why keeping state accurate is crucial.
3
IntermediateReading the plan output details
🤔Before reading on: do you think terraform plan output shows only new resources or also changes and deletions? Commit to your answer.
Concept: Understanding the symbols and sections in terraform plan output.
The plan output uses symbols: '+' means add, '~' means modify, '-' means delete. It groups changes by resource type and name, showing attribute differences.
Result
You can interpret what exactly will happen to each resource before applying.
Recognizing symbols and details in plan output lets you verify changes carefully.
4
IntermediateUsing plan with variables and workspaces
🤔Before reading on: do you think terraform plan automatically uses default variables and workspace or requires explicit input? Commit to your answer.
Concept: How terraform plan respects variable values and workspace context.
Terraform plan uses the current workspace and variable values you provide or defaults. You can pass variable files or override variables at plan time to preview different scenarios.
Result
You get accurate previews matching your intended environment and inputs.
Knowing how variables and workspaces affect plan output prevents mismatches between preview and apply.
5
IntermediateSaving and sharing plan output files
🤔
Concept: Terraform can save the plan to a file for later use or sharing.
Using 'terraform plan -out=planfile' saves the plan in a binary file. This file can be applied later with 'terraform apply planfile' ensuring the exact changes are applied. It also helps in team reviews.
Result
You can review, share, and apply a fixed plan safely.
Saving plan output ensures consistency between preview and apply, reducing risks.
6
AdvancedPlan lifecycle and state locking
🤔Before reading on: do you think terraform plan modifies state or locks it? Commit to your answer.
Concept: Terraform plan reads state but does not modify or lock it; locking happens during apply.
Terraform plan reads the current state file to compare resources but does not change or lock it. State locking to prevent concurrent changes happens only during apply. This means plan can be run multiple times safely.
Result
You can preview changes without blocking others, but must be careful about state changes between plan and apply.
Understanding plan's read-only nature clarifies why state consistency is important between plan and apply.
7
ExpertPlan refresh and drift detection nuances
🤔Before reading on: does terraform plan always refresh state before planning? Commit to your answer.
Concept: Terraform plan refreshes state by default but can be controlled; this affects drift detection.
By default, terraform plan refreshes the state by querying real infrastructure to detect drift. You can disable refresh with '-refresh=false' to speed up plan but risk missing changes made outside Terraform. This tradeoff affects accuracy and performance.
Result
You control whether plan detects external changes or runs faster without refresh.
Knowing refresh behavior helps balance speed and accuracy in complex environments.
Under the Hood
Terraform plan works by loading the current state file, parsing the configuration files, and then performing a diff between the desired state and current state. It queries cloud providers to refresh resource states unless disabled. It builds a graph of resource dependencies to order changes logically. The output is a detailed plan showing resource actions without changing any real infrastructure or state files.
Why designed this way?
Terraform was designed to separate planning from applying to give users confidence and control. This two-step approach reduces accidental changes and downtime. Refreshing state during plan ensures accurate detection of drift. Saving plans to files supports automation and collaboration. Alternatives like immediate apply without preview were rejected to avoid risky blind changes.
┌───────────────┐
│ Config Files  │
└──────┬────────┘
       │
       ▼
┌───────────────┐      ┌───────────────┐
│ State File    │◄─────┤ Cloud APIs    │
└──────┬────────┘      └──────┬────────┘
       │                     │
       ▼                     ▼
┌───────────────────────────────┐
│ Terraform Plan Engine          │
│ - Parses config               │
│ - Refreshes state             │
│ - Compares desired vs current │
│ - Builds change graph         │
└──────────────┬────────────────┘
               │
               ▼
       ┌───────────────┐
       │ Plan Output   │
       │ (Preview)     │
       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does terraform plan apply changes to your cloud? Commit yes or no.
Common Belief:Terraform plan actually makes changes to your infrastructure.
Tap to reveal reality
Reality:Terraform plan only shows what changes would happen; it does not apply any changes.
Why it matters:Believing plan applies changes can cause confusion and fear, preventing safe previews.
Quick: Does terraform plan always detect all changes made outside Terraform? Commit yes or no.
Common Belief:Terraform plan always detects any changes made manually in the cloud.
Tap to reveal reality
Reality:Terraform plan detects drift only if state refresh is enabled; otherwise, it may miss manual changes.
Why it matters:Missing drift can cause Terraform to overwrite manual changes unexpectedly.
Quick: Can you run terraform apply with a saved plan file from a different workspace? Commit yes or no.
Common Belief:You can apply any saved plan file regardless of workspace or variables.
Tap to reveal reality
Reality:Plan files are tied to workspace and variables; applying mismatched plans can cause errors or unexpected results.
Why it matters:Applying wrong plan files risks corrupting infrastructure or causing failures.
Quick: Does terraform plan lock the state file to prevent concurrent changes? Commit yes or no.
Common Belief:Terraform plan locks the state file to prevent others from changing infrastructure.
Tap to reveal reality
Reality:Terraform plan does not lock state; locking happens only during apply.
Why it matters:Assuming plan locks state can lead to race conditions if multiple users apply changes simultaneously.
Expert Zone
1
Terraform plan output can be influenced by provider-specific behaviors, such as computed attributes that appear as changes even if nothing is modified.
2
Using plan with the '-detailed-exitcode' flag allows automation scripts to detect if changes exist without parsing output text.
3
Plan files are binary and not human-readable; they must be applied as-is to ensure consistency, which is critical in CI/CD pipelines.
When NOT to use
Terraform plan is not suitable when you want to make immediate changes without review, such as quick fixes in emergencies. In such cases, direct 'terraform apply' might be used, but with caution. Also, for very large infrastructures, plan can be slow; partial applies or targeted plans might be better.
Production Patterns
In production, teams use terraform plan in CI pipelines to generate and review change previews before manual approval. Saved plan files ensure the exact reviewed changes are applied later. Plans are also used in pull request checks to show impact of proposed changes.
Connections
Version Control Systems
Builds-on
Understanding terraform plan helps appreciate how version control previews code changes before merging, both aiming to prevent unexpected outcomes.
Continuous Integration/Continuous Deployment (CI/CD)
Builds-on
Terraform plan integrates with CI/CD pipelines to automate safe previews of infrastructure changes, enabling reliable and repeatable deployments.
Scientific Experiment Planning
Similar pattern
Just like scientists plan experiments to predict outcomes before running them, terraform plan forecasts infrastructure changes to avoid risks.
Common Pitfalls
#1Running terraform apply without reviewing plan output first.
Wrong approach:terraform apply
Correct approach:terraform plan # Review output terraform apply
Root cause:Skipping the preview step leads to unexpected destructive changes or errors.
#2Applying a saved plan file created with different variables or workspace.
Wrong approach:terraform apply savedplanfile # savedplanfile was created in a different workspace or with different variables
Correct approach:terraform plan -out=savedplanfile -var='correct_values' -workspace=correct_workspace terraform apply savedplanfile
Root cause:Plan files are environment-specific; mismatch causes errors or wrong changes.
#3Disabling state refresh during plan without understanding consequences.
Wrong approach:terraform plan -refresh=false
Correct approach:terraform plan # or use -refresh=false only when sure no external changes occurred
Root cause:Disabling refresh can hide drift, causing Terraform to miss manual changes.
Key Takeaways
Terraform plan previews infrastructure changes safely without applying them, acting as a rehearsal.
It compares your desired configuration with current state and cloud resources to detect additions, modifications, and deletions.
Reading plan output carefully helps prevent accidental destructive changes and downtime.
Saving plan output to a file ensures consistency between preview and apply, supporting collaboration and automation.
Understanding plan's refresh and state locking behavior is key to managing drift and concurrency in real environments.