-
Notifications
You must be signed in to change notification settings - Fork 8
/
planner.go
90 lines (81 loc) · 2.3 KB
/
planner.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
package main
import (
"bytes"
"encoding/json"
"os"
"os/exec"
"reflect"
"regexp"
"strings"
)
func changes(cfg config, planArgs []string) ([]ResChange, error) {
tfPlan, err := os.CreateTemp("", "tfplan")
if err != nil {
return nil, err
}
tfPlanName := tfPlan.Name()
defer os.Remove(tfPlanName)
if err := terraformExec(cfg, true, planArgs, "plan", "-out="+tfPlanName); err != nil {
return nil, err
}
isPre012, err := isPre012()
if err != nil {
return nil, err
}
if isPre012 {
cmd := exec.Command("terraform", "show", "-no-color", tfPlanName)
var stdout bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return nil, err
}
stdoutBytes := stdout.Bytes()
var changes []ResChange
for _, res := range regexp.MustCompile(`(?m)\+ (.*)$`).FindAllSubmatch(stdoutBytes, -1) {
address := string(res[1])
parts := strings.Split(address, ".")
changes = append(changes, ResChange{address, parts[len(parts)-2], Change{[]changeAction{create}}})
}
for _, res := range regexp.MustCompile(`(?m)- (.*)$`).FindAllSubmatch(stdoutBytes, -1) {
address := string(res[1])
parts := strings.Split(address, ".")
changes = append(changes, ResChange{address, parts[len(parts)-2], Change{[]changeAction{del}}})
}
return changes, nil
}
cmd := exec.Command("terraform", "show", "-json", tfPlanName)
var stdout bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
return nil, err
}
changes := resChanges{}
if err := json.Unmarshal(stdout.Bytes(), &changes); err != nil {
return nil, err
}
return changes.ResChanges, nil
}
func filterByAction(resources []ResChange, action changeAction) map[Resource]bool {
set := make(map[Resource]bool)
for _, res := range resources {
if reflect.DeepEqual(res.Change.Actions, []changeAction{action}) {
set[Resource{res.Address, res.Type}] = true
}
}
return set
}
func filterByDestinationResourceTypes(sourceResources map[Resource]bool, destResources map[Resource]bool) map[Resource]bool {
set := make(map[Resource]bool)
types := make(map[string]bool)
for res := range destResources {
types[res.Type] = true
}
for res := range sourceResources {
if types[res.Type] || res.Address == FinishedAddress {
set[Resource{res.Address, res.Type}] = true
}
}
return set
}