Many people I know use the popular Terraform provided variable terraform.workspace
or powerful -var-file=...
command line flag to switch variable values based on environment/workspace.
However, in Terraform Cloud (TFC) / Terraform Enterprise (TFE), the value of terraform.workspace
will always evaluate to default
and you cannot provide a var file to the command line (sort of). This is a problem for many as they migrate to these remote backends, as it messes up their current workflow.
Even though some of the functionality has changed between open source and TFC/TFE, there are ways to mimick the capabilities you may be used to. Below will outline how one can go about configuring the backend and selecting the workspace of choice, while each example's README.md
will go through how to supply variables based on the workspace that was chosen.
In order to tell the backend to switch between workspaces, you can use the workspaces.prefix
attribute.
terraform {
required_version = "~> 0.12"
backend "remote" {
hostname = "app.terraform.io" # use your host if self hosted
organization = "company" # use your organization
workspaces {
prefix = "my-app-" # <-- the magic, use your workspace prefix
}
}
}
There are two main approaches to selecting a workspace in TFC/TFE.
The first being in interactive mode. This is normally done when a user is present and needing to interact with the console, such as on your local machine. You can use the built in terraform workspace select
command to select the proper workspace.
$ terraform workspace select test
The second approach may be when Terraform is ran in some automated fashion, such as your CI/CD pipeline. You can leverage the TF_WORKSPACE
environment variable to select the proper workspace.
$ export TF_WORKSPACE=test
Ultimately, there are endless possibilities to solve the problem from above. But the examples listed below are some of the approaches I find worthy of mentioning and are ordered by my personal preference.
Note: For demonstration purposes, each example will assume that there are two workspaces:
test
&prod
.
- cli-tfvars
- decode config
- locals-v1
- locals-v2
- var-defaults
- tfc-gui