Files
opentf/internal/command/state_replace_provider.go
Martin Atkins 67a5cd0911 statemgr+remote: context.Context parameters
This extends statemgr.Persistent, statemgr.Locker and remote.Client to
all expect context.Context parameters, and then updates all of the existing
implementations of those interfaces to support them.

All of the calls to statemgr.Persistent and statemgr.Locker methods outside
of tests are consistently context.TODO() for now, because the caller
landscape of these interfaces has some complications:

1. statemgr.Locker is also used by the clistate package for its state
   implementation that was derived from statemgr.Filesystem's predecessor,
   even though what clistate manages is not actually "state" in the sense
   of package statemgr. The callers of that are not yet ready to provide
   real contexts.

   In a future commit we'll either need to plumb context through to all of
   the clistate callers, or continue the effort to separate statemgr from
   clistate by introducing a clistate-specific "locker" API for it
   to use instead.

2. We call statemgr.Persistent and statemgr.Locker methods in situations
   where the active context might have already been cancelled, and so we'll
   need to make sure to ignore cancellation when calling those.

   This is mainly limited to PersistState and Unlock, since both need to
   be able to complete after a cancellation, but there are various
   codepaths that perform a Lock, Refresh, Persist, Unlock sequence and so
   it isn't yet clear where is the best place to enforce the invariant that
   Persist and Unlock must not be called with a cancelable context. We'll
   deal with that more in subsequent commits.

Within the various state manager and remote client implementations the
contexts _are_ wired together as best as possible with how these subsystems
are already laid out, and so once we deal with the problems above and make
callers provide suitable contexts they should be able to reach all of the
leaf API clients that might want to generate OpenTelemetry traces.

Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
2025-07-10 08:11:39 -07:00

249 lines
7.2 KiB
Go

// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2023 HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package command
import (
"context"
"fmt"
"strings"
"github.com/mitchellh/cli"
"github.com/opentofu/opentofu/internal/addrs"
"github.com/opentofu/opentofu/internal/command/arguments"
"github.com/opentofu/opentofu/internal/command/clistate"
"github.com/opentofu/opentofu/internal/command/views"
"github.com/opentofu/opentofu/internal/states"
"github.com/opentofu/opentofu/internal/tfdiags"
"github.com/opentofu/opentofu/internal/tofu"
)
// StateReplaceProviderCommand is a Command implementation that allows users
// to change the provider associated with existing resources. This is only
// likely to be useful if a provider is forked or changes its fully-qualified
// name.
type StateReplaceProviderCommand struct {
StateMeta
}
func (c *StateReplaceProviderCommand) Run(args []string) int {
ctx := c.CommandContext()
args = c.Meta.process(args)
var autoApprove bool
cmdFlags := c.Meta.ignoreRemoteVersionFlagSet("state replace-provider")
cmdFlags.BoolVar(&autoApprove, "auto-approve", false, "skip interactive approval of replacements")
cmdFlags.StringVar(&c.backupPath, "backup", "-", "backup")
cmdFlags.BoolVar(&c.Meta.stateLock, "lock", true, "lock states")
cmdFlags.DurationVar(&c.Meta.stateLockTimeout, "lock-timeout", 0, "lock timeout")
cmdFlags.StringVar(&c.statePath, "state", "", "path")
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
return cli.RunResultHelp
}
args = cmdFlags.Args()
if len(args) != 2 {
c.Ui.Error("Exactly two arguments expected.\n")
return cli.RunResultHelp
}
if diags := c.Meta.checkRequiredVersion(ctx); diags != nil {
c.showDiagnostics(diags)
return 1
}
var diags tfdiags.Diagnostics
// Parse from/to arguments into providers
from, fromDiags := addrs.ParseProviderSourceString(args[0])
if fromDiags.HasErrors() {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
fmt.Sprintf(`Invalid "from" provider %q`, args[0]),
fromDiags.Err().Error(),
))
}
to, toDiags := addrs.ParseProviderSourceString(args[1])
if toDiags.HasErrors() {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
fmt.Sprintf(`Invalid "to" provider %q`, args[1]),
toDiags.Err().Error(),
))
}
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// Load the encryption configuration
enc, encDiags := c.Encryption(ctx)
diags = diags.Append(encDiags)
if encDiags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// Initialize the state manager as configured
stateMgr, err := c.State(ctx, enc)
if err != nil {
c.Ui.Error(fmt.Sprintf(errStateLoadingState, err))
return 1
}
// Acquire lock if requested
if c.stateLock {
stateLocker := clistate.NewLocker(c.stateLockTimeout, views.NewStateLocker(arguments.ViewHuman, c.View))
if diags := stateLocker.Lock(stateMgr, "state-replace-provider"); diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
defer func() {
if diags := stateLocker.Unlock(); diags.HasErrors() {
c.showDiagnostics(diags)
}
}()
}
// Refresh and load state
if err := stateMgr.RefreshState(context.TODO()); err != nil {
c.Ui.Error(fmt.Sprintf("Failed to refresh source state: %s", err))
return 1
}
state := stateMgr.State()
if state == nil {
c.Ui.Error(errStateNotFound)
return 1
}
// Fetch all resources from the state
resources, diags := c.lookupAllResources(state)
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
var willReplace []*states.Resource
// Update all matching resources with new provider
for _, resource := range resources {
if resource.ProviderConfig.Provider.Equals(from) {
willReplace = append(willReplace, resource)
}
}
c.showDiagnostics(diags)
if len(willReplace) == 0 {
c.Ui.Output("No matching resources found.")
return 0
}
// Explain the changes
colorize := c.Colorize()
c.Ui.Output("OpenTofu will perform the following actions:\n")
c.Ui.Output(colorize.Color(" [yellow]~[reset] Updating provider:"))
c.Ui.Output(colorize.Color(fmt.Sprintf(" [red]-[reset] %s", from)))
c.Ui.Output(colorize.Color(fmt.Sprintf(" [green]+[reset] %s\n", to)))
c.Ui.Output(colorize.Color(fmt.Sprintf("[bold]Changing[reset] %d resources:\n", len(willReplace))))
for _, resource := range willReplace {
c.Ui.Output(colorize.Color(fmt.Sprintf(" %s", resource.Addr)))
}
// Confirm
if !autoApprove {
c.Ui.Output(colorize.Color(
"\n[bold]Do you want to make these changes?[reset]\n" +
"Only 'yes' will be accepted to continue.\n",
))
v, err := c.Ui.Ask("Enter a value:")
if err != nil {
c.Ui.Error(fmt.Sprintf("Error asking for approval: %s", err))
return 1
}
if v != "yes" {
c.Ui.Output("Cancelled replacing providers.")
return 0
}
}
// Update the provider for each resource
for _, resource := range willReplace {
resource.ProviderConfig.Provider = to
}
b, backendDiags := c.Backend(ctx, nil, enc.State())
diags = diags.Append(backendDiags)
if backendDiags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// Get schemas, if possible, before writing state
var schemas *tofu.Schemas
if isCloudMode(b) {
var schemaDiags tfdiags.Diagnostics
schemas, schemaDiags = c.MaybeGetSchemas(ctx, state, nil)
diags = diags.Append(schemaDiags)
}
// Write the updated state
if err := stateMgr.WriteState(state); err != nil {
c.Ui.Error(fmt.Sprintf(errStateRmPersist, err))
return 1
}
if err := stateMgr.PersistState(context.TODO(), schemas); err != nil {
c.Ui.Error(fmt.Sprintf(errStateRmPersist, err))
return 1
}
c.showDiagnostics(diags)
c.Ui.Output(fmt.Sprintf("\nSuccessfully replaced provider for %d resources.", len(willReplace)))
return 0
}
func (c *StateReplaceProviderCommand) Help() string {
helpText := `
Usage: tofu [global options] state replace-provider [options] FROM_PROVIDER_FQN TO_PROVIDER_FQN
Replace provider for resources in the OpenTofu state.
Options:
-auto-approve Skip interactive approval.
-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.
-ignore-remote-version A rare option used for the remote backend only. See
the remote backend 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.
-state, state-out, and -backup are legacy options supported for the local
backend only. For more information, see the local backend's documentation.
`
return strings.TrimSpace(helpText)
}
func (c *StateReplaceProviderCommand) Synopsis() string {
return "Replace provider in the state"
}