From 4f1ba8f23573f4c024fdc338a6ef0794d5a96ce1 Mon Sep 17 00:00:00 2001 From: James Bardin Date: Fri, 12 Apr 2024 15:12:48 -0400 Subject: [PATCH] check move target module exists We already check if a move target resource still exists, but it's possible the entire module no longer exists. --- internal/refactoring/move_statement.go | 34 ++++++++++--------- .../move-statement-implied.tf | 5 +++ 2 files changed, 23 insertions(+), 16 deletions(-) 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 +}