Purpose of the terraform plan command

The terraform plan command is used to create an execution plan. Terraform performs a syntax validation of the current configuration, a refresh of state based on the actual environment, and, a comparison of the state against the contents of the configuration.

What happens after running the terraform plan command?

Running the terraform plan command doesn’t alter the actual environment. It may alter the state during the refresh process if it finds that a managed resource has changed since the previous refresh. Running terraform plan shows us whether changes are necessary to align the actual environment with the configuration and what changes will be made.

The execution plan generated by Terraform can be saved to a file by using the -out argument and giving a file name as a destination. The execution plan is aligned with the current version of the state, and if the state changes, Terraform no longer accepts the execution plan as valid. The saved execution plan can be used by terraform apply to execute the planned changes against the actual environment.

Why is the terraform plan command used?

We might use the terraform plan command for several reasons:

  • We may use it as a check before merging code in source control.
  • It could be used as a check to validate the current configuration.
  • We could use it as a preparation step to execute changes to the actual environment.

Arguments

The terraform plan command has several arguments. The most commonly used ones are listed below:

  • -input determines whether to prompt for input. It’s set to false in automation.

  • -out specifies a destination file where the execution plan will be saved.

  • -refresh determines whether a refresh of state should be run, and it defaults to true

  • -var sets a value for a variable in the configuration and can be used multiple times.

  • -var-file specifies a file that contains key/value pairs for variable values.

Submit values for variables

The var and var-file arguments are especially common because it’s one way to submit values for variables. There are other ways to submit values, though.

Specify a working directory

The terraform plan command also takes the global -chdir argument to specify a working directory containing a Terraform configuration. If no directory is specified, Terraform uses the configuration found in the current working directory.

Destroy all resources

There’s a special argument, destroy, that generates a plan to destroy all resources managed by the current configuration and state. We’ll explore why we’d use this in thelesson dealing with terraform destroy.

Key takeaways

The terraform plan command compares the current configuration against the state data and generates an execution plan of actions to align the state with the configuration. The execution plan can be saved to a file and used by terraform apply.

Get hands-on with 1400+ tech skills courses.