Skip to content

Commit

Permalink
refactor: calculate drift based on json output instead of human-readable
Browse files Browse the repository at this point in the history
  • Loading branch information
rootsami committed Jan 27, 2023
1 parent dd36605 commit f196f7a
Showing 1 changed file with 21 additions and 30 deletions.
51 changes: 21 additions & 30 deletions pkg/tfstack/stacks.go → pkg/tfstack/tfstack.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ import (
"errors"
"fmt"
"os"
"regexp"
"strconv"

"github.com/rootsami/terradrift/pkg/config"
log "github.com/sirupsen/logrus"

"github.com/hashicorp/terraform-exec/tfexec"
tfjson "github.com/hashicorp/terraform-json"
)

type DriftSum struct {
Expand Down Expand Up @@ -143,7 +142,7 @@ func showPlan(plan bool, planFile string, name string, tf *tfexec.Terraform) (*D

if plan {

state, err := tf.ShowPlanFileRaw(context.Background(), planFile)
state, err := tf.ShowPlanFile(context.Background(), planFile)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -182,37 +181,29 @@ func stackExists(name string, stacks []config.Stack) (stack config.Stack, result
}

// driftCalculator returns a detailed number of changes that was detected in the plan
func driftCalculator(state string) (*DriftSum, error) {

re := regexp.MustCompile("Plan:[^0-9]*(?P<add>[0-9])[^0-9]*(?P<change>[0-9])[^0-9]*(?P<destroy>[0-9])")
matches := re.FindStringSubmatch(state)

addIndex := re.SubexpIndex("add")
add, err := strconv.Atoi(matches[addIndex])
if err != nil {
return nil, err
}

changeIndex := re.SubexpIndex("change")
change, err := strconv.Atoi(matches[changeIndex])
if err != nil {
return nil, err
}

destroyIndex := re.SubexpIndex("destroy")
destroy, err := strconv.Atoi(matches[destroyIndex])
if err != nil {
return nil, err
func driftCalculator(state *tfjson.Plan) (*DriftSum, error) {

var driftSum *DriftSum
for _, resource := range state.ResourceChanges {

for _, action := range resource.Change.Actions {
switch action {
case "create":
driftSum.Add++
case "update":
driftSum.Change++
case "delete":
driftSum.Destroy++
}
}
}

DriftSum := &DriftSum{
Drift: true,
Add: add,
Change: change,
Destroy: destroy,
// if any of the above counters is greater than 0, then drift is detected
if driftSum.Add > 0 || driftSum.Change > 0 || driftSum.Destroy > 0 {
driftSum.Drift = true
}

return DriftSum, err
return driftSum, nil
}

// cleanUpPlanFile removes the plan file after the plan has been reported
Expand Down

0 comments on commit f196f7a

Please sign in to comment.