github.com/paybyphone/terraform@v0.9.5-0.20170613192930-9706042ddd51/terraform/transform_attach_state.go (about)

     1  package terraform
     2  
     3  import (
     4  	"log"
     5  
     6  	"github.com/hashicorp/terraform/dag"
     7  )
     8  
     9  // GraphNodeAttachResourceState is an interface that can be implemented
    10  // to request that a ResourceState is attached to the node.
    11  type GraphNodeAttachResourceState interface {
    12  	// The address to the resource for the state
    13  	ResourceAddr() *ResourceAddress
    14  
    15  	// Sets the state
    16  	AttachResourceState(*ResourceState)
    17  }
    18  
    19  // AttachStateTransformer goes through the graph and attaches
    20  // state to nodes that implement the interfaces above.
    21  type AttachStateTransformer struct {
    22  	State *State // State is the root state
    23  }
    24  
    25  func (t *AttachStateTransformer) Transform(g *Graph) error {
    26  	// If no state, then nothing to do
    27  	if t.State == nil {
    28  		log.Printf("[DEBUG] Not attaching any state: state is nil")
    29  		return nil
    30  	}
    31  
    32  	filter := &StateFilter{State: t.State}
    33  	for _, v := range g.Vertices() {
    34  		// Only care about nodes requesting we're adding state
    35  		an, ok := v.(GraphNodeAttachResourceState)
    36  		if !ok {
    37  			continue
    38  		}
    39  		addr := an.ResourceAddr()
    40  
    41  		// Get the module state
    42  		results, err := filter.Filter(addr.String())
    43  		if err != nil {
    44  			return err
    45  		}
    46  
    47  		// Attach the first resource state we get
    48  		found := false
    49  		for _, result := range results {
    50  			if rs, ok := result.Value.(*ResourceState); ok {
    51  				log.Printf(
    52  					"[DEBUG] Attaching resource state to %q: %#v",
    53  					dag.VertexName(v), rs)
    54  				an.AttachResourceState(rs)
    55  				found = true
    56  				break
    57  			}
    58  		}
    59  
    60  		if !found {
    61  			log.Printf(
    62  				"[DEBUG] Resource state not found for %q: %s",
    63  				dag.VertexName(v), addr)
    64  		}
    65  	}
    66  
    67  	return nil
    68  }