Terraform Plan

One of Terraform’s most powerful features is its ability to show you exactly what changes it will make before applying them. The terraform plan command generates an execution plan, detailing the resources to be created, updated, or destroyed. This transparency helps you avoid surprises when deploying infrastructure.

Why Use terraform plan?

  • Preview changes before making them.
  • Detect potential issues in your configuration.
  • Collaborate more effectively by sharing the plan with your team.

How to Use It?

  • To generate an execution plan: Run terraform plan. Terraform will analyze your configurations and current state to produce a detailed plan.
  • To save the plan for later use: Use the -out flag, e.g., terraform plan -out=myplan.tfplan.
  • To plan for destroying all resources: Use the -destroy flag, e.g., terraform plan -destroy.

Example: Planning Changes

Suppose your main.tf file defines an AWS EC2 instance:

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

Running terraform plan will produce output like this:

Terraform will perform the following actions:

  # aws_instance.example will be created
  + resource "aws_instance" "example" {
      + ami           = "ami-123456"
      + instance_type = "t2.micro"
      ...
    }

Plan: 1 to add, 0 to change, 0 to destroy.

This output tells you that Terraform will create one new resource (aws_instance.example).

If you want to save this plan to apply it later, run terraform plan -out=example.tfplan. This stores the plan in a file that can be used with the terraform apply command.

Use Case

Imagine you're about to deploy changes to a production environment. Running terraform plan allows you to review the impact of those changes in advance, giving you a chance to catch potential issues before they occur. Sharing the plan with stakeholders also ensures everyone is aligned on what’s about to happen.

Conclusion

The terraform plan command is your crystal ball for infrastructure management. By showing you what changes will occur, it helps you maintain control and confidence over your deployments. Always plan before you apply!