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-05-17 17:42:17 +02:00
"github.com/hashicorp/terraform/internal/backend"
2021-09-22 23:53:33 +02:00
"github.com/hashicorp/terraform/internal/cloud"
2021-05-17 21:07:38 +02:00
"github.com/hashicorp/terraform/internal/command/arguments"
"github.com/hashicorp/terraform/internal/command/clistate"
"github.com/hashicorp/terraform/internal/command/views"
2021-05-17 21:43:35 +02:00
"github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/states/statemgr"
2021-05-17 21:46:19 +02:00
"github.com/hashicorp/terraform/internal/terraform"
2017-01-19 05:50:04 +01:00
)
2018-10-31 16:45:03 +01:00
type backendMigrateOpts struct {
2021-10-05 22:36:50 +02:00
SourceType , DestinationType string
Source , Destination backend . Backend
2018-10-31 16:45:03 +01:00
// Fields below are set internally when migrate is called
2021-10-05 22:36:50 +02:00
sourceWorkspace string
destinationWorkspace string
force bool // if true, won't ask for confirmation
2018-10-31 16:45:03 +01:00
}
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 {
2021-10-09 14:47:12 +02:00
log . Printf ( "[INFO] backendMigrateState: need to migrate from %q to %q backend config" , opts . SourceType , opts . DestinationType )
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.
2021-09-22 23:53:33 +02:00
var sourceSingleState , destinationSingleState , sourceTFC , destinationTFC bool
2017-03-01 19:59:17 +01:00
2021-09-22 23:53:33 +02:00
_ , sourceTFC = opts . Source . ( * cloud . Cloud )
_ , destinationTFC = opts . Destination . ( * cloud . Cloud )
sourceWorkspaces , sourceSingleState , err := retrieveWorkspaces ( opts . Source , opts . SourceType )
if err != nil {
return err
2017-03-01 19:59:17 +01:00
}
2021-09-22 23:53:33 +02:00
destinationWorkspaces , destinationSingleState , err := retrieveWorkspaces ( opts . Destination , opts . SourceType )
2017-03-01 19:59:17 +01:00
if err != nil {
2021-09-22 23:53:33 +02:00
return err
2017-03-01 19:59:17 +01:00
}
2021-01-26 20:39:11 +01:00
// Set up defaults
2021-10-05 22:36:50 +02:00
opts . sourceWorkspace = backend . DefaultStateName
opts . destinationWorkspace = 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.
2021-08-24 21:28:12 +02:00
m . ignoreRemoteVersionConflict ( opts . Source )
2021-01-19 17:38:31 +01:00
2021-10-21 20:10:25 +02:00
// Disregard remote Terraform version if instructed to do so via CLI flag.
if m . ignoreRemoteVersion {
2021-08-24 21:28:12 +02:00
m . ignoreRemoteVersionConflict ( opts . Destination )
2021-10-21 20:10:25 +02:00
} else {
2021-06-02 21:23:56 +02:00
// 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.
2021-10-21 20:10:25 +02:00
for _ , workspace := range destinationWorkspaces {
2021-08-24 21:28:12 +02:00
diags := m . remoteVersionCheck ( opts . Destination , workspace )
2021-10-21 20:10:25 +02:00
if diags . HasErrors ( ) {
return diags . Err ( )
}
}
// If there are no specified destination workspaces, perform a remote
// backend version check with the default workspace.
if len ( destinationWorkspaces ) == 0 {
2021-08-24 21:28:12 +02:00
diags := m . remoteVersionCheck ( opts . Destination , backend . DefaultStateName )
2021-10-21 20:10:25 +02:00
if diags . HasErrors ( ) {
return diags . Err ( )
}
2021-06-02 21:23:56 +02:00
}
2021-01-19 17:38:31 +01:00
}
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 {
2021-09-22 23:53:33 +02:00
case sourceTFC || destinationTFC :
return m . backendMigrateTFC ( opts )
2017-03-01 19:59:17 +01:00
// Single-state to single-state. This is the easiest case: we just
// copy the default state directly.
2021-10-05 22:36:50 +02:00
case sourceSingleState && destinationSingleState :
2017-03-01 19:59:17 +01:00
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.
2021-10-05 22:36:50 +02:00
case sourceSingleState && ! destinationSingleState :
2017-03-01 19:59:17 +01:00
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.
2021-10-05 22:36:50 +02:00
case ! sourceSingleState && destinationSingleState :
2017-03-01 19:59:17 +01:00
// If the source only has one state and it is the default,
// treat it as if it doesn't support multi-state.
2021-10-05 22:36:50 +02:00
if len ( sourceWorkspaces ) == 1 && sourceWorkspaces [ 0 ] == backend . DefaultStateName {
2017-03-01 19:59:17 +01:00
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).
2021-10-05 22:36:50 +02:00
case ! sourceSingleState && ! destinationSingleState :
2017-03-01 19:59:17 +01:00
// If the source only has one state and it is the default,
// treat it as if it doesn't support multi-state.
2021-10-05 22:36:50 +02:00
if len ( sourceWorkspaces ) == 1 && sourceWorkspaces [ 0 ] == backend . DefaultStateName {
2017-03-01 19:59:17 +01:00
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 {
2021-10-09 14:47:12 +02:00
log . Print ( "[INFO] backendMigrateState: migrating all named workspaces" )
2018-11-09 23:26:01 +01:00
2021-08-20 20:46:09 +02:00
migrate := opts . force
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-multistate" ,
Query : fmt . Sprintf (
"Do you want to migrate all workspaces to %q?" ,
2021-10-05 22:36:50 +02:00
opts . DestinationType ) ,
2021-08-20 20:46:09 +02:00
Description : fmt . Sprintf (
strings . TrimSpace ( inputBackendMigrateMultiToMulti ) ,
2021-10-05 22:36:50 +02:00
opts . SourceType , opts . DestinationType ) ,
2021-08-20 20:46:09 +02:00
} )
if err != nil {
return fmt . Errorf (
"Error asking for state migration action: %s" , err )
}
2017-03-01 21:35:59 +01:00
}
if ! migrate {
return fmt . Errorf ( "Migration aborted by user." )
}
// Read all the states
2021-10-05 22:36:50 +02:00
sourceWorkspaces , err := opts . Source . Workspaces ( )
2017-03-01 21:35:59 +01:00
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateLoadStates ) , opts . SourceType , err )
2017-03-01 21:35:59 +01:00
}
// Sort the states so they're always copied alphabetically
2021-10-05 22:36:50 +02:00
sort . Strings ( sourceWorkspaces )
2017-03-01 21:35:59 +01:00
// Go through each and migrate
2021-10-05 22:36:50 +02:00
for _ , name := range sourceWorkspaces {
2017-03-01 21:35:59 +01:00
// Copy the same names
2021-10-05 22:36:50 +02:00
opts . sourceWorkspace = name
opts . destinationWorkspace = name
2017-03-01 21:35:59 +01:00
// 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 (
2021-10-05 22:36:50 +02:00
errMigrateMulti ) , name , opts . SourceType , opts . DestinationType , err )
2017-03-01 21:35:59 +01:00
}
}
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 {
2021-10-09 14:47:12 +02:00
log . Printf ( "[INFO] backendMigrateState: destination backend type %q does not support named workspaces" , opts . DestinationType )
2018-11-09 23:26:01 +01:00
2021-10-09 14:47:12 +02:00
currentWorkspace , err := m . Workspace ( )
2020-06-16 18:23:15 +02:00
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?" ,
2021-10-05 22:36:50 +02:00
opts . DestinationType ) ,
2017-03-21 20:05:51 +01:00
Description : fmt . Sprintf (
strings . TrimSpace ( inputBackendMigrateMultiToSingle ) ,
2021-10-09 14:47:12 +02:00
opts . SourceType , opts . DestinationType , currentWorkspace ) ,
2017-03-21 20:05:51 +01:00
} )
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
2021-10-09 14:47:12 +02:00
opts . sourceWorkspace = currentWorkspace
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 {
2021-10-09 14:47:12 +02:00
log . Printf ( "[INFO] backendMigrateState: single-to-single migrating %q workspace to %q workspace" , opts . sourceWorkspace , opts . destinationWorkspace )
2018-11-09 23:26:01 +01:00
2021-10-05 22:36:50 +02:00
sourceState , err := opts . Source . StateMgr ( opts . sourceWorkspace )
2017-03-01 19:59:17 +01:00
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateSingleLoadDefault ) , opts . SourceType , err )
2017-03-01 19:59:17 +01:00
}
2021-10-05 22:36:50 +02:00
if err := sourceState . RefreshState ( ) ; err != nil {
2017-03-01 19:59:17 +01:00
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateSingleLoadDefault ) , opts . SourceType , err )
2017-03-01 19:59:17 +01:00
}
2018-10-31 16:45:03 +01:00
// Do not migrate workspaces without state.
2021-10-05 22:36:50 +02:00
if sourceState . 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
}
2021-10-05 22:36:50 +02:00
destinationState , err := opts . Destination . StateMgr ( opts . destinationWorkspace )
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.
2021-10-05 22:36:50 +02:00
destinationState , err = func ( ) ( statemgr . Full , error ) {
log . Print ( "[TRACE] backendMigrateState: destination doesn't support a default workspace, so we must prompt for a new name" )
2021-10-09 14:47:12 +02:00
name , err := m . promptNewWorkspaceName ( opts . DestinationType )
2018-10-31 16:45:03 +01:00
if err != nil {
2021-10-09 14:47:12 +02:00
return nil , err
2018-10-31 16:45:03 +01:00
}
2021-10-05 22:36:50 +02:00
// Update the name of the destination state.
opts . destinationWorkspace = name
2018-10-31 16:45:03 +01:00
2021-10-05 22:36:50 +02:00
destinationState , err := opts . Destination . StateMgr ( opts . destinationWorkspace )
2018-10-31 16:45:03 +01:00
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 {
2021-10-05 22:36:50 +02:00
if err := m . SetWorkspace ( opts . destinationWorkspace ) ; err != nil {
2018-10-31 16:45:03 +01:00
return nil , fmt . Errorf ( "Failed to set new workspace: %s" , err )
}
}
2021-10-05 22:36:50 +02:00
return destinationState , nil
2018-10-31 16:45:03 +01:00
} ( )
}
2017-03-01 19:59:17 +01:00
if err != nil {
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateSingleLoadDefault ) , opts . DestinationType , err )
2017-03-01 19:59:17 +01:00
}
2021-10-05 22:36:50 +02:00
if err := destinationState . RefreshState ( ) ; err != nil {
2017-03-01 19:59:17 +01:00
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateSingleLoadDefault ) , opts . DestinationType , err )
2017-03-01 19:59:17 +01:00
}
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.
2021-10-05 22:36:50 +02:00
source := sourceState . State ( )
destination := destinationState . State ( )
2017-03-30 21:53:21 +02:00
// no reason to migrate if the state is already there
2021-10-05 22:36:50 +02:00
if source . Equal ( destination ) {
2017-03-30 21:53:21 +02:00
// Equal isn't identical; it doesn't check lineage.
2021-10-05 22:36:50 +02:00
sm1 , _ := sourceState . ( statemgr . PersistentMeta )
sm2 , _ := destinationState . ( statemgr . PersistentMeta )
if source != nil && destination != 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
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 )
2021-10-05 22:36:50 +02:00
lockerSource := locker . WithContext ( lockCtx )
if diags := lockerSource . Lock ( sourceState , "migration source state" ) ; diags . HasErrors ( ) {
2021-02-16 13:19:22 +01:00
return diags . Err ( )
2017-04-01 21:42:13 +02:00
}
2021-10-05 22:36:50 +02:00
defer lockerSource . Unlock ( )
2017-02-09 21:35:49 +01:00
2021-10-05 22:36:50 +02:00
lockerDestination := locker . WithContext ( lockCtx )
if diags := lockerDestination . Lock ( destinationState , "migration destination state" ) ; diags . HasErrors ( ) {
2021-02-16 13:19:22 +01:00
return diags . Err ( )
2017-04-01 21:42:13 +02:00
}
2021-10-05 22:36:50 +02:00
defer lockerDestination . 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" )
2021-10-05 22:36:50 +02:00
if err := sourceState . RefreshState ( ) ; err != nil {
2017-03-30 21:53:21 +02:00
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateSingleLoadDefault ) , opts . SourceType , err )
2017-03-30 21:53:21 +02:00
}
2021-10-05 22:36:50 +02:00
log . Print ( "[TRACE] backendMigrateState: refreshing destination workspace state" )
if err := destinationState . RefreshState ( ) ; err != nil {
2017-03-30 21:53:21 +02:00
return fmt . Errorf ( strings . TrimSpace (
2021-10-05 22:36:50 +02:00
errMigrateSingleLoadDefault ) , opts . SourceType , err )
2017-03-30 21:53:21 +02:00
}
2021-10-05 22:36:50 +02:00
source = sourceState . State ( )
destination = destinationState . State ( )
2017-03-30 21:53:21 +02:00
}
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
2021-10-05 22:36:50 +02:00
case source . Empty ( ) && destination . 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.
2021-10-05 22:36:50 +02:00
case source . Empty ( ) && ! destination . 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.
2021-10-05 22:36:50 +02:00
case ! source . Empty ( ) && destination . Empty ( ) :
log . Print ( "[TRACE] backendMigrateState: destination 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.
2021-10-05 22:36:50 +02:00
case ! source . Empty ( ) && ! destination . 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
2021-10-05 22:36:50 +02:00
confirm , err := confirmFunc ( sourceState , destinationState , opts )
2017-03-01 21:35:59 +01:00
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" )
2021-10-05 22:36:50 +02:00
if err := statemgr . Migrate ( destinationState , sourceState ) ; err != nil {
2017-01-19 05:50:04 +01:00
return fmt . Errorf ( strings . TrimSpace ( errBackendStateCopy ) ,
2021-10-05 22:36:50 +02:00
opts . SourceType , opts . DestinationType , err )
2017-01-19 05:50:04 +01:00
}
2021-10-05 22:36:50 +02:00
if err := destinationState . PersistState ( ) ; err != nil {
2017-01-19 05:50:04 +01:00
return fmt . Errorf ( strings . TrimSpace ( errBackendStateCopy ) ,
2021-10-05 22:36:50 +02:00
opts . SourceType , opts . DestinationType , err )
2017-01-19 05:50:04 +01:00
}
// And we're done.
return nil
}
2021-10-05 22:36:50 +02:00
func ( m * Meta ) backendMigrateEmptyConfirm ( source , destination 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 ) ,
2021-10-05 22:36:50 +02:00
opts . SourceType , opts . DestinationType ) ,
2017-01-19 05:50:04 +01:00
}
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 (
2021-10-05 22:36:50 +02:00
sourceState , destinationState 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
2021-10-05 22:36:50 +02:00
source := sourceState . State ( )
destination := destinationState . 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
2021-10-05 22:36:50 +02:00
sourcePath := filepath . Join ( td , fmt . Sprintf ( "1-%s.tfstate" , opts . SourceType ) )
destinationPath := filepath . Join ( td , fmt . Sprintf ( "2-%s.tfstate" , opts . DestinationType ) )
if err := saveHelper ( opts . SourceType , sourcePath , source ) ; err != nil {
2017-01-19 05:50:04 +01:00
return false , fmt . Errorf ( "Error saving temporary state: %s" , err )
}
2021-10-05 22:36:50 +02:00
if err := saveHelper ( opts . DestinationType , destinationPath , destination ) ; err != nil {
2017-01-19 05:50:04 +01:00
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 ) ,
2021-10-05 22:36:50 +02:00
opts . SourceType , opts . DestinationType , sourcePath , destinationPath ) ,
2017-01-19 05:50:04 +01:00
}
// 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
}
2021-09-22 23:53:33 +02:00
func retrieveWorkspaces ( back backend . Backend , sourceType string ) ( [ ] string , bool , error ) {
var singleState bool
var err error
workspaces , err := back . Workspaces ( )
if err == backend . ErrWorkspacesNotSupported {
singleState = true
err = nil
}
if err != nil {
return nil , singleState , fmt . Errorf ( strings . TrimSpace (
errMigrateLoadStates ) , sourceType , err )
}
return workspaces , singleState , err
}
func ( m * Meta ) backendMigrateTFC ( opts * backendMigrateOpts ) error {
_ , sourceTFC := opts . Source . ( * cloud . Cloud )
cloudBackendDestination , destinationTFC := opts . Destination . ( * cloud . Cloud )
sourceWorkspaces , sourceSingleState , err := retrieveWorkspaces ( opts . Source , opts . SourceType )
if err != nil {
return err
}
//to be used below, not yet implamented
// destinationWorkspaces, destinationSingleState
_ , _ , err = retrieveWorkspaces ( opts . Destination , opts . SourceType )
if err != nil {
return err
}
// from TFC to non-TFC backend
if sourceTFC && ! destinationTFC {
// From Terraform Cloud to another backend. This is not yet implemented, and
// we recommend people to use the TFC API.
return fmt . Errorf ( strings . TrimSpace ( errTFCMigrateNotYetImplemented ) )
}
// from TFC to TFC
if sourceTFC && destinationTFC {
// TODO: see internal/cloud/e2e/migrate_state_tfc_to_tfc_test.go for notes
panic ( "not yet implemented" )
}
// Everything below, by the above two conditionals, now assumes that the
// destination is always Terraform Cloud (TFC).
2021-10-09 14:47:12 +02:00
sourceSingle := sourceSingleState || ( len ( sourceWorkspaces ) == 1 )
2021-09-22 23:53:33 +02:00
if sourceSingle {
if cloudBackendDestination . WorkspaceMapping . Strategy ( ) == cloud . WorkspaceNameStrategy {
// If we know the name via WorkspaceNameStrategy, then set the
// destinationWorkspace to the new Name and skip the user prompt. Here the
// destinationWorkspace is not set to `default` thereby we will create it
// in TFC if it does not exist.
opts . destinationWorkspace = cloudBackendDestination . WorkspaceMapping . Name
}
2021-10-09 14:47:12 +02:00
currentWorkspace , err := m . Workspace ( )
if err != nil {
return err
}
opts . sourceWorkspace = currentWorkspace
log . Printf ( "[INFO] backendMigrateTFC: single-to-single migration from source %s to destination %q" , opts . sourceWorkspace , opts . destinationWorkspace )
2021-09-22 23:53:33 +02:00
// Run normal single-to-single state migration
// This will handle both situations where the new cloud backend
// configuration is using a workspace.name strategy or workspace.tags
// strategy.
return m . backendMigrateState_s_s ( opts )
}
destinationTagsStrategy := cloudBackendDestination . WorkspaceMapping . Strategy ( ) == cloud . WorkspaceTagsStrategy
destinationNameStrategy := cloudBackendDestination . WorkspaceMapping . Strategy ( ) == cloud . WorkspaceNameStrategy
multiSource := ! sourceSingleState && len ( sourceWorkspaces ) > 1
if multiSource && destinationNameStrategy {
2021-10-09 14:47:12 +02:00
if err := m . promptMultiToSingleCloudMigration ( opts ) ; err != nil {
return err
}
2021-10-09 14:47:12 +02:00
currentWorkspace , err := m . Workspace ( )
2021-10-09 14:47:12 +02:00
if err != nil {
return err
}
2021-10-09 14:47:12 +02:00
opts . sourceWorkspace = currentWorkspace
2021-10-09 14:47:12 +02:00
opts . destinationWorkspace = cloudBackendDestination . WorkspaceMapping . Name
2021-10-09 14:47:12 +02:00
log . Printf ( "[INFO] backendMigrateTFC: multi-to-single migration from source %s to destination %q" , opts . sourceWorkspace , opts . destinationWorkspace )
2021-10-09 14:47:12 +02:00
return m . backendMigrateState_s_s ( opts )
2021-09-22 23:53:33 +02:00
}
// Multiple sources, and using tags strategy. So migrate every source
// workspace over to new one, prompt for workspace name pattern (*),
// and start migrating, and create tags for each workspace.
if multiSource && destinationTagsStrategy {
2021-10-09 14:47:12 +02:00
log . Printf ( "[INFO] backendMigrateTFC: multi-to-multi migration from source workspaces %q" , sourceWorkspaces )
2021-10-09 14:47:12 +02:00
return m . backendMigrateState_S_TFC ( opts , sourceWorkspaces )
}
2021-10-09 14:47:12 +02:00
// TODO(omar): after the check for sourceSingle is done, everything following
// it has to be multi. So rework the code to not need to check for multi, adn
// return m.backendMigrateState_S_TFC here.
2021-10-09 14:47:12 +02:00
return nil
}
// migrates a multi-state backend to Terraform Cloud
func ( m * Meta ) backendMigrateState_S_TFC ( opts * backendMigrateOpts , sourceWorkspaces [ ] string ) error {
log . Print ( "[TRACE] backendMigrateState: migrating all named workspaces" )
// This map is used later when doing the migration per source/destination.
// If a source has 'default', then we ask what the new name should be.
// And further down when we actually run state migration for each
// sourc/destination workspce, we use this new name (where source is 'default')
// and set as destinationWorkspace.
defaultNewName := map [ string ] string { }
for i := 0 ; i < len ( sourceWorkspaces ) ; i ++ {
if sourceWorkspaces [ i ] == backend . DefaultStateName {
newName , err := m . promptNewWorkspaceName ( opts . DestinationType )
if err != nil {
return err
}
defaultNewName [ sourceWorkspaces [ i ] ] = newName
}
}
pattern , err := m . promptMultiStateMigrationPattern ( opts . SourceType )
if err != nil {
return err
}
// Go through each and migrate
for _ , name := range sourceWorkspaces {
// Copy the same names
opts . sourceWorkspace = name
if newName , ok := defaultNewName [ name ] ; ok {
// this has to be done before setting destinationWorkspace
name = newName
}
opts . destinationWorkspace = strings . Replace ( pattern , "*" , name , - 1 )
// Force it, we confirmed above
opts . force = true
// Perform the migration
2021-10-09 14:47:12 +02:00
log . Printf ( "[INFO] backendMigrateTFC: multi-to-multi migration, source workspace %q to destination workspace %q" , opts . sourceWorkspace , opts . destinationWorkspace )
2021-10-09 14:47:12 +02:00
if err := m . backendMigrateState_s_s ( opts ) ; err != nil {
return fmt . Errorf ( strings . TrimSpace (
errMigrateMulti ) , name , opts . SourceType , opts . DestinationType , err )
}
}
return nil
}
// Multi-state to single state.
func ( m * Meta ) promptMultiToSingleCloudMigration ( opts * backendMigrateOpts ) error {
migrate := opts . force
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 : "Do you want to copy only your current workspace?" ,
Description : strings . TrimSpace ( tfcInputBackendMigrateMultiToSingle ) ,
} )
if err != nil {
return fmt . Errorf ( "Error asking for state migration action: %s" , err )
}
}
if ! migrate {
return fmt . Errorf ( "Migration aborted by user." )
2021-09-22 23:53:33 +02:00
}
return nil
}
2021-10-09 14:47:12 +02:00
func ( m * Meta ) promptNewWorkspaceName ( destinationType string ) ( string , error ) {
name , err := m . UIInput ( ) . Input ( context . Background ( ) , & terraform . InputOpts {
Id : "new-state-name" ,
Query : fmt . Sprintf (
"[reset][bold][yellow]The %q backend configuration only allows " +
"named workspaces![reset]" ,
destinationType ) ,
Description : strings . TrimSpace ( inputBackendNewWorkspaceName ) ,
} )
if err != nil {
return "" , fmt . Errorf ( "Error asking for new state name: %s" , err )
}
return name , nil
}
func ( m * Meta ) promptMultiStateMigrationPattern ( sourceType string ) ( string , error ) {
renameWorkspaces , err := m . UIInput ( ) . Input ( context . Background ( ) , & terraform . InputOpts {
Id : "backend-migrate-multistate-to-tfc" ,
Query : fmt . Sprintf ( "[reset][bold][yellow]%s[reset]" , "Would you like to rename your workspaces?" ) ,
Description : fmt . Sprintf ( strings . TrimSpace ( tfcInputBackendMigrateMultiToMulti ) , sourceType ) ,
} )
if err != nil {
return "" , fmt . Errorf ( "Error asking for state migration action: %s" , err )
}
if renameWorkspaces != "2" && renameWorkspaces != "1" {
return "" , fmt . Errorf ( "Please select 1 or 2 as part of this option." )
}
if renameWorkspaces == "2" {
// this means they did not want to rename their workspaces, and we are
// returning a generic '*' that means use the same workspace name during
// migration.
return "*" , nil
}
pattern , err := m . UIInput ( ) . Input ( context . Background ( ) , & terraform . InputOpts {
Id : "backend-migrate-multistate-to-tfc-pattern" ,
Query : fmt . Sprintf ( "[reset][bold][yellow]%s[reset]" , "What pattern would you like to add to all your workspaces?" ) ,
Description : fmt . Sprintf ( strings . TrimSpace ( tfcInputBackendMigrateMultiToMultiPattern ) , sourceType ) ,
} )
if err != nil {
return "" , fmt . Errorf ( "Error asking for state migration action: %s" , err )
}
if ! strings . Contains ( pattern , "*" ) {
return "" , fmt . Errorf ( "The pattern must have an '*'" )
}
if count := strings . Count ( pattern , "*" ) ; count > 1 {
return "" , fmt . Errorf ( "The pattern '*' cannot be used more than once." )
}
return pattern , nil
}
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
`
2021-09-22 23:53:33 +02:00
const errTFCMigrateNotYetImplemented = `
Migrating state from Terraform Cloud to another backend is not yet implemented .
Please use the API to do this : https : //www.terraform.io/docs/cloud/api/state-versions.html
`
2021-10-09 14:47:12 +02:00
const tfcInputBackendMigrateMultiToMultiPattern = `
If you choose to NOT rename your workspaces , just input "*" .
The asterisk "*" represents your workspace name . Here are a few examples
if a workspace was named ' prod ' :
* input : ' app - * ' ; output : ' app - prod '
* input : ' * - app ' , output : ' prod - app '
* input : ' app - * - service ' , output : ' app - prod - service '
* input : '*' ; output : ' prod '
`
const tfcInputBackendMigrateMultiToMulti = `
When migrating existing workspaces from the backend % [ 1 ] q to Terraform Cloud , would you like to
rename your workspaces ?
Unlike typical Terraform workspaces representing an environment associated with a particular
configuration ( e . g . production , staging , development ) , Terraform Cloud workspaces are named uniquely
across all configurations used within an organization . A typical strategy to start with is
< COMPONENT > - < ENVIRONMENT > - < REGION > ( e . g . networking - prod - us - east , networking - staging - us - east ) .
For more information on workspace naming , see https : //www.terraform.io/docs/cloud/workspaces/naming.html
1. Yes , rename workspaces according to a pattern .
2. No , I would not like to rename my workspaces . Migrate them as currently named .
`
const tfcInputBackendMigrateMultiToSingle = `
The cloud configuration has one workspace declared , and you are attemtping to migrate multiple workspaces
to a single workspace . By continuing , you will only migrate your current workspace .
`
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
2021-10-05 22:36:50 +02:00
to the default workspace in the new backend . Your existing workspaces in the
2017-12-20 23:50:37 +01:00
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
`