2017-01-19 05:50:04 +01:00
package command
import (
2017-04-01 21:42:13 +02:00
"context"
2017-03-30 21:53:21 +02:00
"errors"
2017-01-19 05:50:04 +01:00
"fmt"
"io/ioutil"
2018-11-09 23:26:01 +01:00
"log"
2017-01-19 05:50:04 +01:00
"os"
"path/filepath"
2017-03-01 21:35:59 +01:00
"sort"
2017-01-19 05:50:04 +01:00
"strings"
2021-02-16 13:19:22 +01:00
"github.com/hashicorp/terraform/command/arguments"
2017-04-01 20:58:19 +02:00
"github.com/hashicorp/terraform/command/clistate"
2021-02-16 13:19:22 +01:00
"github.com/hashicorp/terraform/command/views"
2021-05-17 17:42:17 +02:00
"github.com/hashicorp/terraform/internal/backend"
2018-10-31 16:45:03 +01:00
"github.com/hashicorp/terraform/states"
"github.com/hashicorp/terraform/states/statemgr"
2017-01-19 05:50:04 +01:00
"github.com/hashicorp/terraform/terraform"
)
2018-10-31 16:45:03 +01:00
type backendMigrateOpts struct {
OneType , TwoType string
One , Two backend . Backend
// Fields below are set internally when migrate is called
oneEnv string // source env
twoEnv string // dest env
force bool // if true, won't ask for confirmation
}
2017-01-19 05:50:04 +01:00
// backendMigrateState handles migrating (copying) state from one backend
// to another. This function handles asking the user for confirmation
// as well as the copy itself.
//
// This function can handle all scenarios of state migration regardless
// of the existence of state in either backend.
//
// After migrating the state, the existing state in the first backend
// remains untouched.
2017-02-09 21:35:49 +01:00
//
// This will attempt to lock both states for the migration.
2017-01-19 05:50:04 +01:00
func ( m * Meta ) backendMigrateState ( opts * backendMigrateOpts ) error {
2018-11-09 23:26:01 +01:00
log . Printf ( "[TRACE] backendMigrateState: need to migrate from %q to %q backend config" , opts . OneType , opts . TwoType )
2017-03-01 19:59:17 +01:00
// We need to check what the named state status is. If we're converting
// from multi-state to single-state for example, we need to handle that.
var oneSingle , twoSingle bool
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
oneStates , err := opts . One . Workspaces ( )
if err == backend . ErrWorkspacesNotSupported {
2017-03-01 19:59:17 +01:00
oneSingle = true
err = nil
}
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateLoadStates ) , opts . OneType , err )
}
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
_ , err = opts . Two . Workspaces ( )
if err == backend . ErrWorkspacesNotSupported {
2017-03-01 19:59:17 +01:00
twoSingle = true
err = nil
}
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateLoadStates ) , opts . TwoType , err )
}
2021-01-26 20:39:11 +01:00
// Set up defaults
2017-03-01 20:40:28 +01:00
opts . oneEnv = backend . DefaultStateName
opts . twoEnv = backend . DefaultStateName
2017-03-30 21:53:21 +02:00
opts . force = m . forceInitCopy
2017-03-01 20:40:28 +01:00
2021-01-19 17:38:31 +01:00
// Disregard remote Terraform version for the state source backend. If it's a
// Terraform Cloud remote backend, we don't care about the remote version,
// as we are migrating away and will not break a remote workspace.
m . ignoreRemoteBackendVersionConflict ( opts . One )
// Check the remote Terraform version for the state destination backend. If
// it's a Terraform Cloud remote backend, we want to ensure that we don't
// break the workspace by uploading an incompatible state file.
diags := m . remoteBackendVersionCheck ( opts . Two , opts . twoEnv )
if diags . HasErrors ( ) {
return diags . Err ( )
}
2017-04-11 14:04:36 +02:00
// Determine migration behavior based on whether the source/destination
2017-03-01 19:59:17 +01:00
// supports multi-state.
switch {
// Single-state to single-state. This is the easiest case: we just
// copy the default state directly.
case oneSingle && twoSingle :
return m . backendMigrateState_s_s ( opts )
// Single-state to multi-state. This is easy since we just copy
// the default state and ignore the rest in the destination.
case oneSingle && ! twoSingle :
return m . backendMigrateState_s_s ( opts )
// Multi-state to single-state. If the source has more than the default
// state this is complicated since we have to ask the user what to do.
case ! oneSingle && twoSingle :
// If the source only has one state and it is the default,
// treat it as if it doesn't support multi-state.
if len ( oneStates ) == 1 && oneStates [ 0 ] == backend . DefaultStateName {
return m . backendMigrateState_s_s ( opts )
}
2017-03-01 20:34:45 +01:00
return m . backendMigrateState_S_s ( opts )
2017-03-01 19:59:17 +01:00
// Multi-state to multi-state. We merge the states together (migrating
// each from the source to the destination one by one).
case ! oneSingle && ! twoSingle :
// If the source only has one state and it is the default,
// treat it as if it doesn't support multi-state.
if len ( oneStates ) == 1 && oneStates [ 0 ] == backend . DefaultStateName {
return m . backendMigrateState_s_s ( opts )
}
2017-03-01 21:35:59 +01:00
return m . backendMigrateState_S_S ( opts )
2017-03-01 19:59:17 +01:00
}
return nil
}
//-------------------------------------------------------------------
// State Migration Scenarios
//
// The functions below cover handling all the various scenarios that
// can exist when migrating state. They are named in an immediately not
// obvious format but is simple:
//
// Format: backendMigrateState_s1_s2[_suffix]
//
// When s1 or s2 is lower case, it means that it is a single state backend.
// When either is uppercase, it means that state is a multi-state backend.
// The suffix is used to disambiguate multiple cases with the same type of
// states.
//
//-------------------------------------------------------------------
2017-03-01 21:35:59 +01:00
// Multi-state to multi-state.
func ( m * Meta ) backendMigrateState_S_S ( opts * backendMigrateOpts ) error {
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: migrating all named workspaces" )
2017-03-01 21:35:59 +01:00
// Ask the user if they want to migrate their existing remote state
migrate , err := m . confirm ( & terraform . InputOpts {
Id : "backend-migrate-multistate-to-multistate" ,
Query : fmt . Sprintf (
2017-05-31 00:06:13 +02:00
"Do you want to migrate all workspaces to %q?" ,
2017-03-01 21:35:59 +01:00
opts . TwoType ) ,
Description : fmt . Sprintf (
strings . TrimSpace ( inputBackendMigrateMultiToMulti ) ,
opts . OneType , opts . TwoType ) ,
} )
if err != nil {
return fmt . Errorf (
"Error asking for state migration action: %s" , err )
}
if ! migrate {
return fmt . Errorf ( "Migration aborted by user." )
}
// Read all the states
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
oneStates , err := opts . One . Workspaces ( )
2017-03-01 21:35:59 +01:00
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateLoadStates ) , opts . OneType , err )
}
// Sort the states so they're always copied alphabetically
sort . Strings ( oneStates )
// Go through each and migrate
for _ , name := range oneStates {
// Copy the same names
opts . oneEnv = name
opts . twoEnv = name
// Force it, we confirmed above
opts . force = true
// Perform the migration
if err := m . backendMigrateState_s_s ( opts ) ; err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateMulti ) , name , opts . OneType , opts . TwoType , err )
}
}
2018-10-17 04:48:28 +02:00
return nil
2017-03-01 21:35:59 +01:00
}
2017-03-01 20:34:45 +01:00
// Multi-state to single state.
func ( m * Meta ) backendMigrateState_S_s ( opts * backendMigrateOpts ) error {
2018-11-09 23:26:01 +01:00
log . Printf ( "[TRACE] backendMigrateState: target backend type %q does not support named workspaces" , opts . TwoType )
2020-06-16 18:23:15 +02:00
currentEnv , err := m . Workspace ( )
if err != nil {
return err
}
2017-03-01 20:40:28 +01:00
2017-03-30 21:53:21 +02:00
migrate := opts . force
2017-03-21 20:05:51 +01:00
if ! migrate {
var err error
// Ask the user if they want to migrate their existing remote state
migrate , err = m . confirm ( & terraform . InputOpts {
Id : "backend-migrate-multistate-to-single" ,
Query : fmt . Sprintf (
2017-05-31 00:06:13 +02:00
"Destination state %q doesn't support workspaces.\n" +
"Do you want to copy only your current workspace?" ,
2017-03-21 20:05:51 +01:00
opts . TwoType ) ,
Description : fmt . Sprintf (
strings . TrimSpace ( inputBackendMigrateMultiToSingle ) ,
opts . OneType , opts . TwoType , currentEnv ) ,
} )
if err != nil {
return fmt . Errorf (
"Error asking for state migration action: %s" , err )
}
2017-03-01 20:34:45 +01:00
}
2017-03-21 20:05:51 +01:00
2017-03-01 20:34:45 +01:00
if ! migrate {
return fmt . Errorf ( "Migration aborted by user." )
}
// Copy the default state
2017-03-01 20:40:28 +01:00
opts . oneEnv = currentEnv
2017-03-16 20:31:50 +01:00
// now switch back to the default env so we can acccess the new backend
2017-05-31 02:13:43 +02:00
m . SetWorkspace ( backend . DefaultStateName )
2017-03-16 20:31:50 +01:00
2017-03-01 20:34:45 +01:00
return m . backendMigrateState_s_s ( opts )
}
2017-03-01 19:59:17 +01:00
// Single state to single state, assumed default state name.
func ( m * Meta ) backendMigrateState_s_s ( opts * backendMigrateOpts ) error {
2018-11-09 23:26:01 +01:00
log . Printf ( "[TRACE] backendMigrateState: migrating %q workspace to %q workspace" , opts . oneEnv , opts . twoEnv )
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
stateOne , err := opts . One . StateMgr ( opts . oneEnv )
2017-03-01 19:59:17 +01:00
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateSingleLoadDefault ) , opts . OneType , err )
}
if err := stateOne . RefreshState ( ) ; err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateSingleLoadDefault ) , opts . OneType , err )
}
2018-10-31 16:45:03 +01:00
// Do not migrate workspaces without state.
if stateOne . State ( ) . Empty ( ) {
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: source workspace has empty state, so nothing to migrate" )
2018-10-31 16:45:03 +01:00
return nil
}
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
stateTwo , err := opts . Two . StateMgr ( opts . twoEnv )
2018-10-31 16:45:03 +01:00
if err == backend . ErrDefaultWorkspaceNotSupported {
// If the backend doesn't support using the default state, we ask the user
// for a new name and migrate the default state to the given named state.
stateTwo , err = func ( ) ( statemgr . Full , error ) {
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: target doesn't support a default workspace, so we must prompt for a new name" )
2019-03-07 21:07:13 +01:00
name , err := m . UIInput ( ) . Input ( context . Background ( ) , & terraform . InputOpts {
2018-10-31 16:45:03 +01:00
Id : "new-state-name" ,
Query : fmt . Sprintf (
"[reset][bold][yellow]The %q backend configuration only allows " +
"named workspaces![reset]" ,
opts . TwoType ) ,
Description : strings . TrimSpace ( inputBackendNewWorkspaceName ) ,
} )
if err != nil {
return nil , fmt . Errorf ( "Error asking for new state name: %s" , err )
}
// Update the name of the target state.
opts . twoEnv = name
stateTwo , err := opts . Two . StateMgr ( opts . twoEnv )
if err != nil {
return nil , err
}
2020-06-16 18:23:15 +02:00
// Ignore invalid workspace name as it is irrelevant in this context.
workspace , _ := m . Workspace ( )
2018-10-31 16:45:03 +01:00
// If the currently selected workspace is the default workspace, then set
// the named workspace as the new selected workspace.
2020-06-16 18:23:15 +02:00
if workspace == backend . DefaultStateName {
2018-10-31 16:45:03 +01:00
if err := m . SetWorkspace ( opts . twoEnv ) ; err != nil {
return nil , fmt . Errorf ( "Failed to set new workspace: %s" , err )
}
}
return stateTwo , nil
} ( )
}
2017-03-01 19:59:17 +01:00
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateSingleLoadDefault ) , opts . TwoType , err )
}
if err := stateTwo . RefreshState ( ) ; err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateSingleLoadDefault ) , opts . TwoType , err )
}
2017-03-30 21:53:21 +02:00
// Check if we need migration at all.
// This is before taking a lock, because they may also correspond to the same lock.
one := stateOne . State ( )
two := stateTwo . State ( )
// no reason to migrate if the state is already there
if one . Equal ( two ) {
// Equal isn't identical; it doesn't check lineage.
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
sm1 , _ := stateOne . ( statemgr . PersistentMeta )
sm2 , _ := stateTwo . ( statemgr . PersistentMeta )
if one != nil && two != nil {
if sm1 == nil || sm2 == nil {
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: both source and destination workspaces have no state, so no migration is needed" )
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
return nil
}
if sm1 . StateSnapshotMeta ( ) . Lineage == sm2 . StateSnapshotMeta ( ) . Lineage {
2018-11-09 23:26:01 +01:00
log . Printf ( "[TRACE] backendMigrateState: both source and destination workspaces have equal state with lineage %q, so no migration is needed" , sm1 . StateSnapshotMeta ( ) . Lineage )
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
return nil
}
2017-03-30 21:53:21 +02:00
}
}
2017-04-01 21:42:13 +02:00
if m . stateLock {
2018-02-23 17:28:47 +01:00
lockCtx := context . Background ( )
2017-02-15 00:51:32 +01:00
2021-02-16 13:19:22 +01:00
view := views . NewStateLocker ( arguments . ViewHuman , m . View )
locker := clistate . NewLocker ( m . stateLockTimeout , view )
lockerOne := locker . WithContext ( lockCtx )
if diags := lockerOne . Lock ( stateOne , "migration source state" ) ; diags . HasErrors ( ) {
return diags . Err ( )
2017-04-01 21:42:13 +02:00
}
2021-02-16 13:19:22 +01:00
defer lockerOne . Unlock ( )
2017-02-09 21:35:49 +01:00
2021-02-16 13:19:22 +01:00
lockerTwo := locker . WithContext ( lockCtx )
if diags := lockerTwo . Lock ( stateTwo , "migration destination state" ) ; diags . HasErrors ( ) {
return diags . Err ( )
2017-04-01 21:42:13 +02:00
}
2021-02-16 13:19:22 +01:00
defer lockerTwo . Unlock ( )
2017-02-09 21:35:49 +01:00
2017-03-30 21:53:21 +02:00
// We now own a lock, so double check that we have the version
// corresponding to the lock.
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: refreshing source workspace state" )
2017-03-30 21:53:21 +02:00
if err := stateOne . RefreshState ( ) ; err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateSingleLoadDefault ) , opts . OneType , err )
}
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: refreshing target workspace state" )
2017-03-30 21:53:21 +02:00
if err := stateTwo . RefreshState ( ) ; err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateSingleLoadDefault ) , opts . OneType , err )
}
one = stateOne . State ( )
two = stateTwo . State ( )
}
2017-01-19 05:50:04 +01:00
2020-08-11 17:43:01 +02:00
var confirmFunc func ( statemgr . Full , statemgr . Full , * backendMigrateOpts ) ( bool , error )
2017-01-19 05:50:04 +01:00
switch {
// No migration necessary
case one . Empty ( ) && two . Empty ( ) :
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: both source and destination workspaces have empty state, so no migration is required" )
2017-01-19 05:50:04 +01:00
return nil
// No migration necessary if we're inheriting state.
case one . Empty ( ) && ! two . Empty ( ) :
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: source workspace has empty state, so no migration is required" )
2017-01-19 05:50:04 +01:00
return nil
// We have existing state moving into no state. Ask the user if
// they'd like to do this.
case ! one . Empty ( ) && two . Empty ( ) :
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: target workspace has empty state, so might copy source workspace state" )
2017-01-19 05:50:04 +01:00
confirmFunc = m . backendMigrateEmptyConfirm
// Both states are non-empty, meaning we need to determine which
// state should be used and update accordingly.
case ! one . Empty ( ) && ! two . Empty ( ) :
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: both source and destination workspaces have states, so might overwrite destination with source" )
2017-01-19 05:50:04 +01:00
confirmFunc = m . backendMigrateNonEmptyConfirm
}
if confirmFunc == nil {
panic ( "confirmFunc must not be nil" )
}
2017-03-01 21:35:59 +01:00
if ! opts . force {
2017-03-30 21:53:21 +02:00
// Abort if we can't ask for input.
if ! m . input {
2018-11-09 23:26:01 +01:00
log . Print ( "[TRACE] backendMigrateState: can't prompt for input, so aborting migration" )
2017-05-24 03:58:37 +02:00
return errors . New ( "error asking for state migration action: input disabled" )
2017-03-30 21:53:21 +02:00
}
2017-03-01 21:35:59 +01:00
// Confirm with the user whether we want to copy state over
confirm , err := confirmFunc ( stateOne , stateTwo , opts )
if err != nil {
2018-11-15 00:08:36 +01:00
log . Print ( "[TRACE] backendMigrateState: error reading input, so aborting migration" )
2017-03-01 21:35:59 +01:00
return err
}
if ! confirm {
2018-11-15 00:08:36 +01:00
log . Print ( "[TRACE] backendMigrateState: user cancelled at confirmation prompt, so aborting migration" )
2017-03-01 21:35:59 +01:00
return nil
}
2017-01-19 05:50:04 +01:00
}
2018-11-13 03:30:01 +01:00
// Confirmed! We'll have the statemgr package handle the migration, which
// includes preserving any lineage/serial information where possible, if
// both managers support such metadata.
2018-11-15 00:08:36 +01:00
log . Print ( "[TRACE] backendMigrateState: migration confirmed, so migrating" )
2018-11-13 03:30:01 +01:00
if err := statemgr . Migrate ( stateTwo , stateOne ) ; err != nil {
2017-01-19 05:50:04 +01:00
return fmt . Errorf ( strings . TrimSpace ( errBackendStateCopy ) ,
opts . OneType , opts . TwoType , err )
}
2017-03-01 19:59:17 +01:00
if err := stateTwo . PersistState ( ) ; err != nil {
2017-01-19 05:50:04 +01:00
return fmt . Errorf ( strings . TrimSpace ( errBackendStateCopy ) ,
opts . OneType , opts . TwoType , err )
}
// And we're done.
return nil
}
2020-08-11 17:43:01 +02:00
func ( m * Meta ) backendMigrateEmptyConfirm ( one , two statemgr . Full , opts * backendMigrateOpts ) ( bool , error ) {
2017-01-19 05:50:04 +01:00
inputOpts := & terraform . InputOpts {
2017-12-20 23:50:37 +01:00
Id : "backend-migrate-copy-to-empty" ,
Query : "Do you want to copy existing state to the new backend?" ,
2017-01-19 05:50:04 +01:00
Description : fmt . Sprintf (
strings . TrimSpace ( inputBackendMigrateEmpty ) ,
opts . OneType , opts . TwoType ) ,
}
2017-12-18 17:38:51 +01:00
return m . confirm ( inputOpts )
2017-01-19 05:50:04 +01:00
}
2017-03-01 19:59:17 +01:00
func ( m * Meta ) backendMigrateNonEmptyConfirm (
2020-08-11 17:43:01 +02:00
stateOne , stateTwo statemgr . Full , opts * backendMigrateOpts ) ( bool , error ) {
2017-01-19 05:50:04 +01:00
// We need to grab both states so we can write them to a file
2017-03-01 19:59:17 +01:00
one := stateOne . State ( )
two := stateTwo . State ( )
2017-01-19 05:50:04 +01:00
// Save both to a temporary
td , err := ioutil . TempDir ( "" , "terraform" )
if err != nil {
return false , fmt . Errorf ( "Error creating temporary directory: %s" , err )
}
defer os . RemoveAll ( td )
// Helper to write the state
terraform: Ugly huge change to weave in new State and Plan types
Due to how often the state and plan types are referenced throughout
Terraform, there isn't a great way to switch them out gradually. As a
consequence, this huge commit gets us from the old world to a _compilable_
new world, but still has a large number of known test failures due to
key functionality being stubbed out.
The stubs here are for anything that interacts with providers, since we
now need to do the follow-up work to similarly replace the old
terraform.ResourceProvider interface with its replacement in the new
"providers" package. That work, along with work to fix the remaining
failing tests, will follow in subsequent commits.
The aim here was to replace all references to terraform.State and its
downstream types with states.State, terraform.Plan with plans.Plan,
state.State with statemgr.State, and switch to the new implementations of
the state and plan file formats. However, due to the number of times those
types are used, this also ended up affecting numerous other parts of core
such as terraform.Hook, the backend.Backend interface, and most of the CLI
commands.
Just as with 5861dbf3fc49b19587a31816eb06f511ab861bb4 before, I apologize
in advance to the person who inevitably just found this huge commit while
spelunking through the commit history.
2018-08-14 23:24:45 +02:00
saveHelper := func ( n , path string , s * states . State ) error {
mgr := statemgr . NewFilesystem ( path )
return mgr . WriteState ( s )
2017-01-19 05:50:04 +01:00
}
// Write the states
onePath := filepath . Join ( td , fmt . Sprintf ( "1-%s.tfstate" , opts . OneType ) )
twoPath := filepath . Join ( td , fmt . Sprintf ( "2-%s.tfstate" , opts . TwoType ) )
if err := saveHelper ( opts . OneType , onePath , one ) ; err != nil {
return false , fmt . Errorf ( "Error saving temporary state: %s" , err )
}
if err := saveHelper ( opts . TwoType , twoPath , two ) ; err != nil {
return false , fmt . Errorf ( "Error saving temporary state: %s" , err )
}
// Ask for confirmation
inputOpts := & terraform . InputOpts {
2017-12-20 23:50:37 +01:00
Id : "backend-migrate-to-backend" ,
Query : "Do you want to copy existing state to the new backend?" ,
2017-01-19 05:50:04 +01:00
Description : fmt . Sprintf (
strings . TrimSpace ( inputBackendMigrateNonEmpty ) ,
opts . OneType , opts . TwoType , onePath , twoPath ) ,
}
// Confirm with the user that the copy should occur
2017-12-18 17:38:51 +01:00
return m . confirm ( inputOpts )
2017-01-19 05:50:04 +01:00
}
2017-03-01 19:59:17 +01:00
const errMigrateLoadStates = `
2017-12-20 23:50:37 +01:00
Error inspecting states in the % q backend :
% s
2017-03-01 19:59:17 +01:00
2017-04-11 14:04:36 +02:00
Prior to changing backends , Terraform inspects the source and destination
2017-03-01 19:59:17 +01:00
states to determine what kind of migration steps need to be taken , if any .
Terraform failed to load the states . The data in both the source and the
destination remain unmodified . Please resolve the above error and try again .
`
const errMigrateSingleLoadDefault = `
2017-12-20 23:50:37 +01:00
Error loading state :
% [ 2 ] s
2017-03-01 19:59:17 +01:00
2017-12-20 23:50:37 +01:00
Terraform failed to load the default state from the % [ 1 ] q backend .
2017-03-01 19:59:17 +01:00
State migration cannot occur unless the state can be loaded . Backend
modification and state migration has been aborted . The state in both the
source and the destination remain unmodified . Please resolve the
above error and try again .
`
2017-03-01 21:35:59 +01:00
const errMigrateMulti = `
2018-10-31 16:45:03 +01:00
Error migrating the workspace % q from the previous % q backend
to the newly configured % q backend :
2017-12-20 23:50:37 +01:00
% s
2017-03-01 21:35:59 +01:00
2017-05-31 00:06:13 +02:00
Terraform copies workspaces in alphabetical order . Any workspaces
alphabetically earlier than this one have been copied . Any workspaces
later than this haven ' t been modified in the destination . No workspaces
2017-03-01 21:35:59 +01:00
in the source state have been modified .
Please resolve the error above and run the initialization command again .
2017-05-31 00:06:13 +02:00
This will attempt to copy ( with permission ) all workspaces again .
2017-03-01 21:35:59 +01:00
`
2017-01-19 05:50:04 +01:00
const errBackendStateCopy = `
2018-10-31 16:45:03 +01:00
Error copying state from the previous % q backend to the newly configured
% q backend :
2017-12-20 23:50:37 +01:00
% s
2017-01-19 05:50:04 +01:00
2017-12-20 23:50:37 +01:00
The state in the previous backend remains intact and unmodified . Please resolve
the error above and try again .
2017-01-19 05:50:04 +01:00
`
const inputBackendMigrateEmpty = `
2017-12-20 23:50:37 +01:00
Pre - existing state was found while migrating the previous % q backend to the
newly configured % q backend . No existing state was found in the newly
configured % [ 2 ] q backend . Do you want to copy this state to the new % [ 2 ] q
backend ? Enter "yes" to copy and "no" to start with an empty state .
2017-01-19 05:50:04 +01:00
`
const inputBackendMigrateNonEmpty = `
2017-12-20 23:50:37 +01:00
Pre - existing state was found while migrating the previous % q backend to the
newly configured % q backend . An existing non - empty state already exists in
the new backend . The two states have been saved to temporary files that will be
removed after responding to this query .
2017-01-19 05:50:04 +01:00
2017-12-20 23:50:37 +01:00
Previous ( type % [ 1 ] q ) : % [ 3 ] s
New ( type % [ 2 ] q ) : % [ 4 ] s
2017-01-19 05:50:04 +01:00
2017-12-20 23:50:37 +01:00
Do you want to overwrite the state in the new backend with the previous state ?
Enter "yes" to copy and "no" to start with the existing state in the newly
configured % [ 2 ] q backend .
2017-01-19 05:50:04 +01:00
`
2017-03-01 20:34:45 +01:00
const inputBackendMigrateMultiToSingle = `
2017-12-20 23:50:37 +01:00
The existing % [ 1 ] q backend supports workspaces and you currently are
using more than one . The newly configured % [ 2 ] q backend doesn ' t support
workspaces . If you continue , Terraform will copy your current workspace % [ 3 ] q
to the default workspace in the target backend . Your existing workspaces in the
source backend won ' t be modified . If you want to switch workspaces , back them
up , or cancel altogether , answer "no" and Terraform will abort .
2017-03-01 20:34:45 +01:00
`
2017-03-01 21:35:59 +01:00
const inputBackendMigrateMultiToMulti = `
2018-10-31 16:45:03 +01:00
Both the existing % [ 1 ] q backend and the newly configured % [ 2 ] q backend
support workspaces . When migrating between backends , Terraform will copy
all workspaces ( with the same names ) . THIS WILL OVERWRITE any conflicting
2017-03-01 21:35:59 +01:00
states in the destination .
2017-05-31 00:06:13 +02:00
Terraform initialization doesn ' t currently migrate only select workspaces .
If you want to migrate a select number of workspaces , you must manually
2017-03-01 21:35:59 +01:00
pull and push those states .
If you answer "yes" , Terraform will migrate all states . If you answer
"no" , Terraform will abort .
`
2018-10-31 16:45:03 +01:00
const inputBackendNewWorkspaceName = `
Please provide a new workspace name ( e . g . dev , test ) that will be used
to migrate the existing default workspace .
`
const inputBackendSelectWorkspace = `
This is expected behavior when the selected workspace did not have an
existing non - empty state . Please enter a number to select a workspace :
% s
`