terraform/internal/command/refresh.go

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

214 lines
6.8 KiB
Go
Raw Permalink Normal View History

// Copyright IBM Corp. 2014, 2026
// SPDX-License-Identifier: BUSL-1.1
2014-06-27 14:09:01 -04:00
package command
import (
"fmt"
"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/tfdiags"
2014-06-27 14:09:01 -04:00
)
// RefreshCommand is a cli.Command implementation that refreshes the state
// file.
type RefreshCommand struct {
Meta
2014-06-27 14:09:01 -04:00
}
2021-02-22 11:38:39 -05:00
func (c *RefreshCommand) Run(rawArgs []string) int {
var diags tfdiags.Diagnostics
2021-02-22 11:38:39 -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-22 11:38:39 -05:00
// Parse and validate flags
args, diags := arguments.ParseRefresh(rawArgs)
// 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.NewRefresh(args.ViewType, c.View)
if diags.HasErrors() {
2021-02-22 11:38:39 -05:00
view.Diagnostics(diags)
view.HelpPrompt()
2014-06-27 14:09:01 -04:00
return 1
}
2021-02-22 11:38:39 -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-27 14:09:01 -04:00
return 1
}
2021-02-22 11:38:39 -05:00
// 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 with the backend-specific arguments
be, beDiags := c.PrepareBackend(args.State, args.ViewType)
2021-02-22 11:38:39 -05:00
diags = diags.Append(beDiags)
if diags.HasErrors() {
view.Diagnostics(diags)
return 1
}
2021-02-22 11:38:39 -05:00
// Build the operation request
opReq, opDiags := c.OperationRequest(be, view, args.ViewType, args.Operation)
2021-02-22 11:38:39 -05:00
diags = diags.Append(opDiags)
if diags.HasErrors() {
view.Diagnostics(diags)
return 1
}
// 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)
// 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.
2021-02-22 11:38:39 -05:00
view.Diagnostics(diags)
diags = nil
2021-02-22 11:38:39 -05:00
// Perform the operation
op, err := c.RunOperation(be, opReq)
2014-06-27 14:09:01 -04:00
if err != nil {
2021-02-22 11:38:39 -05:00
diags = diags.Append(err)
view.Diagnostics(diags)
return 1
}
2021-02-22 11:38:39 -05:00
if 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-22 11:38:39 -05:00
return op.Result.ExitStatus()
}
func (c *RefreshCommand) PrepareBackend(args *arguments.State, viewType arguments.ViewType) (backendrun.OperationsBackend, tfdiags.Diagnostics) {
2021-02-22 11:38:39 -05:00
// 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
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
be, diags := c.backend(".", viewType)
if diags.HasErrors() {
2021-02-22 11:38:39 -05:00
return nil, diags
}
2021-02-22 11:38:39 -05:00
return be, diags
}
func (c *RefreshCommand) OperationRequest(be backendrun.OperationsBackend, view views.Refresh, viewType arguments.ViewType, args *arguments.Operation,
) (*backendrun.Operation, tfdiags.Diagnostics) {
2021-02-22 11:38:39 -05:00
var diags tfdiags.Diagnostics
// Build the operation
opReq := c.Operation(be, viewType)
2021-02-22 11:38:39 -05:00
opReq.ConfigDir = "."
opReq.Hooks = view.Hooks()
opReq.Targets = args.Targets
opReq.Type = backendrun.OperationTypeRefresh
2021-02-22 11:38:39 -05:00
opReq.View = view.Operation()
// 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-22 11:38:39 -05:00
var err error
opReq.ConfigLoader, err = c.initConfigLoader()
if err != nil {
diags = diags.Append(fmt.Errorf("Failed to initialize config loader: %s", err))
return nil, diags
}
return opReq, diags
}
2014-06-27 14:09:01 -04:00
func (c *RefreshCommand) Help() string {
helpText := `
Usage: terraform [global options] refresh [options]
Update the state file of your infrastructure with metadata that matches
the physical resources they are tracking.
2014-06-27 14:09:01 -04:00
This will not modify your infrastructure, but it can modify your
state file to update metadata. This metadata might cause new changes
to occur when you generate a plan or call apply next.
2014-06-27 14:09:01 -04:00
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.
-input=true Ask for input for variables if not directly set.
-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.
-no-color If specified, output won't contain any color.
-parallelism=n Limit the number of concurrent operations. Defaults to 10.
-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 14:37:27 -04: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 21:22:07 -04:00
a file. If "terraform.tfvars" or any ".auto.tfvars"
files are present, they will be automatically loaded.
2014-07-18 14:37:27 -04:00
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-24 19:17:03 -04:00
-state, state-out, and -backup are legacy options supported for the local
backend only. For more information, see the local backend's documentation.
2014-06-27 14:09:01 -04:00
`
return strings.TrimSpace(helpText)
}
func (c *RefreshCommand) Synopsis() string {
return "Update the state to match remote systems"
2014-06-27 14:09:01 -04:00
}