Introduction
When running Terraform CLI with multiple workspaces, the terraform init
command will prompt to select a workspace, like so:
$ terraform init
Initializing the backend...
Successfully configured the backend "remote"! Terraform will automatically
use this backend unless the backend configuration changes.
The currently selected workspace (default) does not exist.
This is expected behavior when the selected workspace did not have an
existing non-empty state. Please enter a number to select a workspace:
1. aaa
2. bar
3. foo
4. zzz
Enter a value:
An automation workflow requires that the workspace be already selected and the prompt bypassed. Described below are two options that allow you to configure the selection of a specific workspace for automation with Terraform.
Use Case
Option 1: TF_WORKSPACE Environment Variable
1) Set the TF_WORKSPACE
environment variable to the workspace name you wish to be selected
`export TF_WORKSPACE="one"`
NOTE: If you are using the workspace prefix configuration in your Terraform code (for the remote backend), you will need to set this value to be the portion after the prefix.
For example, with the following Terraform remote backend configuration:
terraform {
backend "remote" {
hostname = "app.terraform.io"
organization = "test-organization"
workspaces {
prefix = "prefix-"
}
}
}
Running terraform workspace list
with TF_WORKSPACE
set to one
(full workspace name is prefix-one
) will produce the following result:
$ terraform workspace list
012
012-new
* one
two
Option 2: Manually populate the .terraform/environment file with workspace name
1) Remove the .terraform
directory:
`rm -rf .terraform`
2) Recreate an empty .terraform
directory:
`mkdir .terraform`
3) Create a file name .terraform/environment
with the workspace name inside:
`printf '%s' foo > .terraform/environment`
By entering the workspace name in the environment
file, you have configured Terraform with this workspace selected. terraform init
will now run without the prompt to select a workspace:
$ terraform init
Initializing the backend...
Successfully configured the backend "remote"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "null" (terraform-providers/null) 2.1.2...
The following providers do not have any version constraints in configuration,
so the latest version was installed.
To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = "..." constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.
* provider.null: version = "~> 2.1"
Terraform has been successfully initialized!
$ terraform workspace list
aaa
bar
* foo
zzz