diff --git a/internal/refactoring/move_statement.go b/internal/refactoring/move_statement.go index 113c8ae1dc..eec12bffc4 100644 --- a/internal/refactoring/move_statement.go +++ b/internal/refactoring/move_statement.go @@ -64,27 +64,29 @@ func findMoveStatements(cfg *configs.Config, into []MoveStatement) []MoveStateme // We have the statement, let's see if we should attach a provider to // it. - if toResource, ok := mc.To.ConfigMoveable(addrs.RootModule).(addrs.ConfigResource); ok { // Only attach providers if we are moving resources, and we attach // the to resource provider from the config. We can retrieve the // from resource provider from the state later. + modCfg := cfg.Descendent(toResource.Module) + // It's possible that multiple refactorings have left a moved block + // that points to a module which no longer exists. This may also be + // a mistake, but the user will see the unexpected deletion in the + // plan if it is. + if modCfg != nil { + resourceConfig := modCfg.Module.ResourceByAddr(toResource.Resource) + if resourceConfig != nil { + // Check the target resource config actually exists before we + // try and extract the provider from them. + + stmt.Provider = &addrs.AbsProviderConfig{ + Module: modAddr, + Provider: resourceConfig.Provider, + } - resourceConfig := cfg.Descendent(toResource.Module).Module.ResourceByAddr(toResource.Resource) - if resourceConfig != nil { - - // Check the target resource config actually exists before we - // try and extract the provider from them. If the resource - // doesn't exist in config, then we'll get a validation error - // later on anyway. - - stmt.Provider = &addrs.AbsProviderConfig{ - Module: modAddr, - Provider: resourceConfig.Provider, - } - - if resourceConfig.ProviderConfigRef != nil { - stmt.Provider.Alias = resourceConfig.ProviderConfigRef.Alias + if resourceConfig.ProviderConfigRef != nil { + stmt.Provider.Alias = resourceConfig.ProviderConfigRef.Alias + } } } } diff --git a/internal/refactoring/testdata/move-statement-implied/move-statement-implied.tf b/internal/refactoring/testdata/move-statement-implied/move-statement-implied.tf index 4ea628ea65..b8ea759a22 100644 --- a/internal/refactoring/testdata/move-statement-implied/move-statement-implied.tf +++ b/internal/refactoring/testdata/move-statement-implied/move-statement-implied.tf @@ -52,3 +52,8 @@ resource "foo" "ambiguous" { module "child" { source = "./child" } + +moved { + from = foo.already_moved + to = module.no_longer_exists.foo.already_moved +}