How to Use Terraform Plan: Syntax, Example, and Tips
Use the
terraform plan command to preview changes Terraform will make to your infrastructure without applying them. It shows a detailed execution plan so you can verify changes before running terraform apply.Syntax
The basic syntax of terraform plan is simple and can include optional flags to customize the output.
terraform plan: Shows the execution plan for the current configuration.-out=filename: Saves the plan to a file for later use withterraform apply.-var 'key=value': Sets a variable value for the plan.-input=false: Disables interactive input during the plan.
bash
terraform plan [options] # Common options: # -out=planfile.tfplan # -var 'key=value' # -input=false
Example
This example shows how to run terraform plan on a simple AWS EC2 instance configuration. It previews the creation of the instance without making any changes.
hcl
provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } # Run terraform init first to initialize # Then run terraform plan to see the changes
Output
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.example will be created
+ resource "aws_instance" "example" {
+ ami = "ami-0c55b159cbfafe1f0"
+ instance_type = "t2.micro"
+ id = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Common Pitfalls
Common mistakes when using terraform plan include:
- Not running
terraform initbefore planning, causing errors. - Forgetting to save the plan with
-outwhen you want to apply the exact plan later. - Ignoring variable values, leading to unexpected plans.
- Running
terraform planin the wrong directory without configuration files.
bash
Wrong way:
terraform plan
# If you want to apply the exact plan later, do this:
terraform plan -out=myplan.tfplan
terraform apply myplan.tfplanQuick Reference
Here is a quick summary of useful terraform plan options:
| Option | Description |
|---|---|
| terraform plan | Show the execution plan for current config |
| -out=filename | Save the plan to a file for later apply |
| -var 'key=value' | Set or override variable values |
| -input=false | Disable interactive input during plan |
| -refresh=true/false | Control state refresh before planning |
Key Takeaways
Always run terraform plan to preview changes before applying.
Use -out option to save the plan for exact apply later.
Run terraform init first to initialize your working directory.
Check variable values carefully to avoid unexpected changes.
Run terraform plan in the directory with your Terraform files.