terraform/internal/command/apply.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

408 lines
13 KiB
Go
Raw Permalink Normal View History

// Copyright IBM Corp. 2014, 2026
// SPDX-License-Identifier: BUSL-1.1
2014-05-24 15:27:58 -04:00
package command
import (
2014-06-18 19:42:13 -04:00
"fmt"
2014-05-24 15:27:58 -04:00
"strings"
"github.com/hashicorp/terraform/internal/backend/backendrun"
"github.com/hashicorp/terraform/internal/command/arguments"
"github.com/hashicorp/terraform/internal/command/views"
"github.com/hashicorp/terraform/internal/plans/planfile"
"github.com/hashicorp/terraform/internal/tfdiags"
2014-05-24 15:27:58 -04:00
)
// ApplyCommand is a Command implementation that applies a Terraform
// configuration and actually builds or changes infrastructure.
type ApplyCommand struct {
Meta
2014-10-01 00:49:24 -04:00
// If true, then this apply command will become the "destroy"
// command. It is just like apply but only processes a destroy.
Destroy bool
2014-05-24 15:27:58 -04:00
}
2021-02-18 17:23:34 -05:00
func (c *ApplyCommand) Run(rawArgs []string) int {
var diags tfdiags.Diagnostics
2021-02-18 17:23:34 -05:00
// Parse and apply global view arguments
common, rawArgs := arguments.ParseView(rawArgs)
c.View.Configure(common)
2021-10-28 16:27:39 -04:00
// Propagate -no-color for legacy use of Ui. The remote backend and
// cloud package use this; it should be removed when/if they are
// migrated to views.
c.Meta.color = !common.NoColor
c.Meta.Color = c.Meta.color
2021-02-18 17:23:34 -05:00
// Parse and validate flags
var args *arguments.Apply
switch {
case c.Destroy:
args, diags = arguments.ParseApplyDestroy(rawArgs)
default:
args, diags = arguments.ParseApply(rawArgs)
}
2021-02-18 17:23:34 -05:00
// Instantiate the view, even if there are flag errors, so that we render
// diagnostics according to the desired view
2021-08-31 17:33:26 -04:00
view := views.NewApply(args.ViewType, c.Destroy, c.View)
2021-02-18 17:23:34 -05:00
if diags.HasErrors() {
view.Diagnostics(diags)
view.HelpPrompt()
return 1
2014-10-01 00:49:24 -04:00
}
2021-02-18 17:23:34 -05: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)
2014-06-18 19:42:13 -04:00
return 1
}
2021-02-18 17:23:34 -05:00
// Attempt to load the plan file, if specified
planFile, loadPlanFileDiags := c.LoadPlanFile(args.PlanPath)
diags = diags.Append(loadPlanFileDiags)
if diags.HasErrors() {
2021-02-18 17:23:34 -05:00
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
// Prepare the backend, passing the plan file if present, and the
// backend-specific arguments
be, beDiags := c.PrepareBackend(planFile, args.State, args.ViewType)
2021-02-18 17:23:34 -05:00
diags = diags.Append(beDiags)
if diags.HasErrors() {
view.Diagnostics(diags)
return 1
}
2021-02-18 17:23:34 -05:00
// Build the operation request
opReq, opDiags := c.OperationRequest(be, view, args.ViewType, planFile, args.Operation, args.AutoApprove)
2021-02-18 17:23:34 -05:00
diags = diags.Append(opDiags)
if diags.HasErrors() {
view.Diagnostics(diags)
return 1
}
2021-02-18 17:23:34 -05:00
// Collect variable value and add them to the operation request
var varDiags tfdiags.Diagnostics
opReq.Variables, varDiags = args.Vars.CollectValues(func(filename string, src []byte) {
opReq.ConfigLoader.Parser().ForceFileSource(filename, src)
})
diags = diags.Append(varDiags)
2021-02-18 17:23:34 -05: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)
if diags.HasErrors() {
return 1
}
diags = nil
// Run the operation
op, err := c.RunOperation(be, opReq)
2017-01-18 23:50:45 -05:00
if err != nil {
2021-02-18 17:23:34 -05:00
diags = diags.Append(err)
view.Diagnostics(diags)
2014-06-18 19:42:13 -04:00
return 1
}
if op.Result != backendrun.OperationSuccess {
2021-02-18 17:23:34 -05:00
return op.Result.ExitStatus()
}
// Render the resource count and outputs, unless those counts are being
// rendered already in a remote Terraform process.
if rb, isRemoteBackend := be.(BackendWithRemoteTerraformVersion); !isRemoteBackend || rb.IsLocalOperations() {
view.ResourceCount(args.State.StateOutPath)
if !c.Destroy && op.State != nil {
states: Only track root module output values For a very long time we've had an annoying discrepancy between the in-memory state model and our state snapshot format where the in-memory format stores output values for all modules whereas the snapshot format only tracks the root module output values because those are all we actually need to preserve between runs. That design wart was a result of us using the state both as an internal and an external artifact, due to having nowhere else to store the transient values of non-root module output values while Terraform Core does its work. We now have namedvals.State to internally track all of the throwaway results from named values that don't need to persist between runs, so now we'll use that for our internal work instead and reserve the states.State model only for the data that we will preserve between runs in state snapshots. The namedvals internal model isn't really designed to support enumerating all of the output values for a particular module call, but our expression evaluator currently depends on being able to do that and so we have a temporary inefficient implementation of that which just scans the entire table of values as a stopgap just to avoid this commit growing even larger than it already is. In a future commit we'll rework the evaluator to support the PartialEval mode and at the same time move the responsiblity for enumerating all of the output values into the evaluator itself, since it should be able to determine what it's expecting by analyzing the configuration rather than just by trusting that earlier evaluation has completed correctly. Because our legacy state string serialization previously included output values for all modules, some of our context tests were accidentally depending on the implementation detail of how those got stored internally. Those tests are updated here to test only the data that is a real part of Terraform Core's result, by ensuring that the relevant data appears somewhere either in a root output value or in a resource attribute.
2023-03-09 22:26:49 -05:00
view.Outputs(op.State.RootOutputValues)
}
2021-02-18 17:23:34 -05:00
}
view.Diagnostics(diags)
if diags.HasErrors() {
return 1
}
2021-02-18 17:23:34 -05:00
return 0
}
func (c *ApplyCommand) LoadPlanFile(path string) (*planfile.WrappedPlanFile, tfdiags.Diagnostics) {
var planFile *planfile.WrappedPlanFile
2021-02-18 17:23:34 -05:00
var diags tfdiags.Diagnostics
// Try to load plan if path is specified
if path != "" {
var err error
planFile, err = c.PlanFile(path)
if err != nil {
2021-02-18 17:23:34 -05:00
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
fmt.Sprintf("Failed to load %q as a plan file", path),
fmt.Sprintf("Error: %s", err),
))
return nil, diags
}
// If the path doesn't look like a plan, both planFile and err will be
// nil. In that case, the user is probably trying to use the positional
// argument to specify a configuration path. Point them at -chdir.
if planFile == nil {
2021-02-18 17:23:34 -05:00
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
fmt.Sprintf("Failed to load %q as a plan file", path),
"The specified path is a directory, not a plan file. You can use the global -chdir flag to use this directory as the configuration root.",
))
return nil, diags
}
// If we successfully loaded a plan but this is a destroy operation,
// explain that this is not supported.
if c.Destroy {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
2021-02-18 17:23:34 -05:00
"Destroy can't be called with a plan file",
fmt.Sprintf("If this plan was created using plan -destroy, apply it using:\n terraform apply %q", path),
))
2021-02-18 17:23:34 -05:00
return nil, diags
}
}
2021-02-18 17:23:34 -05:00
return planFile, diags
}
func (c *ApplyCommand) PrepareBackend(planFile *planfile.WrappedPlanFile, args *arguments.State, viewType arguments.ViewType) (backendrun.OperationsBackend, tfdiags.Diagnostics) {
2021-02-18 17:23:34 -05:00
var diags 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)
// Load the backend
var be backendrun.OperationsBackend
var beDiags tfdiags.Diagnostics
if lp, ok := planFile.Local(); ok {
plan, err := lp.ReadPlan()
if err != nil {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Failed to read plan from plan file",
fmt.Sprintf("Cannot read the plan from the given plan file: %s.", err),
))
2021-02-18 17:23:34 -05:00
return nil, diags
}
if plan.Backend == nil && plan.StateStore == nil {
// Should never happen; always indicates a bug in the creation of the plan file
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Failed to read plan from plan file",
"The given plan file has neither a valid backend nor state store configuration. This is a bug in the Terraform command that generated this plan file.",
))
2021-02-18 17:23:34 -05:00
return nil, diags
}
be, beDiags = c.BackendForLocalPlan(plan)
} else {
PSS: Update how commands access backends, so both `backend` and `state_store` configuration can be used (#37569) * Add a generic method for loading an operations backend in non-init commands * Refactor commands to use new prepareBackend method: group 1 * Refactor commands to use new prepareBackend method: group 2, where config parsing needs to be explicitly added * Refactor commands to use new prepareBackend method: group 3, where we can use already parsed config * Additional, more nested, places where logic for accessing backends needs to be refactored * Remove duplicated comment * Add test coverage of `(m *Meta) prepareBackend()` * Add TODO related to using plans for backend/state_store config in apply commands * Add `testStateStoreMockWithChunkNegotiation` test helper * Add assertions to tests about the backend (remote-state, local, etc) in use within operations backend * Stop prepareBackend taking locks as argument * Code comment in prepareBackend * Replace c.Meta.prepareBackend with c.prepareBackend * Change `c.Meta.loadSingleModule` to `c.loadSingleModule` * Rename (Meta).prepareBackend to (Meta).backend, update godoc comment to make relationship to (Meta).Backend more obvious. * Revert change from config.Module to config.Root.Module * Update `(m *Meta) backend` method to parse config itself, and also to adhere to calling code's viewtype instructions * Update all tests and calling code following previous commit * Change how an operations backend is obtained by autocomplete code * Update autocomplete to return nil if no workspace names are returned from the backend * Add test coverage for autocompleting workspace names when using a pluggable state store * Fix output command: pass view type data to new `backend` method * Fix in plan command: pass correct view type to `backend` method * Fix `providers schema` command to use correct viewtype when preparing a backend
2025-11-03 12:57:20 -05:00
// Load the backend
//
// Note: Both new plans and saved cloud plans load their backend from config,
// hence the config parsing in the method below.
be, beDiags = c.backend(".", viewType)
}
2021-02-18 17:23:34 -05:00
diags = diags.Append(beDiags)
if beDiags.HasErrors() {
2021-02-18 17:23:34 -05:00
return nil, diags
2017-01-18 23:50:45 -05:00
}
2021-02-18 17:23:34 -05:00
return be, diags
}
func (c *ApplyCommand) OperationRequest(
be backendrun.OperationsBackend,
view views.Apply,
viewType arguments.ViewType,
planFile *planfile.WrappedPlanFile,
args *arguments.Operation,
autoApprove bool,
) (*backendrun.Operation, tfdiags.Diagnostics) {
2021-02-18 17:23:34 -05:00
var diags tfdiags.Diagnostics
2017-01-18 23:50:45 -05:00
// Applying changes with dev overrides in effect could make it impossible
// to switch back to a release version if the schema isn't compatible,
// so we'll warn about it.
b, isRemoteBackend := be.(BackendWithRemoteTerraformVersion)
if isRemoteBackend && !b.IsLocalOperations() {
diags = diags.Append(c.providerDevOverrideRuntimeWarningsRemoteExecution())
} else {
diags = diags.Append(c.providerDevOverrideRuntimeWarnings())
}
2017-01-18 23:50:45 -05:00
// Build the operation
opReq := c.Operation(be, viewType)
opReq.AutoApprove = autoApprove
2021-02-18 17:23:34 -05:00
opReq.ConfigDir = "."
opReq.PlanMode = args.PlanMode
2021-02-18 17:23:34 -05:00
opReq.Hooks = view.Hooks()
opReq.PlanFile = planFile
2021-02-18 17:23:34 -05:00
opReq.PlanRefresh = args.Refresh
opReq.Targets = args.Targets
opReq.ForceReplace = args.ForceReplace
opReq.Type = backendrun.OperationTypeApply
2021-02-18 17:23:34 -05:00
opReq.View = view.Operation()
opReq.StatePersistInterval = c.Meta.StatePersistInterval()
2025-09-16 09:58:03 -04:00
opReq.ActionTargets = args.ActionTargets
// EXPERIMENTAL: maybe enable deferred actions
if c.AllowExperimentalFeatures {
opReq.DeferralAllowed = args.DeferralAllowed
} else if args.DeferralAllowed {
// Belated flag parse error, since we don't know about experiments
// support at actual parse time.
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Failed to parse command-line flags",
"The -allow-deferral flag is only valid in experimental builds of Terraform.",
))
return nil, diags
}
2021-02-18 17:23:34 -05:00
var err error
opReq.ConfigLoader, err = c.initConfigLoader()
if err != nil {
2021-02-18 17:23:34 -05:00
diags = diags.Append(fmt.Errorf("Failed to initialize config loader: %s", err))
return nil, diags
}
2021-02-18 17:23:34 -05:00
return opReq, diags
}
2014-05-24 15:27:58 -04:00
func (c *ApplyCommand) Help() string {
2014-10-01 01:01:11 -04:00
if c.Destroy {
return c.helpDestroy()
}
return c.helpApply()
}
func (c *ApplyCommand) Synopsis() string {
if c.Destroy {
return "Destroy previously-created infrastructure"
2014-10-01 01:01:11 -04:00
}
return "Create or update infrastructure"
2014-10-01 01:01:11 -04:00
}
func (c *ApplyCommand) helpApply() string {
2014-05-24 15:27:58 -04:00
helpText := `
Usage: terraform [global options] apply [options] [PLAN]
2014-05-24 15:27:58 -04:00
Creates or updates infrastructure according to Terraform configuration
files in the current directory.
2014-09-29 18:57:35 -04:00
By default, Terraform will generate a new plan and present it for your
approval before taking any action. You can optionally provide a plan
file created by a previous call to "terraform plan", in which case
Terraform will take the actions described in that plan without any
confirmation prompt.
2014-05-24 15:27:58 -04:00
Options:
-auto-approve Skip interactive approval of plan before applying.
2014-07-27 18:09:04 -04:00
-backup=path Path to backup the existing state file before
modifying. Defaults to the "-state-out" path with
".backup" extension. Set to "-" to disable backup.
2014-07-27 18:09:04 -04: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.
-destroy Destroy Terraform-managed infrastructure.
The command "terraform destroy" is a convenience alias
for this option.
-lock=false Don't hold a state lock during the operation. This is
dangerous if others might concurrently run commands
against the same workspace.
-lock-timeout=0s Duration to retry a state lock.
-input=true Ask for input for variables if not directly set.
-no-color If specified, output won't contain any color.
-parallelism=n Limit the number of parallel resource operations.
Defaults to 10.
2015-05-06 11:58:42 -04:00
-replace=resource Terraform will plan to replace this resource instance
instead of doing an update or no-op action.
-state=path Path to read and save state (unless state-out
is specified). Defaults to "terraform.tfstate".
Legacy option for the local backend only. See the local
backend's documentation for more information.
2014-06-19 00:36:44 -04:00
-state-out=path Path to write state to that is different than
"-state". This can be used to preserve the old
state.
Legacy option for the local backend only. See the local
backend's documentation for more information.
-var 'foo=bar' Set a value for one of the input variables in the root
module of the configuration. Use this option more than
once to set more than one variable.
-var-file=filename Load variable values from the given file, in addition
to the default files terraform.tfvars and *.auto.tfvars.
Use this option more than once to include more than one
variables file.
2014-05-24 15:27:58 -04:00
If you don't provide a saved plan file then this command will also accept
all of the plan-customization options accepted by the terraform plan command.
For more information on those options, run:
terraform plan -help
2014-05-24 15:27:58 -04:00
`
return strings.TrimSpace(helpText)
}
2014-10-01 01:01:11 -04:00
func (c *ApplyCommand) helpDestroy() string {
helpText := `
Usage: terraform [global options] destroy [options]
2014-10-01 01:01:11 -04:00
Destroy Terraform-managed infrastructure.
This command is a convenience alias for:
terraform apply -destroy
2014-10-01 01:01:11 -04:00
This command also accepts many of the plan-customization options accepted by
the terraform plan command. For more information on those options, run:
terraform plan -help
2014-10-01 01:01:11 -04:00
`
return strings.TrimSpace(helpText)
}