forked from chanzuckerberg/fogg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
113 lines (98 loc) · 2.42 KB
/
migrate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package migrate
import (
"fmt"
"math"
"os"
"os/exec"
"strings"
"github.com/antzucaro/matchr"
"github.com/aws/aws-sdk-go/aws"
"github.com/hashicorp/terraform/terraform"
"github.com/pkg/errors"
"github.com/segmentio/go-prompt"
log "github.com/sirupsen/logrus"
)
func generatePlan(planPath string) error {
cmd := exec.Command("make", "init")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err := cmd.Run()
if err != nil {
errors.Wrap(err, "Could not run make init")
}
cmd = exec.Command("make", "run")
cmd.Env = append(cmd.Env, fmt.Sprintf("plan -out %s", planPath))
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err = cmd.Run()
return errors.Wrap(err, "Could not run terraform plan")
}
// parsePlan
func parsePlan(planPath string) error {
f, err := os.Open(planPath)
if err != nil {
return errors.Wrapf(err, "Could not read plan at %s", planPath)
}
defer f.Close()
// TODO: also remove the plan?
plan, err := terraform.ReadPlan(f)
if err != nil {
return errors.Wrapf(err, "Terraform could not parse plan at %s", planPath)
}
if plan.Diff == nil {
log.Debug("nil diff")
return nil
}
deletions := map[string]bool{}
additions := map[string]bool{}
for _, module := range plan.Diff.Modules {
moduleName := strings.TrimPrefix(strings.Join(module.Path, "."), "root.")
for name, instance := range module.Resources {
fullName := fmt.Sprintf("%s.%s", moduleName, name)
if instance.Destroy {
deletions[fullName] = true
} else {
additions[fullName] = true
}
}
}
for addition := range additions {
currScore := math.MaxInt64
var replace *string
for deletion, ok := range deletions {
if !ok {
continue
}
score := matchr.DamerauLevenshtein(addition, deletion)
if score < currScore {
currScore = score
replace = aws.String(deletion)
}
}
if replace == nil {
continue
}
if !prompt.Confirm("Would you like us to move %s to %s", *replace, addition) {
continue
}
deletions[*replace] = false
cmd := exec.Command("make", "run")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Env = append(cmd.Env, fmt.Sprintf("CMD=state mv %s %s", *replace, addition))
err = cmd.Run()
if err != nil {
return errors.Wrapf(err, "Could not move %s to %s", *replace, addition)
}
}
return nil
}
// Migrate migrates
func Migrate(planPath string) error {
defer os.Remove(planPath)
err := generatePlan(planPath)
if err != nil {
return err
}
return parsePlan(planPath)
}