-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New Terraform Workspace subcommand: selectornew
This adds the new terraform workspace subcommand. This command is intended to make managing workspaces easier in CI environments where auto creating or selecting a workspace is useful.
- Loading branch information
1 parent
2aff678
commit 8abd500
Showing
4 changed files
with
377 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,231 @@ | ||
package command | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"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/statefile" | ||
"github.com/hashicorp/terraform/internal/tfdiags" | ||
"github.com/mitchellh/cli" | ||
"github.com/posener/complete" | ||
) | ||
|
||
type WorkspaceSelectornewCommand struct { | ||
Meta | ||
LegacyName bool | ||
} | ||
|
||
func (c *WorkspaceSelectornewCommand) 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 selectornew") | ||
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 | ||
} | ||
|
||
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 | ||
} | ||
|
||
current, isOverridden := c.WorkspaceOverridden() | ||
if isOverridden { | ||
c.Ui.Error(envIsOverriddenSelectError) | ||
return 1 | ||
} | ||
|
||
// Load the backend | ||
b, backendDiags := c.Backend(&BackendOpts{ | ||
Config: backendConfig, | ||
}) | ||
diags = diags.Append(backendDiags) | ||
if backendDiags.HasErrors() { | ||
c.showDiagnostics(diags) | ||
return 1 | ||
} | ||
|
||
if err != nil { | ||
c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err)) | ||
return 1 | ||
} | ||
|
||
// This command will not write state | ||
c.ignoreRemoteVersionConflict(b) | ||
|
||
workspace := args[0] | ||
if !validWorkspaceName(workspace) { | ||
c.Ui.Error(fmt.Sprintf(envInvalidName, workspace)) | ||
return 1 | ||
} | ||
|
||
states, err := b.Workspaces() | ||
if err != nil { | ||
c.Ui.Error(err.Error()) | ||
return 1 | ||
} | ||
|
||
if workspace == current { | ||
// already using this workspace | ||
return 0 | ||
} | ||
|
||
found := false | ||
for _, s := range states { | ||
if workspace == s { | ||
found = true | ||
break | ||
} | ||
} | ||
|
||
if !found { | ||
c.Colorize().Color(fmt.Sprintf(envDoesNotExist, workspace)) | ||
|
||
_, 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 | ||
} | ||
|
||
err = c.SetWorkspace(workspace) | ||
if err != nil { | ||
c.Ui.Error(err.Error()) | ||
return 1 | ||
} | ||
|
||
c.Ui.Output( | ||
c.Colorize().Color( | ||
fmt.Sprintf(envChanged, workspace), | ||
), | ||
) | ||
|
||
return 0 | ||
} | ||
|
||
func (c *WorkspaceSelectornewCommand) AutocompleteArgs() complete.Predictor { | ||
return completePredictSequence{ | ||
c.completePredictWorkspaceName(), | ||
complete.PredictDirs(""), | ||
} | ||
} | ||
|
||
func (c *WorkspaceSelectornewCommand) AutocompleteFlags() complete.Flags { | ||
return complete.Flags{ | ||
"-state": complete.PredictFiles("*.tfstate"), | ||
} | ||
} | ||
|
||
func (c *WorkspaceSelectornewCommand) Help() string { | ||
helpText := ` | ||
Usage: terraform [global options] workspace selectornew [OPTIONS] NAME | ||
Select a different Terraform workspace or create if it does not exist. | ||
Options: | ||
-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. | ||
-state=path Copy an existing state file into the new workspace. | ||
` | ||
return strings.TrimSpace(helpText) | ||
} | ||
|
||
func (c *WorkspaceSelectornewCommand) Synopsis() string { | ||
return "Select or create a workspace" | ||
} |