github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/backend/local/hook_count.go (about) 1 package local 2 3 import ( 4 "strings" 5 "sync" 6 7 "github.com/hashicorp/terraform/terraform" 8 ) 9 10 // CountHook is a hook that counts the number of resources 11 // added, removed, changed during the course of an apply. 12 type CountHook struct { 13 Added int 14 Changed int 15 Removed int 16 17 ToAdd int 18 ToChange int 19 ToRemove int 20 ToRemoveAndAdd int 21 22 pending map[string]countHookAction 23 24 sync.Mutex 25 terraform.NilHook 26 } 27 28 func (h *CountHook) Reset() { 29 h.Lock() 30 defer h.Unlock() 31 32 h.pending = nil 33 h.Added = 0 34 h.Changed = 0 35 h.Removed = 0 36 } 37 38 func (h *CountHook) PreApply( 39 n *terraform.InstanceInfo, 40 s *terraform.InstanceState, 41 d *terraform.InstanceDiff) (terraform.HookAction, error) { 42 h.Lock() 43 defer h.Unlock() 44 45 if h.pending == nil { 46 h.pending = make(map[string]countHookAction) 47 } 48 49 action := countHookActionChange 50 if d.GetDestroy() { 51 action = countHookActionRemove 52 } else if s.ID == "" { 53 action = countHookActionAdd 54 } 55 56 h.pending[n.HumanId()] = action 57 58 return terraform.HookActionContinue, nil 59 } 60 61 func (h *CountHook) PostApply( 62 n *terraform.InstanceInfo, 63 s *terraform.InstanceState, 64 e error) (terraform.HookAction, error) { 65 h.Lock() 66 defer h.Unlock() 67 68 if h.pending != nil { 69 if a, ok := h.pending[n.HumanId()]; ok { 70 delete(h.pending, n.HumanId()) 71 72 if e == nil { 73 switch a { 74 case countHookActionAdd: 75 h.Added += 1 76 case countHookActionChange: 77 h.Changed += 1 78 case countHookActionRemove: 79 h.Removed += 1 80 } 81 } 82 } 83 } 84 85 return terraform.HookActionContinue, nil 86 } 87 88 func (h *CountHook) PostDiff( 89 n *terraform.InstanceInfo, d *terraform.InstanceDiff) ( 90 terraform.HookAction, error) { 91 h.Lock() 92 defer h.Unlock() 93 94 // We don't count anything for data sources 95 if strings.HasPrefix(n.Id, "data.") { 96 return terraform.HookActionContinue, nil 97 } 98 99 switch d.ChangeType() { 100 case terraform.DiffDestroyCreate: 101 h.ToRemoveAndAdd += 1 102 case terraform.DiffCreate: 103 h.ToAdd += 1 104 case terraform.DiffDestroy: 105 h.ToRemove += 1 106 case terraform.DiffUpdate: 107 h.ToChange += 1 108 } 109 110 return terraform.HookActionContinue, nil 111 }