hashicorp/terraform · error
Error selecting workspace
Error message
Error selecting workspace: %s
What it means
Thrown when c.Workspace() returns an error during init after a backend is initialized/available. Workspace() resolves the active workspace (from TF_WORKSPACE env, .terraform/environment, or CLI selection) and can fail if the metadata file is unreadable or the selected workspace is invalid.
Solutions
- Inspect .terraform/environment: it should contain a valid workspace name (or be absent).
- Run `terraform workspace select default` (or a valid workspace) to reset the active workspace.
- Remove a corrupted .terraform/environment file and re-run init.
Example fix
$ terraform workspace select default && terraform init
Defensive patterns
Strategy: validation
Validate before calling
// Validate the active workspace marker before init.
func validWorkspace() error {
b, err := os.ReadFile(".terraform/environment")
if err != nil { return nil } // absent is fine
name := strings.TrimSpace(string(b))
if name == "" { return errors.New("empty workspace marker") }
return nil
} Prevention
- Run `terraform workspace select <name>` before init to ensure a valid workspace.
- Delete corrupted .terraform/environment files.
- Avoid switching branches that leave stale workspace markers.
When it happens
Trigger: Backend is configured but the workspace cannot be resolved: corrupted .terraform/environment file, invalid workspace name, or workspace selection logic fails.
Common situations: .terraform/environment contains an invalid/removed workspace name; stale state from switching branches; permission error reading the environment marker file.
Related errors
- Error loading state
- Error refreshing state
- Failed to load state manager
- backendDiags.Err()
- default state is not allowed to be deleted
AI-assisted analysis of hashicorp/terraform@d32a084675 (2026-08-11).
Data as JSON: /api/errors/4dab76f87adddee3.
Report an issue: GitHub.
Appendix: source
Thrown at internal/command/init_run.go:316
return 1
}
}
providerHook := &providerPolicyHook{
client: policyClient,
view: view,
rootModule: rootModEarly,
}
var state *states.State
// If we have a functional backend (either just initialized or initialized
// on a previous run) we'll use the current state as a potential source
// of provider dependencies.
if back != nil {
c.ignoreRemoteVersionConflict(back)
workspace, err := c.Workspace()
if err != nil {
diags = diags.Append(fmt.Errorf("Error selecting workspace: %s", err))
view.Diagnostics(diags)
return 1
}
sMgr, sDiags := back.StateMgr(workspace)
if sDiags.HasErrors() {
diags = diags.Append(fmt.Errorf("Error loading state: %s", sDiags.Err()))
view.Diagnostics(diags)
return 1
}
if err := sMgr.RefreshState(); err != nil {
diags = diags.Append(fmt.Errorf("Error refreshing state: %s", err))
view.Diagnostics(diags)
return 1
}
state = sMgr.State()
}View on GitHub (pinned to d32a084675)