Terraform Cloud offers a few options to select a workspace, ranging from prefix, tags to standard name. Workspace selection pattern plays a critical role in a good project configuration. As it enforces a standard across the wide projects.
In this blog post, I’ll be covering the three options to configure your workspace in Terraform with pros/cons of each.
1. Prefix
Workspace prefixes are great to use when you have multiple environments and the workspaces in the Terraform cloud follow a fixed pattern
In the example, we have the prefix “main-app-” which means
terraform { backend "remote" { hostname = "app.terraform.io" workspaces { prefix = "main-app-" } } }
To select the correct workspace we can utilise the Terraform environment variable TF_WORKSPACE
export TF_WORKSPACE=dev
Using prefix is highly recommended compared to tags as it enforces a naming convention
2. Tags
The other approach is to utilise tags. This might sound great and easy to use, however I highly discourage it! Tags can become complicated and difficult to manage.
terraform { cloud { organization = "infinitypp" workspaces { tags = ["networking", "dev] } } }
3. Workspace name
Workspace names are the default approach in selecting a workspace. This is a great approach and it’s great for small projects where multiple environments do not exist.
terraform { cloud { organization = "infinitypp" workspaces { name = "main-app-dev" } } }
Pros and Cons of each method
Pattern | Advantages | Disadvantages |
---|---|---|
Prefix | Enforce a naming convention | Slightly difficult to understand |
Tags | Great when there is a strict tag collection library | Can become extremely difficult in large size projects |
Workspace name | Clear and easy to understand | Slightly inconvenient as you have to store large workspace names in your config file |
Summary
In my past experience, using prefix is the way to go. It is easy on day to day operation as workspaces is a resource which you might create quiet often in the beginning of a project, and having a naming standard enforce across your projects is a great practice.
Keep in mind, to create your Terraform workspace via IaC.
How to create Terraform Workspaces through code?
resource "tfe_organization" "organization" { name = "my-org-name" email = "[email protected]" } variable "environments" { type = list(string) default = ["dev", "prod"] } resource "tfe_workspace" "main_app" { for_each = toset(var.environments) name = "main-app-${each.value}" organization = tfe_organization.organization.name }
The above code enforces a naming standard and creates two workspaces:
- main-app-dev
- main-app-prod
We are using the for_each function to loop through the environment list. This makes it easier to add a new environment.