/
destroy_infra.go
180 lines (157 loc) · 4.62 KB
/
destroy_infra.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package command
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strings"
"time"
"github.com/TimeIncOSS/ape-dev-rt/aws"
"github.com/TimeIncOSS/ape-dev-rt/clippy"
"github.com/TimeIncOSS/ape-dev-rt/commons"
"github.com/TimeIncOSS/ape-dev-rt/deploymentstate"
"github.com/TimeIncOSS/ape-dev-rt/hcl"
"github.com/TimeIncOSS/ape-dev-rt/terraform"
)
func DestroyInfra(c *commons.Context) error {
user, ok := c.CliContext.App.Metadata["user"].(*aws.User)
if !ok {
return fmt.Errorf("Unable to find AWS User in metadata")
}
ds, ok := c.CliContext.App.Metadata["ds"].(*deploymentstate.DeploymentState)
if !ok {
return fmt.Errorf("Unable to find Deployment State in metadata")
}
rs, ok := c.CliContext.App.Metadata["remote_state"].(*hcl.RemoteState)
if !ok {
return fmt.Errorf("Unable to find Remote State in metadata")
}
cfgPath, err := os.Getwd()
if err != nil {
return err
}
appData, exists, err := BeginApplicationOperation(c.String("env"), c.String("app"), ds)
if err != nil {
return err
}
if !exists {
return nil
}
if appData.UseCentralGitRepo {
return deprecatedGitError()
}
slotData, err := ds.ListSlots(c.String("app"))
if err != nil {
return err
}
activeSlots := make([]string, 0)
for _, slot := range slotData {
if slot.IsActive {
activeSlots = append(activeSlots, slot.SlotId)
}
}
if len(activeSlots) > 0 {
return fmt.Errorf(
"Bailing out of destroy-infra...\n"+
"Cannot destroy app %s in env %s while slots are active. "+
"Please use deploy-destroy on active slots:\n%v",
c.String("app"), c.String("env"), activeSlots)
}
namespace := user.AccountID
if c.String("namespace") != "default" {
namespace = c.String("namespace")
}
rootDir := cfgPath
filesToCleanup := make([]string, 0)
templateVars := ApplicationTemplateVars{
AwsAccountId: namespace,
Environment: c.String("env"),
}
filesToCleanup, err = commons.ProcessTemplates(rootDir, "tpl", templateVars)
if err != nil {
return err
}
remoteState, err := terraform.GetRemoteStateForApp(&terraform.RemoteState{
Backend: rs.Backend,
Config: rs.Config,
}, namespace, c.String("app"))
if err != nil {
return err
}
vars := c.StringSlice("var")
tfVariables := make(map[string]string, 0)
for _, v := range vars {
parts := strings.Split(v, "=")
key, value := parts[0], parts[1]
tfVariables[key] = value
}
tfVariables["app_name"] = c.String("app")
tfVariables["environment"] = c.String("env")
planStartTime := time.Now().UTC()
filesToCleanup = append(filesToCleanup, path.Join(rootDir, ".terraform"))
filesToCleanup = append(filesToCleanup, path.Join(rootDir, "terraform.tfstate.backup"))
planOut, err := terraform.FreshPlan(&terraform.FreshPlanInput{
RemoteState: remoteState,
RootPath: rootDir,
Variables: tfVariables,
Refresh: true,
Target: c.String("target"),
Destroy: true,
XLegacy: c.Bool("x"),
})
filesToCleanup = append(filesToCleanup, terraform.GetBackendConfigFilename(rootDir))
planFinishTime := time.Now().UTC()
if err != nil {
return err
}
log.Printf("[DEBUG] Plan started %s, finished %s",
planStartTime.String(), planFinishTime.String())
if planOut.ExitCode != 0 {
return fmt.Errorf("Planning failed (exit code %d). Stderr:\n%v", planOut.ExitCode, planOut.Stderr)
}
diff := planOut.Diff
if diff.ToChange+diff.ToCreate+diff.ToRemove == 0 && !c.Bool("f") {
return cleanupFilePaths(filesToCleanup)
}
note := fmt.Sprintf(
"It looks like you want to DESTROY INFRASTRUCTURE of '%s' (%s/%s).",
c.String("app"), namespace, c.String("env"))
yesOverride := c.Bool("y")
isSensitive := isEnvironmentSensitive(c.String("env"))
destroyOut, confirmed, err := clippy.BoolPrompt(note, yesOverride, isSensitive, func() (interface{}, error) {
input := terraform.DestroyInput{
RootPath: rootDir,
Target: "",
XLegacy: c.Bool("x"),
Variables: tfVariables,
Refresh: true,
StderrWriter: ioutil.Discard,
}
return terraform.Destroy(&input)
}, nil)
if !confirmed {
log.Printf("[DEBUG] User didn't confirm clippy dialog - not destroying infra.")
return cleanupFilePaths(filesToCleanup)
}
if err != nil {
return fmt.Errorf("Destroy operation failed: %s", err)
}
isActive := true
isStateEmpty, err := terraform.IsStateEmpty(rootDir)
if err != nil {
return err
}
isActive = !isStateEmpty
appData.LastInfraChangeTime = time.Now().UTC()
err = FinishApplicationOperation(c.String("app"), appData, isActive, nil, ds)
if err != nil {
return err
}
do := destroyOut.(*terraform.DestroyOutput)
if do.ExitCode != 0 {
return fmt.Errorf("Destroy operation failed (exit code %d). Stderr:\n%s",
do.ExitCode, do.Stderr)
}
return nil
}