github.com/muratcelep/terraform@v1.1.0-beta2-not-internal-4/not-internal/instances/expansion_mode.go (about) 1 package instances 2 3 import ( 4 "fmt" 5 "sort" 6 7 "github.com/zclconf/go-cty/cty" 8 9 "github.com/muratcelep/terraform/not-internal/addrs" 10 ) 11 12 // expansion is an not-internal interface used to represent the different 13 // ways expansion can operate depending on how repetition is configured for 14 // an object. 15 type expansion interface { 16 instanceKeys() []addrs.InstanceKey 17 repetitionData(addrs.InstanceKey) RepetitionData 18 } 19 20 // expansionSingle is the expansion corresponding to no repetition arguments 21 // at all, producing a single object with no key. 22 // 23 // expansionSingleVal is the only valid value of this type. 24 type expansionSingle uintptr 25 26 var singleKeys = []addrs.InstanceKey{addrs.NoKey} 27 var expansionSingleVal expansionSingle 28 29 func (e expansionSingle) instanceKeys() []addrs.InstanceKey { 30 return singleKeys 31 } 32 33 func (e expansionSingle) repetitionData(key addrs.InstanceKey) RepetitionData { 34 if key != addrs.NoKey { 35 panic("cannot use instance key with non-repeating object") 36 } 37 return RepetitionData{} 38 } 39 40 // expansionCount is the expansion corresponding to the "count" argument. 41 type expansionCount int 42 43 func (e expansionCount) instanceKeys() []addrs.InstanceKey { 44 ret := make([]addrs.InstanceKey, int(e)) 45 for i := range ret { 46 ret[i] = addrs.IntKey(i) 47 } 48 return ret 49 } 50 51 func (e expansionCount) repetitionData(key addrs.InstanceKey) RepetitionData { 52 i := int(key.(addrs.IntKey)) 53 if i < 0 || i >= int(e) { 54 panic(fmt.Sprintf("instance key %d out of range for count %d", i, e)) 55 } 56 return RepetitionData{ 57 CountIndex: cty.NumberIntVal(int64(i)), 58 } 59 } 60 61 // expansionForEach is the expansion corresponding to the "for_each" argument. 62 type expansionForEach map[string]cty.Value 63 64 func (e expansionForEach) instanceKeys() []addrs.InstanceKey { 65 ret := make([]addrs.InstanceKey, 0, len(e)) 66 for k := range e { 67 ret = append(ret, addrs.StringKey(k)) 68 } 69 sort.Slice(ret, func(i, j int) bool { 70 return ret[i].(addrs.StringKey) < ret[j].(addrs.StringKey) 71 }) 72 return ret 73 } 74 75 func (e expansionForEach) repetitionData(key addrs.InstanceKey) RepetitionData { 76 k := string(key.(addrs.StringKey)) 77 v, ok := e[k] 78 if !ok { 79 panic(fmt.Sprintf("instance key %q does not match any instance", k)) 80 } 81 return RepetitionData{ 82 EachKey: cty.StringVal(k), 83 EachValue: v, 84 } 85 }