-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
workspace_delete.go
229 lines (191 loc) · 6.08 KB
/
workspace_delete.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package command
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform/internal/command/arguments"
"github.com/hashicorp/terraform/internal/command/clistate"
"github.com/hashicorp/terraform/internal/command/views"
"github.com/hashicorp/terraform/internal/states"
"github.com/hashicorp/terraform/internal/tfdiags"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
type WorkspaceDeleteCommand struct {
Meta
LegacyName bool
}
func (c *WorkspaceDeleteCommand) Run(args []string) int {
args = c.Meta.process(args)
envCommandShowWarning(c.Ui, c.LegacyName)
var force bool
var stateLock bool
var stateLockTimeout time.Duration
cmdFlags := c.Meta.defaultFlagSet("workspace delete")
cmdFlags.BoolVar(&force, "force", false, "force removal of a non-empty workspace")
cmdFlags.BoolVar(&stateLock, "lock", true, "lock state")
cmdFlags.DurationVar(&stateLockTimeout, "lock-timeout", 0, "lock timeout")
cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
return 1
}
args = cmdFlags.Args()
if len(args) != 1 {
c.Ui.Error("Expected a single argument: NAME.\n")
return cli.RunResultHelp
}
configPath, err := ModulePath(args[1:])
if err != nil {
c.Ui.Error(err.Error())
return 1
}
var diags tfdiags.Diagnostics
backendConfig, backendDiags := c.loadBackendConfig(configPath)
diags = diags.Append(backendDiags)
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// Load the backend
b, backendDiags := c.Backend(&BackendOpts{
Config: backendConfig,
})
diags = diags.Append(backendDiags)
if backendDiags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
// This command will not write state
c.ignoreRemoteVersionConflict(b)
workspaces, err := b.Workspaces()
if err != nil {
c.Ui.Error(err.Error())
return 1
}
workspace := args[0]
exists := false
for _, ws := range workspaces {
if workspace == ws {
exists = true
break
}
}
if !exists {
c.Ui.Error(fmt.Sprintf(strings.TrimSpace(envDoesNotExist), workspace))
return 1
}
currentWorkspace, err := c.Workspace()
if err != nil {
c.Ui.Error(fmt.Sprintf("Error selecting workspace: %s", err))
return 1
}
if workspace == currentWorkspace {
c.Ui.Error(fmt.Sprintf(strings.TrimSpace(envDelCurrent), workspace))
return 1
}
// we need the actual state to see if it's empty
stateMgr, err := b.StateMgr(workspace)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
var stateLocker clistate.Locker
if stateLock {
stateLocker = clistate.NewLocker(c.stateLockTimeout, views.NewStateLocker(arguments.ViewHuman, c.View))
if diags := stateLocker.Lock(stateMgr, "state-replace-provider"); diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
} else {
stateLocker = clistate.NewNoopLocker()
}
if err := stateMgr.RefreshState(); err != nil {
// We need to release the lock before exit
stateLocker.Unlock()
c.Ui.Error(err.Error())
return 1
}
hasResources := stateMgr.State().HasManagedResourceInstanceObjects()
if hasResources && !force {
// We'll collect a list of what's being managed here as extra context
// for the message.
var buf strings.Builder
for _, obj := range stateMgr.State().AllResourceInstanceObjectAddrs() {
if obj.DeposedKey == states.NotDeposed {
fmt.Fprintf(&buf, "\n - %s", obj.Instance.String())
} else {
fmt.Fprintf(&buf, "\n - %s (deposed object %s)", obj.Instance.String(), obj.DeposedKey)
}
}
// We need to release the lock before exit
stateLocker.Unlock()
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Workspace is not empty",
fmt.Sprintf(
"Workspace %q is currently tracking the following resource instances:%s\n\nDeleting this workspace would cause Terraform to lose track of any associated remote objects, which would then require you to delete them manually outside of Terraform. You should destroy these objects with Terraform before deleting the workspace.\n\nIf you want to delete this workspace anyway, and have Terraform forget about these managed objects, use the -force option to disable this safety check.",
workspace, buf.String(),
),
))
c.showDiagnostics(diags)
return 1
}
// We need to release the lock just before deleting the state, in case
// the backend can't remove the resource while holding the lock. This
// is currently true for Windows local files.
//
// TODO: While there is little safety in locking while deleting the
// state, it might be nice to be able to coordinate processes around
// state deletion, i.e. in a CI environment. Adding Delete() as a
// required method of States would allow the removal of the resource to
// be delegated from the Backend to the State itself.
stateLocker.Unlock()
err = b.DeleteWorkspace(workspace, force)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
c.Ui.Output(
c.Colorize().Color(
fmt.Sprintf(envDeleted, workspace),
),
)
if hasResources {
c.Ui.Output(
c.Colorize().Color(
fmt.Sprintf(envWarnNotEmpty, workspace),
),
)
}
return 0
}
func (c *WorkspaceDeleteCommand) AutocompleteArgs() complete.Predictor {
return completePredictSequence{
c.completePredictWorkspaceName(),
complete.PredictDirs(""),
}
}
func (c *WorkspaceDeleteCommand) AutocompleteFlags() complete.Flags {
return complete.Flags{
"-force": complete.PredictNothing,
}
}
func (c *WorkspaceDeleteCommand) Help() string {
helpText := `
Usage: terraform [global options] workspace delete [OPTIONS] NAME
Delete a Terraform workspace
Options:
-force Remove a workspace even if it is managing resources.
Terraform can no longer track or manage the workspace's
infrastructure.
-lock=false Don't hold a state lock during the operation. This is
dangerous if others might concurrently run commands
against the same workspace.
-lock-timeout=0s Duration to retry a state lock.
`
return strings.TrimSpace(helpText)
}
func (c *WorkspaceDeleteCommand) Synopsis() string {
return "Delete a workspace"
}