github.com/opentofu/opentofu@v1.7.1/internal/tofu/transform_removed_modules.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package tofu
     7  
     8  import (
     9  	"log"
    10  
    11  	"github.com/opentofu/opentofu/internal/addrs"
    12  	"github.com/opentofu/opentofu/internal/configs"
    13  	"github.com/opentofu/opentofu/internal/states"
    14  )
    15  
    16  // RemovedModuleTransformer implements GraphTransformer to add nodes indicating
    17  // when a module was removed from the configuration.
    18  type RemovedModuleTransformer struct {
    19  	Config *configs.Config // root node in the config tree
    20  	State  *states.State
    21  }
    22  
    23  func (t *RemovedModuleTransformer) Transform(g *Graph) error {
    24  	// nothing to remove if there's no state!
    25  	if t.State == nil {
    26  		return nil
    27  	}
    28  
    29  	removed := map[string]addrs.Module{}
    30  
    31  	for _, m := range t.State.Modules {
    32  		cc := t.Config.DescendentForInstance(m.Addr)
    33  		if cc != nil {
    34  			continue
    35  		}
    36  		removed[m.Addr.Module().String()] = m.Addr.Module()
    37  		log.Printf("[DEBUG] %s is no longer in configuration\n", m.Addr)
    38  	}
    39  
    40  	// add closers to collect any module instances we're removing
    41  	for _, modAddr := range removed {
    42  		closer := &nodeCloseModule{
    43  			Addr: modAddr,
    44  		}
    45  		g.Add(closer)
    46  	}
    47  
    48  	return nil
    49  }