kubeform.dev/terraform-backend-sdk@v0.0.0-20220310143633-45f07fe731c5/terraform/transform_orphan_count.go (about) 1 package terraform 2 3 import ( 4 "log" 5 6 "kubeform.dev/terraform-backend-sdk/addrs" 7 "kubeform.dev/terraform-backend-sdk/dag" 8 "kubeform.dev/terraform-backend-sdk/states" 9 ) 10 11 // OrphanResourceInstanceCountTransformer is a GraphTransformer that adds orphans 12 // for an expanded count to the graph. The determination of this depends 13 // on the count argument given. 14 // 15 // Orphans are found by comparing the count to what is found in the state. 16 // This transform assumes that if an element in the state is within the count 17 // bounds given, that it is not an orphan. 18 type OrphanResourceInstanceCountTransformer struct { 19 Concrete ConcreteResourceInstanceNodeFunc 20 21 Addr addrs.AbsResource // Addr of the resource to look for orphans 22 InstanceAddrs []addrs.AbsResourceInstance // Addresses that currently exist in config 23 State *states.State // Full global state 24 } 25 26 func (t *OrphanResourceInstanceCountTransformer) Transform(g *Graph) error { 27 rs := t.State.Resource(t.Addr) 28 if rs == nil { 29 return nil // Resource doesn't exist in state, so nothing to do! 30 } 31 32 // This is an O(n*m) analysis, which we accept for now because the 33 // number of instances of a single resource ought to always be small in any 34 // reasonable Terraform configuration. 35 Have: 36 for key := range rs.Instances { 37 thisAddr := rs.Addr.Instance(key) 38 for _, wantAddr := range t.InstanceAddrs { 39 if wantAddr.Equal(thisAddr) { 40 continue Have 41 } 42 } 43 // If thisAddr is not in t.InstanceAddrs then we've found an "orphan" 44 45 abstract := NewNodeAbstractResourceInstance(thisAddr) 46 var node dag.Vertex = abstract 47 if f := t.Concrete; f != nil { 48 node = f(abstract) 49 } 50 log.Printf("[TRACE] OrphanResourceInstanceCountTransformer: adding %s as %T", thisAddr, node) 51 g.Add(node) 52 } 53 54 return nil 55 }