2014-06-09 13:53:41 -05:00
package command
import (
"fmt"
"strings"
2017-01-18 22:50:45 -06:00
"github.com/hashicorp/terraform/backend"
2018-03-27 17:31:05 -05:00
"github.com/hashicorp/terraform/configs"
2018-10-09 16:53:24 -05:00
"github.com/hashicorp/terraform/plans"
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 18:41:48 -06:00
"github.com/hashicorp/terraform/tfdiags"
2014-06-09 13:53:41 -05:00
)
2014-06-20 13:47:02 -05:00
// PlanCommand is a Command implementation that compares a Terraform
2014-06-09 13:53:41 -05:00
// configuration to an actual infrastructure and shows the differences.
2014-06-20 13:47:02 -05:00
type PlanCommand struct {
2014-07-12 22:21:46 -05:00
Meta
2014-06-09 13:53:41 -05:00
}
2014-06-20 13:47:02 -05:00
func ( c * PlanCommand ) Run ( args [ ] string ) int {
2015-04-01 11:38:19 -05:00
var destroy , refresh , detailed bool
2014-10-11 20:47:52 -05:00
var outPath string
2014-06-19 15:51:05 -05:00
2020-04-01 14:01:08 -05:00
args = c . Meta . process ( args )
2018-11-21 08:35:27 -06:00
cmdFlags := c . Meta . extendedFlagSet ( "plan" )
2014-07-01 11:12:05 -05:00
cmdFlags . BoolVar ( & destroy , "destroy" , false , "destroy" )
2014-06-26 11:56:29 -05:00
cmdFlags . BoolVar ( & refresh , "refresh" , true , "refresh" )
2014-06-27 00:23:51 -05:00
cmdFlags . StringVar ( & outPath , "out" , "" , "path" )
2018-11-21 08:35:27 -06:00
cmdFlags . IntVar ( & c . Meta . parallelism , "parallelism" , DefaultParallelism , "parallelism" )
2017-01-18 22:50:45 -06:00
cmdFlags . StringVar ( & c . Meta . statePath , "state" , "" , "path" )
2015-04-01 11:38:19 -05:00
cmdFlags . BoolVar ( & detailed , "detailed-exitcode" , false , "detailed-exitcode" )
2017-02-06 09:07:32 -06:00
cmdFlags . BoolVar ( & c . Meta . stateLock , "lock" , true , "lock state" )
2017-04-01 15:19:59 -05:00
cmdFlags . DurationVar ( & c . Meta . stateLockTimeout , "lock-timeout" , 0 , "lock timeout" )
2014-06-09 13:53:41 -05:00
cmdFlags . Usage = func ( ) { c . Ui . Error ( c . Help ( ) ) }
if err := cmdFlags . Parse ( args ) ; err != nil {
return 1
}
2017-01-18 22:50:45 -06:00
configPath , err := ModulePath ( cmdFlags . Args ( ) )
2014-06-09 13:53:41 -05:00
if err != nil {
2014-07-12 22:37:30 -05:00
c . Ui . Error ( err . Error ( ) )
2014-06-09 13:53:41 -05:00
return 1
}
2015-11-10 12:31:15 -06:00
2017-06-15 13:26:12 -05:00
// Check for user-supplied plugin path
if c . pluginPath , err = c . loadPluginPath ( ) ; err != nil {
c . Ui . Error ( fmt . Sprintf ( "Error loading plugin path: %s" , err ) )
return 1
}
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 16:24:45 -05:00
// Check if the path is a plan, which is not permitted
planFileReader , err := c . PlanFile ( configPath )
2016-11-04 10:30:51 -05:00
if err != nil {
c . Ui . Error ( err . Error ( ) )
return 1
}
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 16:24:45 -05:00
if planFileReader != nil {
c . showDiagnostics ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid configuration directory" ,
fmt . Sprintf ( "Cannot pass a saved plan file to the 'terraform plan' command. To apply a saved plan, use: terraform apply %s" , configPath ) ,
) )
return 1
2015-11-10 12:31:15 -06:00
}
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 18:41:48 -06:00
var diags tfdiags . Diagnostics
2018-03-27 17:31:05 -05:00
var backendConfig * configs . Backend
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 16:24:45 -05:00
var configDiags tfdiags . Diagnostics
backendConfig , configDiags = c . loadBackendConfig ( configPath )
diags = diags . Append ( configDiags )
if configDiags . HasErrors ( ) {
c . showDiagnostics ( diags )
return 1
2014-06-26 11:56:29 -05:00
}
2017-01-18 22:50:45 -06:00
// Load the backend
2018-03-27 17:31:05 -05:00
b , backendDiags := c . Backend ( & BackendOpts {
Config : backendConfig ,
2017-01-18 22:50:45 -06:00
} )
2018-03-27 17:31:05 -05:00
diags = diags . Append ( backendDiags )
if backendDiags . HasErrors ( ) {
c . showDiagnostics ( diags )
2014-06-10 13:34:08 -05:00
return 1
}
2018-03-27 17:31:05 -05:00
// Emit any diagnostics we've accumulated before we delegate to the
// backend, since the backend will handle its own diagnostics internally.
c . showDiagnostics ( diags )
diags = nil
2017-01-18 22:50:45 -06:00
// Build the operation
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 16:24:45 -05:00
opReq := c . Operation ( b )
2018-03-27 17:31:05 -05:00
opReq . ConfigDir = configPath
2018-10-31 10:45:03 -05:00
opReq . Destroy = destroy
2017-01-18 22:50:45 -06:00
opReq . PlanOutPath = outPath
2018-10-05 08:25:17 -05:00
opReq . PlanRefresh = refresh
2017-01-18 22:50:45 -06:00
opReq . Type = backend . OperationTypePlan
2018-10-31 10:45:03 -05:00
2018-03-27 17:31:05 -05:00
opReq . ConfigLoader , err = c . initConfigLoader ( )
if err != nil {
c . showDiagnostics ( err )
return 1
}
2018-10-31 10:45:03 -05:00
2018-10-12 15:19:58 -05:00
{
var moreDiags tfdiags . Diagnostics
opReq . Variables , moreDiags = c . collectVariableValues ( )
diags = diags . Append ( moreDiags )
if moreDiags . HasErrors ( ) {
c . showDiagnostics ( diags )
return 1
}
}
2017-01-18 22:50:45 -06:00
2018-10-09 16:53:24 -05:00
// c.Backend above has a non-obvious side-effect of also populating
// c.backendState, which is the state-shaped formulation of the effective
// backend configuration after evaluation of the backend configuration.
// We will in turn adapt that to a plans.Backend to include in a plan file
// if opReq.PlanOutPath was set to a non-empty value above.
//
// FIXME: It's ugly to be doing this inline here, but it's also not really
// clear where would be better to do it. In future we should find a better
// home for this logic, and ideally also stop depending on the side-effect
// of c.Backend setting c.backendState.
{
// This is not actually a state in the usual sense, but rather a
// representation of part of the current working directory's
// "configuration state".
backendPseudoState := c . backendState
if backendPseudoState == nil {
// Should never happen if c.Backend is behaving properly.
diags = diags . Append ( fmt . Errorf ( "Backend initialization didn't produce resolved configuration (This is a bug in Terraform)" ) )
c . showDiagnostics ( diags )
return 1
}
var backendForPlan plans . Backend
backendForPlan . Type = backendPseudoState . Type
2020-06-16 11:23:15 -05:00
workspace , err := c . Workspace ( )
if err != nil {
c . Ui . Error ( fmt . Sprintf ( "Error selecting workspace: %s" , err ) )
return 1
}
backendForPlan . Workspace = workspace
2018-10-09 16:53:24 -05:00
// Configuration is a little more awkward to handle here because it's
// stored in state as raw JSON but we need it as a plans.DynamicValue
// to save it in the state. To do that conversion we need to know the
// configuration schema of the backend.
configSchema := b . ConfigSchema ( )
config , err := backendPseudoState . Config ( configSchema )
if err != nil {
// This means that the stored settings don't conform to the current
// schema, which could either be because we're reading something
// created by an older version that is no longer compatible, or
// because the user manually tampered with the stored config.
diags = diags . Append ( tfdiags . Sourceless (
tfdiags . Error ,
"Invalid backend initialization" ,
2018-10-09 18:50:57 -05:00
fmt . Sprintf ( "The backend configuration for this working directory is not valid: %s.\n\nIf you have recently upgraded Terraform, you may need to re-run \"terraform init\" to re-initialize this working directory." , err ) ,
2018-10-09 16:53:24 -05:00
) )
c . showDiagnostics ( diags )
return 1
}
configForPlan , err := plans . NewDynamicValue ( config , configSchema . ImpliedType ( ) )
if err != nil {
// This should never happen, since we've just decoded this value
// using the same schema.
diags = diags . Append ( fmt . Errorf ( "Failed to encode backend configuration to store in plan: %s" , err ) )
c . showDiagnostics ( diags )
return 1
}
backendForPlan . Config = configForPlan
}
2017-01-18 22:50:45 -06:00
// Perform the operation
2018-02-09 17:51:29 -06:00
op , err := c . RunOperation ( b , opReq )
2017-01-18 22:50:45 -06:00
if err != nil {
2018-03-27 17:31:05 -05:00
c . showDiagnostics ( err )
command: validate config as part of loading it
Previously we required callers to separately call .Validate on the root
module to determine if there were any value errors, but we did that
inconsistently and would thus see crashes in some cases where later code
would try to use invalid configuration as if it were valid.
Now we run .Validate automatically after config loading, returning the
resulting diagnostics. Since we return a diagnostics here, it's possible
to return both warnings and errors.
We return the loaded module even if it's invalid, so callers are free to
ignore returned errors and try to work with the config anyway, though they
will need to be defensive against invalid configuration themselves in
that case.
As a result of this, all of the commands that load configuration now need
to use diagnostic printing to signal errors. For the moment this just
allows us to return potentially-multiple config errors/warnings in full
fidelity, but also sets us up for later when more subsystems are able
to produce rich diagnostics so we can show them all together.
Finally, this commit also removes some stale, commented-out code for the
"legacy" (pre-0.8) graph implementation, which has not been available
for some time.
2017-12-06 18:41:48 -06:00
return 1
}
2016-11-03 16:46:26 -05:00
2018-03-27 17:31:05 -05:00
if op . Result != backend . OperationSuccess {
return op . Result . ExitStatus ( )
}
2017-01-18 22:50:45 -06:00
if detailed && ! op . PlanEmpty {
2015-04-01 11:38:19 -05:00
return 2
}
2017-01-18 22:50:45 -06:00
2018-03-27 17:31:05 -05:00
return op . Result . ExitStatus ( )
2014-06-09 13:53:41 -05:00
}
2014-06-20 13:47:02 -05:00
func ( c * PlanCommand ) Help ( ) string {
2014-06-09 13:53:41 -05:00
helpText := `
2019-03-01 14:30:51 -06:00
Usage : terraform plan [ options ] [ DIR ]
2014-07-11 22:51:26 -05:00
2020-10-23 18:55:32 -05:00
Generates a speculative execution plan , showing what actions Terraform
would take to apply the current configuration . This command will not
actually perform the planned actions .
2014-06-09 13:53:41 -05:00
2020-10-23 18:55:32 -05:00
You can optionally save the plan to a file , which you can then pass to
the "apply" command to perform exactly the actions described in the plan .
2014-06-09 13:53:41 -05:00
Options :
2019-12-10 13:06:06 -06:00
- compact - warnings If Terraform produces any warnings that are not
accompanied by errors , show them in a more compact form
that includes only the summary messages .
2014-07-01 11:12:35 -05:00
- destroy If set , a plan will be generated to destroy all resources
managed by the given configuration and state .
2015-04-01 11:38:19 -05:00
- detailed - exitcode Return detailed exit codes when the command exits . This
will change the meaning of exit codes to :
0 - Succeeded , diff is empty ( no changes )
1 - Errored
2 - Succeeded , there is a diff
2014-09-29 13:11:35 -05:00
- input = true Ask for input for variables if not directly set .
2017-02-06 09:07:32 -06:00
- lock = true Lock the state file when locking is supported .
2017-02-03 13:15:08 -06:00
2017-04-01 15:19:59 -05:00
- lock - timeout = 0 s Duration to retry a state lock .
2014-07-12 22:21:46 -05:00
- no - color If specified , output won ' t contain any color .
2014-06-27 00:23:51 -05:00
- out = path Write a plan file to the given path . This can be used as
input to the "apply" command .
2015-10-05 17:18:03 -05:00
- parallelism = n Limit the number of concurrent operations . Defaults to 10.
2015-10-05 15:06:08 -05:00
2014-06-26 11:56:29 -05:00
- refresh = true Update state prior to checking for differences .
2014-06-09 13:53:41 -05:00
- state = statefile Path to a Terraform state file to use to look
2014-07-11 22:51:26 -05:00
up Terraform - managed resources . By default it will
use the state "terraform.tfstate" if it exists .
2014-06-09 13:53:41 -05:00
2015-03-24 11:18:15 -05:00
- target = resource Resource to target . Operation will be limited to this
resource and its dependencies . This flag can be used
multiple times .
2014-07-18 13:37:27 -05:00
- var ' foo = bar ' Set a variable in the Terraform configuration . This
flag can be set multiple times .
- var - file = foo Set variables in the Terraform configuration from
2017-06-21 20:22:07 -05:00
a file . If "terraform.tfvars" or any ".auto.tfvars"
files are present , they will be automatically loaded .
2014-06-09 13:53:41 -05:00
`
return strings . TrimSpace ( helpText )
}
2014-06-20 13:47:02 -05:00
func ( c * PlanCommand ) Synopsis ( ) string {
2020-10-23 18:55:32 -05:00
return "Show changes required by the current configuration"
2014-06-09 13:53:41 -05:00
}