github.com/skyscape-cloud-services/terraform@v0.9.2-0.20170609144644-7ece028a1747/terraform/transform_resource_count.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/hashicorp/terraform/dag"
     7  )
     8  
     9  // ResourceCountTransformer is a GraphTransformer that expands the count
    10  // out for a specific resource.
    11  //
    12  // This assumes that the count is already interpolated.
    13  type ResourceCountTransformer struct {
    14  	Concrete ConcreteResourceNodeFunc
    15  
    16  	Count int
    17  	Addr  *ResourceAddress
    18  }
    19  
    20  func (t *ResourceCountTransformer) Transform(g *Graph) error {
    21  	// Don't allow the count to be negative
    22  	if t.Count < 0 {
    23  		return fmt.Errorf("negative count: %d", t.Count)
    24  	}
    25  
    26  	// For each count, build and add the node
    27  	for i := 0; i < t.Count; i++ {
    28  		// Set the index. If our count is 1 we special case it so that
    29  		// we handle the "resource.0" and "resource" boundary properly.
    30  		index := i
    31  		if t.Count == 1 {
    32  			index = -1
    33  		}
    34  
    35  		// Build the resource address
    36  		addr := t.Addr.Copy()
    37  		addr.Index = index
    38  
    39  		// Build the abstract node and the concrete one
    40  		abstract := &NodeAbstractResource{Addr: addr}
    41  		var node dag.Vertex = abstract
    42  		if f := t.Concrete; f != nil {
    43  			node = f(abstract)
    44  		}
    45  
    46  		// Add it to the graph
    47  		g.Add(node)
    48  	}
    49  
    50  	return nil
    51  }