terraform/command/plan.go

244 lines
7.6 KiB
Go
Raw Normal View History

package command
import (
"fmt"
"strings"
2017-01-19 05:50:45 +01:00
"github.com/hashicorp/terraform/backend"
2021-02-17 19:01:30 +01:00
"github.com/hashicorp/terraform/command/arguments"
"github.com/hashicorp/terraform/command/views"
"github.com/hashicorp/terraform/tfdiags"
)
2014-06-20 20:47:02 +02:00
// PlanCommand is a Command implementation that compares a Terraform
// configuration to an actual infrastructure and shows the differences.
2014-06-20 20:47:02 +02:00
type PlanCommand struct {
Meta
}
2021-02-22 17:55:00 +01:00
func (c *PlanCommand) Run(rawArgs []string) int {
// Parse and apply global view arguments
common, rawArgs := arguments.ParseView(rawArgs)
c.View.Configure(common)
// Parse and validate flags
args, diags := arguments.ParsePlan(rawArgs)
// Instantiate the view, even if there are flag errors, so that we render
// diagnostics according to the desired view
view := views.NewPlan(args.ViewType, c.RunningInAutomation, c.View)
if diags.HasErrors() {
view.Diagnostics(diags)
view.HelpPrompt()
return 1
}
2021-02-22 17:55:00 +01:00
// Check for user-supplied plugin path
var err error
if c.pluginPath, err = c.loadPluginPath(); err != nil {
diags = diags.Append(err)
view.Diagnostics(diags)
return 1
}
// FIXME: the -input flag value is needed to initialize the backend and the
// operation, but there is no clear path to pass this value down, so we
// continue to mutate the Meta object state for now.
c.Meta.input = args.InputEnabled
// FIXME: the -parallelism flag is used to control the concurrency of
// Terraform operations. At the moment, this value is used both to
// initialize the backend via the ContextOpts field inside CLIOpts, and to
// set a largely unused field on the Operation request. Again, there is no
// clear path to pass this value down, so we continue to mutate the Meta
// object state for now.
c.Meta.parallelism = args.Operation.Parallelism
diags = diags.Append(c.providerDevOverrideRuntimeWarnings())
// Prepare the backend with the backend-specific arguments
be, beDiags := c.PrepareBackend(args.State)
diags = diags.Append(beDiags)
if diags.HasErrors() {
2021-02-22 17:55:00 +01:00
view.Diagnostics(diags)
return 1
}
2021-02-22 17:55:00 +01:00
// Build the operation request
opReq, opDiags := c.OperationRequest(be, view, args.Operation, args.Destroy, args.OutPath)
diags = diags.Append(opDiags)
if diags.HasErrors() {
view.Diagnostics(diags)
return 1
}
2021-02-22 17:55:00 +01:00
// Collect variable value and add them to the operation request
diags = diags.Append(c.GatherVariables(opReq, args.Vars))
if diags.HasErrors() {
view.Diagnostics(diags)
return 1
}
2021-02-22 17:55:00 +01:00
// Before we delegate to the backend, we'll print any warning diagnostics
// we've accumulated here, since the backend will start fresh with its own
// diagnostics.
view.Diagnostics(diags)
diags = nil
// Perform the operation
op, err := c.RunOperation(be, opReq)
if err != nil {
diags = diags.Append(err)
view.Diagnostics(diags)
return 1
2014-06-26 18:56:29 +02:00
}
2021-02-22 17:55:00 +01:00
if op.Result != backend.OperationSuccess {
return op.Result.ExitStatus()
}
if args.DetailedExitCode && !op.PlanEmpty {
return 2
}
return op.Result.ExitStatus()
}
func (c *PlanCommand) PrepareBackend(args *arguments.State) (backend.Enhanced, tfdiags.Diagnostics) {
// FIXME: we need to apply the state arguments to the meta object here
// because they are later used when initializing the backend. Carving a
// path to pass these arguments to the functions that need them is
// difficult but would make their use easier to understand.
c.Meta.applyStateArguments(args)
backendConfig, diags := c.loadBackendConfig(".")
if diags.HasErrors() {
return nil, diags
}
2017-01-19 05:50:45 +01:00
// Load the backend
2021-02-22 17:55:00 +01:00
be, beDiags := c.Backend(&BackendOpts{
Config: backendConfig,
2017-01-19 05:50:45 +01:00
})
2021-02-22 17:55:00 +01:00
diags = diags.Append(beDiags)
if beDiags.HasErrors() {
return nil, diags
2014-06-10 20:34:08 +02:00
}
2021-02-22 17:55:00 +01:00
return be, diags
}
func (c *PlanCommand) OperationRequest(
be backend.Enhanced,
view views.Plan,
args *arguments.Operation,
destroy bool,
planOutPath string,
) (*backend.Operation, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
2017-01-19 05:50:45 +01:00
// Build the operation
2021-02-22 17:55:00 +01:00
opReq := c.Operation(be)
opReq.ConfigDir = "."
opReq.Destroy = destroy
2021-02-22 17:55:00 +01:00
opReq.Hooks = view.Hooks()
opReq.PlanRefresh = args.Refresh
opReq.PlanOutPath = planOutPath
opReq.Targets = args.Targets
2017-01-19 05:50:45 +01:00
opReq.Type = backend.OperationTypePlan
2021-02-22 17:55:00 +01:00
opReq.View = view.Operation()
2021-02-22 17:55:00 +01:00
var err error
opReq.ConfigLoader, err = c.initConfigLoader()
if err != nil {
2021-02-22 17:55:00 +01:00
diags = diags.Append(fmt.Errorf("Failed to initialize config loader: %s", err))
return nil, diags
}
2017-01-19 05:50:45 +01:00
2021-02-22 17:55:00 +01:00
return opReq, diags
}
2021-02-22 17:55:00 +01:00
func (c *PlanCommand) GatherVariables(opReq *backend.Operation, args *arguments.Vars) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
// FIXME the arguments package currently trivially gathers variable related
// arguments in a heterogenous slice, in order to minimize the number of
// code paths gathering variables during the transition to this structure.
// Once all commands that gather variables have been converted to this
// structure, we could move the variable gathering code to the arguments
// package directly, removing this shim layer.
varArgs := args.All()
items := make([]rawFlag, len(varArgs))
for i := range varArgs {
items[i].Name = varArgs[i].Name
items[i].Value = varArgs[i].Value
}
2021-02-22 17:55:00 +01:00
c.Meta.variableArgs = rawFlags{items: &items}
opReq.Variables, diags = c.collectVariableValues()
2017-01-19 05:50:45 +01:00
2021-02-22 17:55:00 +01:00
return diags
}
2014-06-20 20:47:02 +02:00
func (c *PlanCommand) Help() string {
helpText := `
Usage: terraform [global options] plan [options]
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.
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.
Options:
-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 18:12:35 +02:00
-destroy If set, a plan will be generated to destroy all resources
managed by the given configuration and state.
-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
-input=true Ask for input for variables if not directly set.
2017-02-06 16:07:32 +01:00
-lock=true Lock the state file when locking is supported.
-lock-timeout=0s Duration to retry a state lock.
-no-color If specified, output won't contain any color.
2014-06-27 07:23:51 +02:00
-out=path Write a plan file to the given path. This can be used as
input to the "apply" command.
-parallelism=n Limit the number of concurrent operations. Defaults to 10.
2014-06-26 18:56:29 +02:00
-refresh=true Update state prior to checking for differences.
command: Reorganize docs of the local backend's legacy CLI options We have these funny extra options that date back to before Terraform even had remote state, which we've preserved along the way by most recently incorporating them as special-case overrides for the local backend. The documentation we had for these has grown less accurate over time as the details have shifted, and was in many cases missing the requisite caveats that they are only for the local backend and that backend configuration is the modern, preferred way to deal with the use-cases they were intended for. We always have a bit of a tension with this sort of legacy option because we want to keep them documented just enough to be useful to someone who finds an existing script/etc using them and wants to know what they do, but not to take up so much space that they might distract users from finding the modern alternative they should consider instead. As a compromise in that vein here I've created a new section about these options under the local backend documentation, which then gives us the space to go into some detail about the various behaviors and interactions and also to discuss their history and our recommended alternatives. I then simplified all of the other mentions of these in command documentation to just link to or refer to the local backend documentation. My hope then is that folks who need to know what these do can still find the docs, but that information can be kept out of the direct path of new users so they can focus on learning about remote backends instead. This is certainly not the most ideal thing ever, but it seemed like the best compromise between the competing priorities I described above.
2021-03-25 00:17:03 +01:00
-state=statefile A legacy option used for the local backend only. See the
local backend's documentation for more information.
-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 20:37:27 +02: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-22 03:22:07 +02:00
a file. If "terraform.tfvars" or any ".auto.tfvars"
files are present, they will be automatically loaded.
`
return strings.TrimSpace(helpText)
}
2014-06-20 20:47:02 +02:00
func (c *PlanCommand) Synopsis() string {
return "Show changes required by the current configuration"
}