Terraform: Workspace variables

Steven Burrows
2 min readAug 17, 2019

--

I was recently working on a project that required 7 different staging environments all with some unique variables required within the deploy. While you can use .tfvars to and load them each workspace var file using terraform plan -var-file="var/$(terraform workspace show).tfvars" , I wanted to find a more automated solution.

Terraform v0.12.2 introduced to ability to use YAML files. By using terraform locals, yamlencode, and yamldecode we can configure our project to load a default variables file and override with a workspace variable file.

To keep things simple in this post, we will just work with two environment files, dev, and production. That would make the project file structure look something like the following:

├── config.yaml
├── main.tf
└── workspaces
├── dev.yaml
└── production.yaml

Terraform file:

locals {
workspace_path = "./workspaces/${terraform.workspace}.yaml"
defaults = file("${path.module}/config.yaml")
workspace = fileexists(local.workspace_path) ? file(local.workspace_path) : yamlencode({}) settings = merge(
yamldecode(local.defaults),
yamldecode(local.workspace)
)
}
output "project_settings" {
value = local.settings
}

The “locals” block will load a default file and a workspace file (if it exists) and then merge them together. This exposes local.settings to be used in the rest of the terraform module. We are now ready to try this out. By running the terraform in each respective workspace we would get the following results.

terraform workspace select dev
terraform apply
Outputs:project_settings = {
"instance_size" = "t2.medium"
"project_name" = "dev-example"
}
terraform workspace select production
terraform apply
Outputs:project_settings = {
"instance_size" = "t2.xlarge"
"project_name" = "example"
}

As you can see from the outputs of each, the variables are unique for each workspace, without having to specify which file to load in the CLI command.

I hope you find this useful! If you have any problems feel free to leave them in the comments below. The whole code can also be found on my Github.

--

--

Steven Burrows

Full Stack Developer. I love experimenting with new tools and tech!