/
workspace_new.go
203 lines (167 loc) · 4.62 KB
/
workspace_new.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
package command
import (
"fmt"
"os"
"strings"
"time"
"github.com/hashicorp/terraform/command/arguments"
"github.com/hashicorp/terraform/command/clistate"
"github.com/hashicorp/terraform/command/views"
"github.com/hashicorp/terraform/states/statefile"
"github.com/hashicorp/terraform/tfdiags"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
type WorkspaceNewCommand struct {
Meta
LegacyName bool
}
func (c *WorkspaceNewCommand) Run(args []string) int {
args = c.Meta.process(args)
envCommandShowWarning(c.Ui, c.LegacyName)
var stateLock bool
var stateLockTimeout time.Duration
var statePath string
cmdFlags := c.Meta.defaultFlagSet("workspace new")
cmdFlags.BoolVar(&stateLock, "lock", true, "lock state")
cmdFlags.DurationVar(&stateLockTimeout, "lock-timeout", 0, "lock timeout")
cmdFlags.StringVar(&statePath, "state", "", "terraform state file")
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
}
workspace := args[0]
if !validWorkspaceName(workspace) {
c.Ui.Error(fmt.Sprintf(envInvalidName, workspace))
return 1
}
// You can't ask to create a workspace when you're overriding the
// workspace name to be something different.
if current, isOverridden := c.WorkspaceOverridden(); current != workspace && isOverridden {
c.Ui.Error(envIsOverriddenNewError)
return 1
}
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.ignoreRemoteBackendVersionConflict(b)
workspaces, err := b.Workspaces()
if err != nil {
c.Ui.Error(fmt.Sprintf("Failed to get configured named states: %s", err))
return 1
}
for _, ws := range workspaces {
if workspace == ws {
c.Ui.Error(fmt.Sprintf(envExists, workspace))
return 1
}
}
_, err = b.StateMgr(workspace)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
// now set the current workspace locally
if err := c.SetWorkspace(workspace); err != nil {
c.Ui.Error(fmt.Sprintf("Error selecting new workspace: %s", err))
return 1
}
c.Ui.Output(c.Colorize().Color(fmt.Sprintf(
strings.TrimSpace(envCreated), workspace)))
if statePath == "" {
// if we're not loading a state, then we're done
return 0
}
// load the new Backend state
stateMgr, err := b.StateMgr(workspace)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
if stateLock {
stateLocker := clistate.NewLocker(c.stateLockTimeout, views.NewStateLocker(arguments.ViewHuman, c.View))
if diags := stateLocker.Lock(stateMgr, "workspace-new"); diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}
defer func() {
if diags := stateLocker.Unlock(); diags.HasErrors() {
c.showDiagnostics(diags)
}
}()
}
// read the existing state file
f, err := os.Open(statePath)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
stateFile, err := statefile.Read(f)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
// save the existing state in the new Backend.
err = stateMgr.WriteState(stateFile.State)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
err = stateMgr.PersistState()
if err != nil {
c.Ui.Error(err.Error())
return 1
}
return 0
}
func (c *WorkspaceNewCommand) AutocompleteArgs() complete.Predictor {
return completePredictSequence{
complete.PredictNothing, // the "new" subcommand itself (already matched)
complete.PredictAnything,
complete.PredictDirs(""),
}
}
func (c *WorkspaceNewCommand) AutocompleteFlags() complete.Flags {
return complete.Flags{
"-state": complete.PredictFiles("*.tfstate"),
}
}
func (c *WorkspaceNewCommand) Help() string {
helpText := `
Usage: terraform [global options] workspace new [OPTIONS] NAME
Create a new Terraform workspace.
Options:
-lock=true Lock the state file when locking is supported.
-lock-timeout=0s Duration to retry a state lock.
-state=path Copy an existing state file into the new workspace.
`
return strings.TrimSpace(helpText)
}
func (c *WorkspaceNewCommand) Synopsis() string {
return "Create a new workspace"
}