github.com/hashicorp/terraform-plugin-sdk@v1.17.2/terraform/transform_resource_count.go (about) 1 package terraform 2 3 import ( 4 "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" 5 "github.com/hashicorp/terraform-plugin-sdk/internal/configs/configschema" 6 "github.com/hashicorp/terraform-plugin-sdk/internal/dag" 7 "github.com/zclconf/go-cty/cty" 8 ) 9 10 // ResourceCountTransformer is a GraphTransformer that expands the count 11 // out for a specific resource. 12 // 13 // This assumes that the count is already interpolated. 14 type ResourceCountTransformer struct { 15 Concrete ConcreteResourceInstanceNodeFunc 16 Schema *configschema.Block 17 18 // Count is either the number of indexed instances to create, or -1 to 19 // indicate that count is not set at all and thus a no-key instance should 20 // be created. 21 Count int 22 ForEach map[string]cty.Value 23 Addr addrs.AbsResource 24 } 25 26 func (t *ResourceCountTransformer) Transform(g *Graph) error { 27 if t.Count < 0 && t.ForEach == nil { 28 // Negative count indicates that count is not set at all. 29 addr := t.Addr.Instance(addrs.NoKey) 30 31 abstract := NewNodeAbstractResourceInstance(addr) 32 abstract.Schema = t.Schema 33 var node dag.Vertex = abstract 34 if f := t.Concrete; f != nil { 35 node = f(abstract) 36 } 37 38 g.Add(node) 39 return nil 40 } 41 42 // Add nodes related to the for_each expression 43 for key := range t.ForEach { 44 addr := t.Addr.Instance(addrs.StringKey(key)) 45 abstract := NewNodeAbstractResourceInstance(addr) 46 abstract.Schema = t.Schema 47 var node dag.Vertex = abstract 48 if f := t.Concrete; f != nil { 49 node = f(abstract) 50 } 51 52 g.Add(node) 53 } 54 55 // For each count, build and add the node 56 for i := 0; i < t.Count; i++ { 57 key := addrs.IntKey(i) 58 addr := t.Addr.Instance(key) 59 60 abstract := NewNodeAbstractResourceInstance(addr) 61 abstract.Schema = t.Schema 62 var node dag.Vertex = abstract 63 if f := t.Concrete; f != nil { 64 node = f(abstract) 65 } 66 67 g.Add(node) 68 } 69 70 return nil 71 }