2023-05-02 10:33:06 -05:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2020-03-30 16:26:22 -05:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/mitchellh/cli"
|
2023-08-24 03:56:05 -05:00
|
|
|
|
2023-08-17 07:45:11 -05:00
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/addrs"
|
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/command/arguments"
|
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/command/clistate"
|
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/command/views"
|
2023-08-27 09:51:49 -05:00
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/opentf"
|
2023-08-27 09:58:18 -05:00
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/states"
|
2023-08-17 07:45:11 -05:00
|
|
|
"github.com/placeholderplaceholderplaceholder/opentf/internal/tfdiags"
|
2020-03-30 16:26:22 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// 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 {
|
|
|
|
args = c.Meta.process(args)
|
|
|
|
|
|
|
|
var autoApprove bool
|
backend: Validate remote backend Terraform version
When using the enhanced remote backend, a subset of all Terraform
operations are supported. Of these, only plan and apply can be executed
on the remote infrastructure (e.g. Terraform Cloud). Other operations
run locally and use the remote backend for state storage.
This causes problems when the local version of Terraform does not match
the configured version from the remote workspace. If the two versions
are incompatible, an `import` or `state mv` operation can cause the
remote workspace to be unusable until a manual fix is applied.
To prevent this from happening accidentally, this commit introduces a
check that the local Terraform version and the configured remote
workspace Terraform version are compatible. This check is skipped for
commands which do not write state, and can also be disabled by the use
of a new command-line flag, `-ignore-remote-version`.
Terraform version compatibility is defined as:
- For all releases before 0.14.0, local must exactly equal remote, as
two different versions cannot share state;
- 0.14.0 to 1.0.x are compatible, as we will not change the state
version number until at least Terraform 1.1.0;
- Versions after 1.1.0 must have the same major and minor versions, as
we will not change the state version number in a patch release.
If the two versions are incompatible, a diagnostic is displayed,
advising that the error can be suppressed with `-ignore-remote-version`.
When this flag is used, the diagnostic is still displayed, but as a
warning instead of an error.
Commands which will not write state can assert this fact by calling the
helper `meta.ignoreRemoteBackendVersionConflict`, which will disable the
checks. Those which can write state should instead call the helper
`meta.remoteBackendVersionCheck`, which will return diagnostics for
display.
In addition to these explicit paths for managing the version check, we
have an implicit check in the remote backend's state manager
initialization method. Both of the above helpers will disable this
check. This fallback is in place to ensure that future code paths which
access state cannot accidentally skip the remote version check.
2020-11-13 15:43:56 -06:00
|
|
|
cmdFlags := c.Meta.ignoreRemoteVersionFlagSet("state replace-provider")
|
2020-03-30 16:26:22 -05:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-03-31 12:42:42 -05:00
|
|
|
if diags := c.Meta.checkRequiredVersion(); diags != nil {
|
|
|
|
c.showDiagnostics(diags)
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
2020-03-30 16:26:22 -05:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize the state manager as configured
|
|
|
|
stateMgr, err := c.State()
|
|
|
|
if err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf(errStateLoadingState, err))
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
|
|
|
// Acquire lock if requested
|
|
|
|
if c.stateLock {
|
2021-02-16 06:19:22 -06:00
|
|
|
stateLocker := clistate.NewLocker(c.stateLockTimeout, views.NewStateLocker(arguments.ViewHuman, c.View))
|
|
|
|
if diags := stateLocker.Lock(stateMgr, "state-replace-provider"); diags.HasErrors() {
|
|
|
|
c.showDiagnostics(diags)
|
2020-03-30 16:26:22 -05:00
|
|
|
return 1
|
|
|
|
}
|
2021-02-16 06:19:22 -06:00
|
|
|
defer func() {
|
|
|
|
if diags := stateLocker.Unlock(); diags.HasErrors() {
|
|
|
|
c.showDiagnostics(diags)
|
|
|
|
}
|
|
|
|
}()
|
2020-03-30 16:26:22 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Refresh and load state
|
|
|
|
if err := stateMgr.RefreshState(); err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf("Failed to refresh source state: %s", err))
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
|
|
|
state := stateMgr.State()
|
|
|
|
if state == nil {
|
2020-12-01 11:34:50 -06:00
|
|
|
c.Ui.Error(errStateNotFound)
|
2020-03-30 16:26:22 -05:00
|
|
|
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()
|
2023-08-24 03:56:05 -05:00
|
|
|
c.Ui.Output("OpenTF will perform the following actions:\n")
|
2020-12-01 11:34:50 -06:00
|
|
|
c.Ui.Output(colorize.Color(" [yellow]~[reset] Updating provider:"))
|
2020-03-30 16:26:22 -05:00
|
|
|
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",
|
|
|
|
))
|
2020-12-01 11:34:50 -06:00
|
|
|
v, err := c.Ui.Ask("Enter a value:")
|
2020-03-30 16:26:22 -05:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-08-29 11:10:03 -05:00
|
|
|
b, backendDiags := c.Backend(nil)
|
2022-08-26 15:32:18 -05:00
|
|
|
diags = diags.Append(backendDiags)
|
|
|
|
if backendDiags.HasErrors() {
|
|
|
|
c.showDiagnostics(diags)
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
2022-08-25 14:57:40 -05:00
|
|
|
// Get schemas, if possible, before writing state
|
2023-08-27 09:51:49 -05:00
|
|
|
var schemas *opentf.Schemas
|
2022-08-29 11:10:03 -05:00
|
|
|
if isCloudMode(b) {
|
2022-08-30 17:52:51 -05:00
|
|
|
var schemaDiags tfdiags.Diagnostics
|
|
|
|
schemas, schemaDiags = c.MaybeGetSchemas(state, nil)
|
2022-08-30 18:03:57 -05:00
|
|
|
diags = diags.Append(schemaDiags)
|
2022-08-25 14:57:40 -05:00
|
|
|
}
|
2022-08-26 14:17:37 -05:00
|
|
|
|
2020-03-30 16:26:22 -05:00
|
|
|
// Write the updated state
|
|
|
|
if err := stateMgr.WriteState(state); err != nil {
|
|
|
|
c.Ui.Error(fmt.Sprintf(errStateRmPersist, err))
|
|
|
|
return 1
|
|
|
|
}
|
2022-08-25 14:57:40 -05:00
|
|
|
if err := stateMgr.PersistState(schemas); err != nil {
|
2020-03-30 16:26:22 -05:00
|
|
|
c.Ui.Error(fmt.Sprintf(errStateRmPersist, err))
|
|
|
|
return 1
|
|
|
|
}
|
|
|
|
|
2022-08-30 17:52:51 -05:00
|
|
|
c.showDiagnostics(diags)
|
2020-03-30 16:26:22 -05:00
|
|
|
c.Ui.Output(fmt.Sprintf("\nSuccessfully replaced provider for %d resources.", len(willReplace)))
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *StateReplaceProviderCommand) Help() string {
|
|
|
|
helpText := `
|
2023-08-24 03:56:05 -05:00
|
|
|
Usage: opentf [global options] state replace-provider [options] FROM_PROVIDER_FQN TO_PROVIDER_FQN
|
2020-03-30 16:26:22 -05:00
|
|
|
|
2023-08-24 03:56:05 -05:00
|
|
|
Replace provider for resources in the OpenTF state.
|
2020-03-30 16:26:22 -05:00
|
|
|
|
|
|
|
Options:
|
|
|
|
|
backend: Validate remote backend Terraform version
When using the enhanced remote backend, a subset of all Terraform
operations are supported. Of these, only plan and apply can be executed
on the remote infrastructure (e.g. Terraform Cloud). Other operations
run locally and use the remote backend for state storage.
This causes problems when the local version of Terraform does not match
the configured version from the remote workspace. If the two versions
are incompatible, an `import` or `state mv` operation can cause the
remote workspace to be unusable until a manual fix is applied.
To prevent this from happening accidentally, this commit introduces a
check that the local Terraform version and the configured remote
workspace Terraform version are compatible. This check is skipped for
commands which do not write state, and can also be disabled by the use
of a new command-line flag, `-ignore-remote-version`.
Terraform version compatibility is defined as:
- For all releases before 0.14.0, local must exactly equal remote, as
two different versions cannot share state;
- 0.14.0 to 1.0.x are compatible, as we will not change the state
version number until at least Terraform 1.1.0;
- Versions after 1.1.0 must have the same major and minor versions, as
we will not change the state version number in a patch release.
If the two versions are incompatible, a diagnostic is displayed,
advising that the error can be suppressed with `-ignore-remote-version`.
When this flag is used, the diagnostic is still displayed, but as a
warning instead of an error.
Commands which will not write state can assert this fact by calling the
helper `meta.ignoreRemoteBackendVersionConflict`, which will disable the
checks. Those which can write state should instead call the helper
`meta.remoteBackendVersionCheck`, which will return diagnostics for
display.
In addition to these explicit paths for managing the version check, we
have an implicit check in the remote backend's state manager
initialization method. Both of the above helpers will disable this
check. This fallback is in place to ensure that future code paths which
access state cannot accidentally skip the remote version check.
2020-11-13 15:43:56 -06:00
|
|
|
-auto-approve Skip interactive approval.
|
2020-03-30 16:26:22 -05:00
|
|
|
|
2021-05-12 11:05:03 -05:00
|
|
|
-lock=false Don't hold a state lock during the operation. This is
|
|
|
|
dangerous if others might concurrently run commands
|
|
|
|
against the same workspace.
|
2020-03-30 16:26:22 -05:00
|
|
|
|
backend: Validate remote backend Terraform version
When using the enhanced remote backend, a subset of all Terraform
operations are supported. Of these, only plan and apply can be executed
on the remote infrastructure (e.g. Terraform Cloud). Other operations
run locally and use the remote backend for state storage.
This causes problems when the local version of Terraform does not match
the configured version from the remote workspace. If the two versions
are incompatible, an `import` or `state mv` operation can cause the
remote workspace to be unusable until a manual fix is applied.
To prevent this from happening accidentally, this commit introduces a
check that the local Terraform version and the configured remote
workspace Terraform version are compatible. This check is skipped for
commands which do not write state, and can also be disabled by the use
of a new command-line flag, `-ignore-remote-version`.
Terraform version compatibility is defined as:
- For all releases before 0.14.0, local must exactly equal remote, as
two different versions cannot share state;
- 0.14.0 to 1.0.x are compatible, as we will not change the state
version number until at least Terraform 1.1.0;
- Versions after 1.1.0 must have the same major and minor versions, as
we will not change the state version number in a patch release.
If the two versions are incompatible, a diagnostic is displayed,
advising that the error can be suppressed with `-ignore-remote-version`.
When this flag is used, the diagnostic is still displayed, but as a
warning instead of an error.
Commands which will not write state can assert this fact by calling the
helper `meta.ignoreRemoteBackendVersionConflict`, which will disable the
checks. Those which can write state should instead call the helper
`meta.remoteBackendVersionCheck`, which will return diagnostics for
display.
In addition to these explicit paths for managing the version check, we
have an implicit check in the remote backend's state manager
initialization method. Both of the above helpers will disable this
check. This fallback is in place to ensure that future code paths which
access state cannot accidentally skip the remote version check.
2020-11-13 15:43:56 -06:00
|
|
|
-lock-timeout=0s Duration to retry a state lock.
|
|
|
|
|
2021-05-11 13:37:32 -05:00
|
|
|
-ignore-remote-version A rare option used for the remote backend only. See
|
|
|
|
the remote backend documentation for more information.
|
backend: Validate remote backend Terraform version
When using the enhanced remote backend, a subset of all Terraform
operations are supported. Of these, only plan and apply can be executed
on the remote infrastructure (e.g. Terraform Cloud). Other operations
run locally and use the remote backend for state storage.
This causes problems when the local version of Terraform does not match
the configured version from the remote workspace. If the two versions
are incompatible, an `import` or `state mv` operation can cause the
remote workspace to be unusable until a manual fix is applied.
To prevent this from happening accidentally, this commit introduces a
check that the local Terraform version and the configured remote
workspace Terraform version are compatible. This check is skipped for
commands which do not write state, and can also be disabled by the use
of a new command-line flag, `-ignore-remote-version`.
Terraform version compatibility is defined as:
- For all releases before 0.14.0, local must exactly equal remote, as
two different versions cannot share state;
- 0.14.0 to 1.0.x are compatible, as we will not change the state
version number until at least Terraform 1.1.0;
- Versions after 1.1.0 must have the same major and minor versions, as
we will not change the state version number in a patch release.
If the two versions are incompatible, a diagnostic is displayed,
advising that the error can be suppressed with `-ignore-remote-version`.
When this flag is used, the diagnostic is still displayed, but as a
warning instead of an error.
Commands which will not write state can assert this fact by calling the
helper `meta.ignoreRemoteBackendVersionConflict`, which will disable the
checks. Those which can write state should instead call the helper
`meta.remoteBackendVersionCheck`, which will return diagnostics for
display.
In addition to these explicit paths for managing the version check, we
have an implicit check in the remote backend's state manager
initialization method. Both of the above helpers will disable this
check. This fallback is in place to ensure that future code paths which
access state cannot accidentally skip the remote version check.
2020-11-13 15:43:56 -06:00
|
|
|
|
2021-05-11 13:37:32 -05:00
|
|
|
-state, state-out, and -backup are legacy options supported for the local
|
|
|
|
backend only. For more information, see the local backend's documentation.
|
2020-03-30 16:26:22 -05:00
|
|
|
|
|
|
|
`
|
|
|
|
return strings.TrimSpace(helpText)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *StateReplaceProviderCommand) Synopsis() string {
|
|
|
|
return "Replace provider in the state"
|
|
|
|
}
|